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
652670d00874828c363db803e84245d16211f84d
Search_api
Issue #1697246 by drunken monkey: Added "Parse mode" option to views.
a
https://github.com/lucidworks/drupal_search_api
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index a15d7d31..c0766e0a 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,6 @@ Search API 1.x, dev (xx/xx/xxxx): --------------------------------- +- #1697246 by drunken monkey: Added 'Parse mode' option to views. - #1993536 by drunken monkey, jpieck: Fixed handling of empty values in processors. - #1992228 by drunken monkey: Fixed current search block for empty keys. diff --git a/contrib/search_api_views/README.txt b/contrib/search_api_views/README.txt index c08d8bf8..e92f3ef3 100644 --- a/contrib/search_api_views/README.txt +++ b/contrib/search_api_views/README.txt @@ -95,6 +95,18 @@ settings ensuring that only when the index isn't up-to-date items will be filtered out this way. This option is only available for indexes on entity types. +Other features +-------------- +- Change parse mode +You can determine how search keys entered by the user will be parsed by going to +"Advanced" > "Query settings" within your View's settings. "Direct" can be +useful, e.g., when you want to give users the full power of Solr. In other +cases, "Multiple terms" is usually what you want / what users expect. +Caution: For letting users use fulltext searches, always use the "Search: +Fulltext search" filter or contextual filter – using a normal filter on a +fulltext field won't parse the search keys, which means multiple words will only +be found when they appear as that exact phrase. + FAQ: Why „*Indexed* Node“? -------------------------- The group name used for the search result itself (in fields, filters, etc.) is diff --git a/contrib/search_api_views/includes/handler_argument_fulltext.inc b/contrib/search_api_views/includes/handler_argument_fulltext.inc index 2d7311d6..684df287 100644 --- a/contrib/search_api_views/includes/handler_argument_fulltext.inc +++ b/contrib/search_api_views/includes/handler_argument_fulltext.inc @@ -20,6 +20,8 @@ class SearchApiViewsHandlerArgumentFulltext extends SearchApiViewsHandlerArgumen public function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); + $form['help']['#markup'] = t('Note: You can change how search keys are parsed under "Advanced" > "Query settings".'); + $fields = $this->getFulltextFields(); if (!empty($fields)) { $form['fields'] = array( diff --git a/contrib/search_api_views/includes/handler_filter_fulltext.inc b/contrib/search_api_views/includes/handler_filter_fulltext.inc index b7f2e1e8..403d0e36 100644 --- a/contrib/search_api_views/includes/handler_filter_fulltext.inc +++ b/contrib/search_api_views/includes/handler_filter_fulltext.inc @@ -27,7 +27,7 @@ class SearchApiViewsHandlerFilterFulltext extends SearchApiViewsHandlerFilterTex '#title' => t('Use as'), '#type' => 'radios', '#options' => array( - 'keys' => t('Search keys – multiple words will be split and the filter will influence relevance.'), + 'keys' => t('Search keys – multiple words will be split and the filter will influence relevance. You can change how search keys are parsed under "Advanced" > "Query settings".'), 'filter' => t("Search filter – use as a single phrase that restricts the result set but doesn't influence relevance."), ), '#default_value' => $this->options['mode'], diff --git a/contrib/search_api_views/includes/query.inc b/contrib/search_api_views/includes/query.inc index 25f00d3b..9d16ce69 100644 --- a/contrib/search_api_views/includes/query.inc +++ b/contrib/search_api_views/includes/query.inc @@ -85,7 +85,7 @@ class SearchApiViewsQuery extends views_plugin_query { $id = substr($base_table, 17); $this->index = search_api_index_load($id); $this->query = $this->index->query(array( - 'parse mode' => 'terms', + 'parse mode' => $this->options['parse_mode'], )); } } @@ -136,6 +136,9 @@ class SearchApiViewsQuery extends views_plugin_query { 'entity_access' => array( 'default' => FALSE, ), + 'parse_mode' => array( + 'default' => 'terms', + ), ); } @@ -153,6 +156,7 @@ class SearchApiViewsQuery extends views_plugin_query { '#description' => t('If the underlying search index has access checks enabled, this option allows to disable them for this view.'), '#default_value' => $this->options['search_api_bypass_access'], ); + if (entity_get_info($this->index->item_type)) { $form['entity_access'] = array( '#type' => 'checkbox', @@ -161,6 +165,27 @@ class SearchApiViewsQuery extends views_plugin_query { '#default_value' => $this->options['entity_access'], ); } + + $form['parse_mode'] = array( + '#type' => 'select', + '#title' => t('Parse mode'), + '#description' => t('Choose how the search keys will be parsed.'), + '#options' => array(), + '#default_value' => $this->options['parse_mode'], + ); + $modes = array(); + foreach ($this->query->parseModes() as $key => $mode) { + $form['parse_mode']['#options'][$key] = $mode['name']; + if (!empty($mode['description'])) { + $states['visible'][':input[name="query[options][parse_mode]"]']['value'] = $key; + $form["parse_mode_{$key}_description"] = array( + '#type' => 'item', + '#title' => $mode['name'], + '#description' => $mode['description'], + '#states' => $states, + ); + } + } } /**
33b59a403ff3d1297bc8378a4ab995aff0e6ec73
intellij-community
PY-996--
a
https://github.com/JetBrains/intellij-community
diff --git a/python/src/com/jetbrains/python/actions/AddFieldQuickFix.java b/python/src/com/jetbrains/python/actions/AddFieldQuickFix.java index e595307a13eba..68c4338e4bb8e 100644 --- a/python/src/com/jetbrains/python/actions/AddFieldQuickFix.java +++ b/python/src/com/jetbrains/python/actions/AddFieldQuickFix.java @@ -43,7 +43,7 @@ public String getFamilyName() { } @Nullable - private static PsiElement appendToInit(PyFunction init, Function<String, PyStatement> callback) { + public static PsiElement appendToInit(PyFunction init, Function<String, PyStatement> callback) { // add this field as the last stmt of the constructor final PyStatementList stmt_list = init.getStatementList(); PyStatement[] stmts = stmt_list.getStatements(); // NOTE: rather wasteful, consider iterable stmt list diff --git a/python/src/com/jetbrains/python/refactoring/introduce/PyIntroduceDialog.form b/python/src/com/jetbrains/python/refactoring/introduce/PyIntroduceDialog.form index 936b4b4f25e90..d56e5206d202b 100644 --- a/python/src/com/jetbrains/python/refactoring/introduce/PyIntroduceDialog.form +++ b/python/src/com/jetbrains/python/refactoring/introduce/PyIntroduceDialog.form @@ -110,4 +110,11 @@ </vspacer> </children> </grid> + <buttonGroups> + <group name="placeButtonGroup"> + <member id="2a16a"/> + <member id="9196d"/> + <member id="7fc5b"/> + </group> + </buttonGroups> </form> diff --git a/python/src/com/jetbrains/python/refactoring/introduce/field/FieldIntroduceHandler.java b/python/src/com/jetbrains/python/refactoring/introduce/field/FieldIntroduceHandler.java index 0bc67dd995da6..9da92cb66fa64 100644 --- a/python/src/com/jetbrains/python/refactoring/introduce/field/FieldIntroduceHandler.java +++ b/python/src/com/jetbrains/python/refactoring/introduce/field/FieldIntroduceHandler.java @@ -14,6 +14,7 @@ import com.jetbrains.python.PyNames; import com.jetbrains.python.actions.AddFieldQuickFix; import com.jetbrains.python.psi.*; +import com.jetbrains.python.psi.impl.PyFunctionBuilder; import com.jetbrains.python.refactoring.PyRefactoringUtil; import com.jetbrains.python.refactoring.introduce.IntroduceHandler; import com.jetbrains.python.refactoring.introduce.variable.VariableIntroduceHandler; @@ -74,17 +75,31 @@ protected PsiElement addDeclaration(@NotNull PsiElement expression, @NotNull Psi final PsiElement expr = expression instanceof PyClass ? expression : expression.getParent(); PsiElement anchor = PyUtil.getContainingClassOrSelf(expr); assert anchor instanceof PyClass; + final PyClass clazz = (PyClass)anchor; + final Project project = anchor.getProject(); if (initInConstructor == InitPlace.CONSTRUCTOR) { - final Project project = anchor.getProject(); - final PyClass clazz = (PyClass)anchor; - AddFieldQuickFix.addFieldToInit(project, clazz, "", new AddFieldDeclaration(declaration)); - final PyFunction init = clazz.findMethodByName(PyNames.INIT, false); - final PyStatementList statements = init != null ? init.getStatementList() : null; - return statements != null ? statements.getLastChild() : null; + return AddFieldQuickFix.addFieldToInit(project, clazz, "", new AddFieldDeclaration(declaration)); + } else if (initInConstructor == InitPlace.SET_UP) { + return addFieldToSetUp(project, clazz, declaration); } return VariableIntroduceHandler.doIntroduceVariable(expression, declaration, occurrences, replaceAll); } + @Nullable + private static PsiElement addFieldToSetUp(Project project, PyClass clazz, PsiElement declaration) { + final PyFunction init = clazz.findMethodByName(PythonUnitTestUtil.TESTCASE_SETUP_NAME, false); + if (init != null) { + return AddFieldQuickFix.appendToInit(init, new AddFieldDeclaration(declaration)); + } + final PyFunctionBuilder builder = new PyFunctionBuilder(PythonUnitTestUtil.TESTCASE_SETUP_NAME); + builder.parameter(PyNames.CANONICAL_SELF); + PyFunction setUp = builder.buildFunction(project); + final PyStatementList statements = clazz.getStatementList(); + final PsiElement anchor = statements.getFirstChild(); + setUp = (PyFunction)statements.addBefore(setUp, anchor); + return AddFieldQuickFix.appendToInit(setUp, new AddFieldDeclaration(declaration)); + } + @Override protected PyExpression createExpression(Project project, String name, PyAssignmentStatement declaration) { final String text = declaration.getText(); diff --git a/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java b/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java index 83f6b1f768b46..9e6ccb729e1f5 100644 --- a/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java +++ b/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java @@ -13,6 +13,7 @@ */ public class PythonUnitTestUtil { private static final String TESTCASE_CLASS_NAME = "TestCase"; + public static final String TESTCASE_SETUP_NAME = "setUp"; private static final String UNITTEST_FILE_NAME = "unittest.py"; private static final String TESTCASE_METHOD_PREFIX = "test";
115c6c59f5fea078d2b3000e1eef035b5f47bfcd
Vala
vapigen: Add support for base types and ranks in structs Fixes bug 605039.
a
https://github.com/GNOME/vala/
diff --git a/vala/valastruct.vala b/vala/valastruct.vala index 49177f240b..63b8b85424 100644 --- a/vala/valastruct.vala +++ b/vala/valastruct.vala @@ -403,6 +403,15 @@ public class Vala.Struct : TypeSymbol { return rank; } + /** + * Sets the rank of this integer or floating point type. + * + * @return the rank if this is an integer or floating point type + */ + public void set_rank (int rank) { + this.rank = rank; + } + private void process_ccode_attribute (Attribute a) { if (a.has_argument ("const_cname")) { set_const_cname (a.get_string ("const_cname")); diff --git a/vapigen/valagidlparser.vala b/vapigen/valagidlparser.vala index 010c82ffba..246dd18f50 100644 --- a/vapigen/valagidlparser.vala +++ b/vapigen/valagidlparser.vala @@ -425,6 +425,10 @@ public class Vala.GIdlParser : CodeVisitor { if (eval (nv[1]) == "1") { return; } + } else if (nv[0] == "base_type") { + st.base_type = parse_type_string (eval (nv[1])); + } else if (nv[0] == "rank") { + st.set_rank (eval (nv[1]).to_int ()); } else if (nv[0] == "simple_type") { if (eval (nv[1]) == "1") { st.set_simple_type (true);
81aa854e7fc6cda7ff390112c436f3644181dc81
Mylyn Reviews
Enabled opening the corresponding task for a result node
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java index 475a9279..275a43a7 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java @@ -26,6 +26,7 @@ import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; import org.eclipse.mylyn.reviews.tasks.core.internal.ITreeNode; +import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewResultNode; import org.eclipse.mylyn.reviews.tasks.core.internal.TaskNode; import org.eclipse.mylyn.reviews.tasks.ui.Images; import org.eclipse.mylyn.reviews.tasks.ui.ReviewUiUtils; @@ -162,8 +163,12 @@ public String getColumnText(Object element, int columnIndex) { public void doubleClick(DoubleClickEvent event) { if (!event.getSelection().isEmpty()) { - ITaskProperties task = ((ITreeNode) ((IStructuredSelection) event - .getSelection()).getFirstElement()).getTask(); + ITreeNode treeNode = (ITreeNode) ((IStructuredSelection) event + .getSelection()).getFirstElement(); + if(treeNode instanceof ReviewResultNode) { + treeNode = treeNode.getParent(); + } + ITaskProperties task = treeNode.getTask(); ReviewUiUtils.openTaskInMylyn(task); } }
0bc40733a748cac21657e141f841c1ee81110a59
qos-ch$logback
better test stability
p
https://github.com/qos-ch/logback
diff --git a/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java b/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java old mode 100644 new mode 100755 index 2971d7d42b..b490949b97 --- a/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java @@ -18,15 +18,16 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { ch.qos.logback.access.spi.PackageTest.class, - ch.qos.logback.access.boolex.PackageTest.class, - ch.qos.logback.access.net.PackageTest.class, - ch.qos.logback.access.pattern.PackageTest.class, - ch.qos.logback.access.joran.PackageTest.class, - ch.qos.logback.access.jetty.PackageTest.class, - ch.qos.logback.access.filter.PackageTest.class, - ch.qos.logback.access.servlet.PackageTest.class, - ch.qos.logback.access.sift.PackageTest.class }) +@SuiteClasses({ch.qos.logback.access.spi.PackageTest.class, + ch.qos.logback.access.boolex.PackageTest.class, + ch.qos.logback.access.net.PackageTest.class, + ch.qos.logback.access.db.PackageTest.class, + ch.qos.logback.access.pattern.PackageTest.class, + ch.qos.logback.access.joran.PackageTest.class, + ch.qos.logback.access.jetty.PackageTest.class, + ch.qos.logback.access.filter.PackageTest.class, + ch.qos.logback.access.servlet.PackageTest.class, + ch.qos.logback.access.sift.PackageTest.class}) public class AllAccessTest { } diff --git a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderTest.java b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTest.java old mode 100644 new mode 100755 similarity index 84% rename from logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderTest.java rename to logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTest.java index 85ff39fb15..6a5a3913ba --- a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTest.java @@ -37,23 +37,26 @@ import ch.qos.logback.core.db.DriverManagerConnectionSource; import ch.qos.logback.core.util.StatusPrinter; -public class DBAppenderTest { +public class DBAppenderHSQLTest { + static DBAppenderHSQLTestFixture DB_APPENDER_HSQL_TEST_FIXTURE; + AccessContext context; DBAppender appender; DriverManagerConnectionSource connectionSource; - static DBAppenderTestFixture DB_APPENDER_TEST_FIXTURE; - + int existingRowCount; + Statement stmt; + @BeforeClass static public void fixtureSetUp() throws SQLException { - DB_APPENDER_TEST_FIXTURE = new DBAppenderTestFixture(); - DB_APPENDER_TEST_FIXTURE.setUp(); + DB_APPENDER_HSQL_TEST_FIXTURE = new DBAppenderHSQLTestFixture(); + DB_APPENDER_HSQL_TEST_FIXTURE.setUp(); } @AfterClass static public void fixtureTearDown() throws SQLException { - DB_APPENDER_TEST_FIXTURE.tearDown(); + DB_APPENDER_HSQL_TEST_FIXTURE.tearDown(); } @Before @@ -65,17 +68,15 @@ public void setUp() throws SQLException { appender.setContext(context); connectionSource = new DriverManagerConnectionSource(); connectionSource.setContext(context); - connectionSource.setDriverClass(DBAppenderTestFixture.DRIVER_CLASS); - connectionSource.setUrl(DB_APPENDER_TEST_FIXTURE.url); - connectionSource.setUser(DB_APPENDER_TEST_FIXTURE.user); - connectionSource.setPassword(DB_APPENDER_TEST_FIXTURE.password); + connectionSource.setDriverClass(DBAppenderHSQLTestFixture.DRIVER_CLASS); + connectionSource.setUrl(DB_APPENDER_HSQL_TEST_FIXTURE.url); + connectionSource.setUser(DB_APPENDER_HSQL_TEST_FIXTURE.user); + connectionSource.setPassword(DB_APPENDER_HSQL_TEST_FIXTURE.password); connectionSource.start(); appender.setConnectionSource(connectionSource); - } - - private void setInsertHeadersAndStart(boolean insert) { - appender.setInsertHeaders(insert); - appender.start(); + + stmt = connectionSource.getConnection().createStatement(); + existingRowCount = existingRowCount(stmt); } @After @@ -83,8 +84,25 @@ public void tearDown() throws SQLException { context = null; appender = null; connectionSource = null; + stmt.close(); + } + + int existingRowCount(Statement stmt) throws SQLException { + ResultSet rs = stmt.executeQuery("SELECT count(*) FROM access_event"); + int result = -1; + if (rs.next()) { + result = rs.getInt(1); + } + rs.close(); + return result; } + private void setInsertHeadersAndStart(boolean insert) { + appender.setInsertHeaders(insert); + appender.start(); + } + + @Test public void testAppendAccessEvent() throws SQLException { setInsertHeadersAndStart(false); @@ -94,7 +112,7 @@ public void testAppendAccessEvent() throws SQLException { Statement stmt = connectionSource.getConnection().createStatement(); ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM access_event"); + rs = stmt.executeQuery("SELECT * FROM access_event where EVENT_ID = "+ existingRowCount); if (rs.next()) { assertEquals(event.getTimeStamp(), rs.getLong(1)); assertEquals(event.getRequestURI(), rs.getString(2)); @@ -109,7 +127,6 @@ public void testAppendAccessEvent() throws SQLException { } else { fail("No row was inserted in the database"); } - rs.close(); stmt.close(); } diff --git a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderTestFixture.java b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTestFixture.java old mode 100644 new mode 100755 similarity index 98% rename from logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderTestFixture.java rename to logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTestFixture.java index 5e5d8527b7..b70420a3ed --- a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderTestFixture.java +++ b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTestFixture.java @@ -20,7 +20,7 @@ import org.hsqldb.Server; -public class DBAppenderTestFixture { +public class DBAppenderHSQLTestFixture { public static final String DRIVER_CLASS = "org.hsqldb.jdbcDriver"; String serverProps; diff --git a/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java old mode 100644 new mode 100755 index 3bdf629120..a38f5f86a5 --- a/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java @@ -19,7 +19,7 @@ public class PackageTest extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTest(new JUnit4TestAdapter(DBAppenderTest.class)); + suite.addTest(new JUnit4TestAdapter(DBAppenderHSQLTest.class)); suite.addTest(new JUnit4TestAdapter(DBAppenderIntegrationTest.class)); return suite; } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java old mode 100644 new mode 100755 index 4bbf41788f..de2b59fcbd --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java @@ -13,7 +13,9 @@ */ package ch.qos.logback.classic.net; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.util.concurrent.TimeUnit; import javax.mail.MessagingException; @@ -32,7 +34,6 @@ import ch.qos.logback.classic.html.XHTMLEntityResolver; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.Layout; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.testUtil.RandomUtil; @@ -48,7 +49,7 @@ public class SMTPAppender_GreenTest { static boolean SYNCHRONOUS = false; static boolean ASYNCHRONOUS = true; static int port = RandomUtil.getRandomServerPort(); - static GreenMail GREEN_MAIL_SERVER; + static GreenMail greenMailServer; SMTPAppender smtpAppender; LoggerContext lc = new LoggerContext(); @@ -63,23 +64,20 @@ public class SMTPAppender_GreenTest { int oldCount; - @BeforeClass - public static void beforeClass() throws Exception { + @Before + public void setUp() throws Exception { ServerSetup serverSetup = new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP); - GREEN_MAIL_SERVER = new GreenMail(serverSetup); - GREEN_MAIL_SERVER.start(); - } + greenMailServer = new GreenMail(serverSetup); + greenMailServer.start(); - @Before - public void setUp() throws Exception { MDC.clear(); oldCount = messageCount(); } - @AfterClass - public static void tearDown() throws Exception { - GREEN_MAIL_SERVER.stop(); + @After + public void tearDown() throws Exception { + greenMailServer.stop(); } void buildSMTPAppender(boolean synchronicity) throws Exception { @@ -117,14 +115,14 @@ private Layout<ILoggingEvent> buildHTMLLayout(LoggerContext lc) { } private int messageCount() throws MessagingException, IOException { - MimeMessage[] mma = GREEN_MAIL_SERVER.getReceivedMessages(); + MimeMessage[] mma = greenMailServer.getReceivedMessages(); assertNotNull(mma); return mma.length; } private MimeMultipart verify(String subject) throws MessagingException, IOException { - MimeMessage[] mma = GREEN_MAIL_SERVER.getReceivedMessages(); + MimeMessage[] mma = greenMailServer.getReceivedMessages(); assertNotNull(mma); assertEquals(oldCount + 1, mma.length); MimeMessage mm = mma[oldCount]; @@ -195,13 +193,14 @@ public void LBCLASSIC_104() throws Exception { smtpAppender.start(); logger.addAppender(smtpAppender); MDC.put("key", "val"); - logger.debug("hello"); + logger.debug("LBCLASSIC_104"); MDC.clear(); logger.error("en error", new Exception("an exception")); MimeMultipart mp = verify(TEST_SUBJECT); String body = GreenMailUtil.getBody(mp.getBodyPart(0)); assertTrue(body.startsWith(HEADER.trim())); + System.out.println(body); assertTrue(body.contains("key=val")); assertTrue(body.endsWith(FOOTER.trim())); } @@ -213,7 +212,7 @@ public void html() throws Exception { smtpAppender.setLayout(buildHTMLLayout(lc)); smtpAppender.start(); logger.addAppender(smtpAppender); - logger.debug("hello"); + logger.debug("html"); logger.error("en error", new Exception("an exception")); MimeMultipart mp = verify(TEST_SUBJECT); @@ -226,6 +225,17 @@ public void html() throws Exception { } + private byte[] getAsByteArray(InputStream inputStream) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + byte[] buffer = new byte[1024]; + int n = -1; + while((n = inputStream.read(buffer)) != -1) { + baos.write(buffer, 0, n); + } + return baos.toByteArray(); + } + private void configure(String file) throws JoranException { JoranConfigurator jc = new JoranConfigurator(); jc.setContext(lc); @@ -274,7 +284,7 @@ public void testMultipleTo() throws Exception { logger.debug("hello"); logger.error("en error", new Exception("an exception")); - MimeMessage[] mma = GREEN_MAIL_SERVER.getReceivedMessages(); + MimeMessage[] mma = greenMailServer.getReceivedMessages(); assertNotNull(mma); assertEquals(oldCount+3, mma.length); } @@ -296,7 +306,7 @@ public void bufferShouldBeResetBetweenMessages() throws Exception { waitUntilEmailIsSent(); - MimeMessage[] mma = GREEN_MAIL_SERVER.getReceivedMessages(); + MimeMessage[] mma = greenMailServer.getReceivedMessages(); assertNotNull(mma); assertEquals(oldCount+2, mma.length); diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java old mode 100644 new mode 100755 index 56a822c919..33e6c79e46 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java @@ -301,6 +301,7 @@ public double directLoop(ReconfigureOnChangeFilter rocf) { return (end - start) / (1.0d * LOOP_LEN); } + @Ignore @Test public void indirectPerfTest() throws MalformedURLException { if (Env.isLinux()) {
db1599cb657d598ef7d4a56e682dfea201aadd57
restlet-framework-java
- Updated Jetty to version 6.1.15--
p
https://github.com/restlet/restlet-framework-java
diff --git a/build/tmpl/eclipse/dictionary.xml b/build/tmpl/eclipse/dictionary.xml index 6f3370400b..b11df09131 100644 --- a/build/tmpl/eclipse/dictionary.xml +++ b/build/tmpl/eclipse/dictionary.xml @@ -24,3 +24,4 @@ thierry boileau callback chunked +jetty diff --git a/modules/org.restlet.ext.jetty_6.1/src/org/restlet/ext/jetty/JettyServerHelper.java b/modules/org.restlet.ext.jetty_6.1/src/org/restlet/ext/jetty/JettyServerHelper.java index f104e6d12f..10672b69ad 100644 --- a/modules/org.restlet.ext.jetty_6.1/src/org/restlet/ext/jetty/JettyServerHelper.java +++ b/modules/org.restlet.ext.jetty_6.1/src/org/restlet/ext/jetty/JettyServerHelper.java @@ -34,7 +34,7 @@ import org.mortbay.jetty.AbstractConnector; import org.mortbay.jetty.HttpConnection; import org.mortbay.jetty.Server; -import org.mortbay.thread.BoundedThreadPool; +import org.mortbay.thread.QueuedThreadPool; /** * Abstract Jetty Web server connector. Here is the list of parameters that are @@ -194,7 +194,7 @@ public JettyServerHelper(org.restlet.Server server) { this.wrappedServer = new WrappedServer(this); // Configuring the thread pool - final BoundedThreadPool btp = new BoundedThreadPool(); + final QueuedThreadPool btp = new QueuedThreadPool(); btp.setLowThreads(getLowThreads()); btp.setMaxIdleTimeMs(getThreadMaxIdleTimeMs()); btp.setMaxThreads(getMaxThreads()); @@ -292,8 +292,8 @@ public int getLowResourceMaxIdleTimeMs() { * considered as running low on resources. */ public int getLowThreads() { - return Integer.parseInt(getHelpedParameters().getFirstValue("lowThreads", - "25")); + return Integer.parseInt(getHelpedParameters().getFirstValue( + "lowThreads", "25")); } /** @@ -302,8 +302,8 @@ public int getLowThreads() { * @return The maximum threads that will service requests. */ public int getMaxThreads() { - return Integer.parseInt(getHelpedParameters().getFirstValue("maxThreads", - "255")); + return Integer.parseInt(getHelpedParameters().getFirstValue( + "maxThreads", "255")); } /** @@ -312,8 +312,8 @@ public int getMaxThreads() { * @return The minimum threads waiting to service requests. */ public int getMinThreads() { - return Integer.parseInt(getHelpedParameters() - .getFirstValue("minThreads", "1")); + return Integer.parseInt(getHelpedParameters().getFirstValue( + "minThreads", "1")); } /** @@ -342,8 +342,8 @@ public int getResponseBufferSize() { * @return The SO linger time (see Jetty 6 documentation). */ public int getSoLingerTime() { - return Integer.parseInt(getHelpedParameters().getFirstValue("soLingerTime", - "1000")); + return Integer.parseInt(getHelpedParameters().getFirstValue( + "soLingerTime", "1000")); } /**
4c68481e3ec68e29df6b54d90a80c985729fafa0
isa-tools$isacreator
Extracted common functionality for user creation to super class, added icons for GS user registration
p
https://github.com/isa-tools/isacreator
diff --git a/src/main/java/org/isatools/isacreator/gui/menu/CreateProfileMenu.java b/src/main/java/org/isatools/isacreator/gui/menu/CreateProfileMenu.java index b02996bd..1cd7493d 100644 --- a/src/main/java/org/isatools/isacreator/gui/menu/CreateProfileMenu.java +++ b/src/main/java/org/isatools/isacreator/gui/menu/CreateProfileMenu.java @@ -60,10 +60,9 @@ The ISA Team and the ISA software suite have been funded by the EU Carcinogenomi public class CreateProfileMenu extends UserCreationMenu { @InjectedResource - private ImageIcon createProfileButton, createProfileButtonOver, - backButtonSml, backButtonSmlOver; + private ImageIcon createProfileButton, createProfileButtonOver; - private JLabel back, createProfile; + private JLabel createProfile; private JTextField firstnameVal; private JTextField institutionVal; @@ -125,23 +124,7 @@ public void actionPerformed(ActionEvent e) { JPanel buttonContainer = new JPanel(new BorderLayout()); - back = new JLabel(backButtonSml, - JLabel.LEFT); - back.addMouseListener(new MouseAdapter() { - - public void mousePressed(MouseEvent event) { - back.setIcon(backButtonSml); - menu.changeView(menu.getAuthenticationGUI()); - } - - public void mouseEntered(MouseEvent event) { - back.setIcon(backButtonSmlOver); - } - - public void mouseExited(MouseEvent event) { - back.setIcon(backButtonSml); - } - }); + createBackJLabel(); buttonContainer.add(back, BorderLayout.WEST); @@ -184,6 +167,8 @@ public void mouseExited(MouseEvent event) { add(northPanel, BorderLayout.CENTER); } + + private JPanel createInstitutionPanel(Action createProfileAction) { // institution JPanel institutionCont = createPanel(); diff --git a/src/main/java/org/isatools/isacreator/gui/menu/UserCreationMenu.java b/src/main/java/org/isatools/isacreator/gui/menu/UserCreationMenu.java index 5779257c..b1fbd70b 100644 --- a/src/main/java/org/isatools/isacreator/gui/menu/UserCreationMenu.java +++ b/src/main/java/org/isatools/isacreator/gui/menu/UserCreationMenu.java @@ -2,8 +2,11 @@ import org.isatools.isacreator.common.UIHelper; import org.isatools.isacreator.effects.components.RoundedJPasswordField; +import org.jdesktop.fuse.InjectedResource; import javax.swing.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; /** * Created by the ISATeam. @@ -15,7 +18,10 @@ */ public abstract class UserCreationMenu extends MenuUIComponent { - protected JLabel status; + @InjectedResource + public ImageIcon backButtonSml, backButtonSmlOver; + + protected JLabel status, back; protected JTextField emailVal; protected JPasswordField passwordVal; protected JPasswordField confirmPasswordVal; @@ -76,6 +82,26 @@ protected JPanel createUsernamePanel(Action createProfileAction) { return userNameCont; } + protected void createBackJLabel() { + back = new JLabel(backButtonSml, + JLabel.LEFT); + back.addMouseListener(new MouseAdapter() { + + public void mousePressed(MouseEvent event) { + back.setIcon(backButtonSml); + menu.changeView(menu.getAuthenticationGUI()); + } + + public void mouseEntered(MouseEvent event) { + back.setIcon(backButtonSmlOver); + } + + public void mouseExited(MouseEvent event) { + back.setIcon(backButtonSml); + } + }); + } + protected void assignKeyActionToComponent(Action action, JComponent field) { field.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "CREATE_PROFILE"); field.getActionMap().put("CREATE_PROFILE", action); diff --git a/src/main/resources/dependency-injections/gui-package.properties b/src/main/resources/dependency-injections/gui-package.properties index 488721fd..874c9013 100644 --- a/src/main/resources/dependency-injections/gui-package.properties +++ b/src/main/resources/dependency-injections/gui-package.properties @@ -97,7 +97,7 @@ SaveAsDialog.closeButtonOver={AddStudyDialog.closeButtonOver} SaveAsDialog.saveSubmission=/images/gui/savesubmission.png SaveAsDialog.saveSubmissionOver=/images/gui/savesubmission_over.png -# MenuUIComponent images. This class is extended by AuthenticationMenu, CreateISATabMenu, CreateProfie, +# MenuUIComponent images. This class is extended by AuthenticationMenu, CreateISATabMenu, CreateProfile, # ImportConfigurationMenu, ImportFilesMenu & MainMenu MenuUIComponent.backButton={CreateProfileMenu.backButtonSml} MenuUIComponent.backButtonOver={CreateProfileMenu.backButtonSmlOver} @@ -125,10 +125,16 @@ GSAuthenticationMenu.genomespacelogo=/images/gs/genomespacelogo.png GSAuthenticationMenu.ssoIcon=/images/gs/sso.png GSAuthenticationMenu.ssoOverIcon=/images/gs/sso_over.png +UserCreationMenu.backButtonSml=/images/gui/menu_new/back_sml.png +UserCreationMenu.backButtonSmlOver=/images/gui/menu_new/back_sml_over.png + CreateProfileMenu.createProfileButton={AuthenticationMenu.createProfileButton} CreateProfileMenu.createProfileButtonOver={AuthenticationMenu.createProfileButtonOver} -CreateProfileMenu.backButtonSml=/images/gui/menu_new/back_sml.png -CreateProfileMenu.backButtonSmlOver=/images/gui/menu_new/back_sml_over.png +CreateProfileMenu.backButtonSml={UserCreationMenu.backButtonSml} +CreateProfileMenu.backButtonSmlOver={UserCreationMenu.backButtonSmlOver} + +GSRegistrationMenu.registerIcon={GSAuthenticationMenu.registerIcon} +GSRegistrationMenu.registerOverIcon={GSAuthenticationMenu.registerOverIcon} MainMenu.panelHeader=/images/gui/mainmenu.png MainMenu.createNew=/images/gui/menu_new/create_new.png
23f836454d9c5a495111b068f45d6aa89a2a724a
hbase
HADOOP-1424. TestHBaseCluster fails with- IllegalMonitorStateException. Fix regression introduced by HADOOP-1397.--git-svn-id: https://svn.apache.org/repos/asf/lucene/hadoop/trunk/src/contrib/hbase@541095 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 65fd5cb1c100..092e9a0505a4 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -14,3 +14,5 @@ Trunk (unreleased changes) 'Performance Evaluation', etc. 7. HADOOP-1420, HADOOP-1423. Findbugs changes, remove reference to removed class HLocking. + 8. HADOOP-1424. TestHBaseCluster fails with IllegalMonitorStateException. Fix + regression introduced by HADOOP-1397. diff --git a/src/java/org/apache/hadoop/hbase/HLocking.java b/src/java/org/apache/hadoop/hbase/HLocking.java new file mode 100644 index 000000000000..8031caf99b58 --- /dev/null +++ b/src/java/org/apache/hadoop/hbase/HLocking.java @@ -0,0 +1,101 @@ +/** + * Copyright 2007 The Apache Software Foundation + * + * 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.apache.hadoop.hbase; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * HLocking is a set of lock primitives that does not rely on a + * particular thread holding the monitor for an object. This is + * especially important when a lock must persist over multiple RPC's + * since there is no guarantee that the same Server thread will handle + * all the RPC's until the lock is released. Not requiring that the locker + * thread is same as unlocking thread is the key distinction between this + * class and {@link java.util.concurrent.locks.ReentrantReadWriteLock}. + * + * <p>For each independent entity that needs locking, create a new HLocking + * instance. + */ +public class HLocking { + private Integer mutex; + + // If lockers == 0, the lock is unlocked + // If lockers > 0, locked for read + // If lockers == -1 locked for write + + private AtomicInteger lockers; + + /** Constructor */ + public HLocking() { + this.mutex = new Integer(0); + this.lockers = new AtomicInteger(0); + } + + /** + * Caller needs the nonexclusive read-lock + */ + public void obtainReadLock() { + synchronized(mutex) { + while(lockers.get() < 0) { + try { + mutex.wait(); + } catch(InterruptedException ie) { + } + } + lockers.incrementAndGet(); + mutex.notifyAll(); + } + } + + /** + * Caller is finished with the nonexclusive read-lock + */ + public void releaseReadLock() { + synchronized(mutex) { + if(lockers.decrementAndGet() < 0) { + throw new IllegalStateException("lockers: " + lockers); + } + mutex.notifyAll(); + } + } + + /** + * Caller needs the exclusive write-lock + */ + public void obtainWriteLock() { + synchronized(mutex) { + while(!lockers.compareAndSet(0, -1)) { + try { + mutex.wait(); + } catch (InterruptedException ie) { + } + } + mutex.notifyAll(); + } + } + + /** + * Caller is finished with the write lock + */ + public void releaseWriteLock() { + synchronized(mutex) { + if(!lockers.compareAndSet(-1, 0)) { + throw new IllegalStateException("lockers: " + lockers); + } + mutex.notifyAll(); + } + } +} diff --git a/src/java/org/apache/hadoop/hbase/HMemcache.java b/src/java/org/apache/hadoop/hbase/HMemcache.java index 87616e25f2d1..740caf1d323c 100644 --- a/src/java/org/apache/hadoop/hbase/HMemcache.java +++ b/src/java/org/apache/hadoop/hbase/HMemcache.java @@ -15,14 +15,17 @@ */ package org.apache.hadoop.hbase; -import org.apache.hadoop.io.*; +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - -import java.io.*; -import java.util.*; -import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.apache.hadoop.io.BytesWritable; +import org.apache.hadoop.io.Text; /******************************************************************************* * The HMemcache holds in-memory modifications to the HRegion. This is really a @@ -39,7 +42,7 @@ public class HMemcache { TreeMap<HStoreKey, BytesWritable> snapshot = null; - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final HLocking lock = new HLocking(); public HMemcache() { super(); @@ -70,7 +73,7 @@ public Snapshot() { public Snapshot snapshotMemcacheForLog(HLog log) throws IOException { Snapshot retval = new Snapshot(); - this.lock.writeLock().lock(); + this.lock.obtainWriteLock(); try { if(snapshot != null) { throw new IOException("Snapshot in progress!"); @@ -99,7 +102,7 @@ public Snapshot snapshotMemcacheForLog(HLog log) throws IOException { return retval; } finally { - this.lock.writeLock().unlock(); + this.lock.releaseWriteLock(); } } @@ -109,7 +112,7 @@ public Snapshot snapshotMemcacheForLog(HLog log) throws IOException { * Modifying the structure means we need to obtain a writelock. */ public void deleteSnapshot() throws IOException { - this.lock.writeLock().lock(); + this.lock.obtainWriteLock(); try { if(snapshot == null) { @@ -135,7 +138,7 @@ public void deleteSnapshot() throws IOException { } } finally { - this.lock.writeLock().unlock(); + this.lock.releaseWriteLock(); } } @@ -145,14 +148,14 @@ public void deleteSnapshot() throws IOException { * Operation uses a write lock. */ public void add(Text row, TreeMap<Text, BytesWritable> columns, long timestamp) { - this.lock.writeLock().lock(); + this.lock.obtainWriteLock(); try { for (Map.Entry<Text, BytesWritable> es: columns.entrySet()) { HStoreKey key = new HStoreKey(row, es.getKey(), timestamp); memcache.put(key, es.getValue()); } } finally { - this.lock.writeLock().unlock(); + this.lock.releaseWriteLock(); } } @@ -163,7 +166,7 @@ public void add(Text row, TreeMap<Text, BytesWritable> columns, long timestamp) */ public BytesWritable[] get(HStoreKey key, int numVersions) { Vector<BytesWritable> results = new Vector<BytesWritable>(); - this.lock.readLock().lock(); + this.lock.obtainReadLock(); try { Vector<BytesWritable> result = get(memcache, key, numVersions-results.size()); results.addAll(0, result); @@ -180,7 +183,7 @@ public BytesWritable[] get(HStoreKey key, int numVersions) { return (results.size() == 0)? null: results.toArray(new BytesWritable[results.size()]); } finally { - this.lock.readLock().unlock(); + this.lock.releaseReadLock(); } } @@ -192,7 +195,7 @@ public BytesWritable[] get(HStoreKey key, int numVersions) { */ public TreeMap<Text, BytesWritable> getFull(HStoreKey key) { TreeMap<Text, BytesWritable> results = new TreeMap<Text, BytesWritable>(); - this.lock.readLock().lock(); + this.lock.obtainReadLock(); try { internalGetFull(memcache, key, results); for(int i = history.size()-1; i >= 0; i--) { @@ -202,7 +205,7 @@ public TreeMap<Text, BytesWritable> getFull(HStoreKey key) { return results; } finally { - this.lock.readLock().unlock(); + this.lock.releaseReadLock(); } } @@ -275,7 +278,7 @@ public HMemcacheScanner(long timestamp, Text targetCols[], Text firstRow) super(timestamp, targetCols); - lock.readLock().lock(); + lock.obtainReadLock(); try { this.backingMaps = new TreeMap[history.size() + 1]; @@ -367,7 +370,7 @@ public void close() { } } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); scannerClosed = true; } } diff --git a/src/java/org/apache/hadoop/hbase/HRegion.java b/src/java/org/apache/hadoop/hbase/HRegion.java index b5d000a19735..3cdb8f4cd0af 100644 --- a/src/java/org/apache/hadoop/hbase/HRegion.java +++ b/src/java/org/apache/hadoop/hbase/HRegion.java @@ -23,7 +23,6 @@ import java.io.*; import java.util.*; -import java.util.concurrent.locks.ReentrantReadWriteLock; /** * HRegion stores data for a certain region of a table. It stores all columns @@ -283,7 +282,7 @@ public WriteState() { int maxUnflushedEntries = 0; int compactionThreshold = 0; - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final HLocking lock = new HLocking(); ////////////////////////////////////////////////////////////////////////////// // Constructor @@ -398,7 +397,7 @@ public void closeAndDelete() throws IOException { * time-sensitive thread. */ public Vector<HStoreFile> close() throws IOException { - lock.writeLock().lock(); + lock.obtainWriteLock(); try { boolean shouldClose = false; synchronized(writestate) { @@ -438,7 +437,7 @@ public Vector<HStoreFile> close() throws IOException { } } } finally { - lock.writeLock().unlock(); + lock.releaseWriteLock(); } } @@ -614,7 +613,7 @@ public FileSystem getFilesystem() { * @return - true if the region should be split */ public boolean needsSplit(Text midKey) { - lock.readLock().lock(); + lock.obtainReadLock(); try { Text key = new Text(); @@ -632,7 +631,7 @@ public boolean needsSplit(Text midKey) { return (maxSize > (DESIRED_MAX_FILE_SIZE + (DESIRED_MAX_FILE_SIZE / 2))); } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); } } @@ -641,7 +640,7 @@ public boolean needsSplit(Text midKey) { */ public boolean needsCompaction() { boolean needsCompaction = false; - lock.readLock().lock(); + lock.obtainReadLock(); try { for(Iterator<HStore> i = stores.values().iterator(); i.hasNext(); ) { if(i.next().getNMaps() > compactionThreshold) { @@ -650,7 +649,7 @@ public boolean needsCompaction() { } } } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); } return needsCompaction; } @@ -670,7 +669,7 @@ public boolean needsCompaction() { */ public boolean compactStores() throws IOException { boolean shouldCompact = false; - lock.readLock().lock(); + lock.obtainReadLock(); try { synchronized(writestate) { if((! writestate.writesOngoing) @@ -683,32 +682,30 @@ public boolean compactStores() throws IOException { } } } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); } if(! shouldCompact) { LOG.info("not compacting region " + this.regionInfo.regionName); - return false; - - } else { - lock.writeLock().lock(); - try { - LOG.info("starting compaction on region " + this.regionInfo.regionName); - for(Iterator<HStore> it = stores.values().iterator(); it.hasNext(); ) { - HStore store = it.next(); - store.compact(); - } - LOG.info("compaction completed on region " + this.regionInfo.regionName); - return true; - - } finally { - synchronized(writestate) { - writestate.writesOngoing = false; - recentCommits = 0; - writestate.notifyAll(); - } - lock.writeLock().unlock(); + return false; + } + lock.obtainWriteLock(); + try { + LOG.info("starting compaction on region " + this.regionInfo.regionName); + for (Iterator<HStore> it = stores.values().iterator(); it.hasNext();) { + HStore store = it.next(); + store.compact(); + } + LOG.info("compaction completed on region " + this.regionInfo.regionName); + return true; + + } finally { + synchronized (writestate) { + writestate.writesOngoing = false; + recentCommits = 0; + writestate.notifyAll(); } + lock.releaseWriteLock(); } } @@ -928,7 +925,7 @@ public BytesWritable[] get(Text row, Text column, long timestamp, int numVersion private BytesWritable[] get(HStoreKey key, int numVersions) throws IOException { - lock.readLock().lock(); + lock.obtainReadLock(); try { // Check the memcache @@ -948,7 +945,7 @@ private BytesWritable[] get(HStoreKey key, int numVersions) throws IOException { return targetStore.get(key, numVersions); } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); } } @@ -965,7 +962,7 @@ private BytesWritable[] get(HStoreKey key, int numVersions) throws IOException { public TreeMap<Text, BytesWritable> getFull(Text row) throws IOException { HStoreKey key = new HStoreKey(row, System.currentTimeMillis()); - lock.readLock().lock(); + lock.obtainReadLock(); try { TreeMap<Text, BytesWritable> memResult = memcache.getFull(key); for(Iterator<Text> it = stores.keySet().iterator(); it.hasNext(); ) { @@ -976,7 +973,7 @@ public TreeMap<Text, BytesWritable> getFull(Text row) throws IOException { return memResult; } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); } } @@ -985,7 +982,7 @@ public TreeMap<Text, BytesWritable> getFull(Text row) throws IOException { * columns. This Iterator must be closed by the caller. */ public HInternalScannerInterface getScanner(Text[] cols, Text firstRow) throws IOException { - lock.readLock().lock(); + lock.obtainReadLock(); try { TreeSet<Text> families = new TreeSet<Text>(); for(int i = 0; i < cols.length; i++) { @@ -1001,7 +998,7 @@ public HInternalScannerInterface getScanner(Text[] cols, Text firstRow) throws I return new HScanner(cols, firstRow, memcache, storelist); } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); } } @@ -1024,11 +1021,11 @@ public long startUpdate(Text row) throws IOException { // We obtain a per-row lock, so other clients will // block while one client performs an update. - lock.readLock().lock(); + lock.obtainReadLock(); try { return obtainLock(row); } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); } } diff --git a/src/java/org/apache/hadoop/hbase/HStore.java b/src/java/org/apache/hadoop/hbase/HStore.java index aa3b64d6cc65..7669747b5219 100644 --- a/src/java/org/apache/hadoop/hbase/HStore.java +++ b/src/java/org/apache/hadoop/hbase/HStore.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.TreeMap; import java.util.Vector; -import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -64,7 +63,7 @@ public class HStore { Integer compactLock = 0; Integer flushLock = 0; - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final HLocking lock = new HLocking(); TreeMap<Long, MapFile.Reader> maps = new TreeMap<Long, MapFile.Reader>(); TreeMap<Long, HStoreFile> mapFiles = new TreeMap<Long, HStoreFile>(); @@ -237,7 +236,7 @@ public HStore(Path dir, Text regionName, Text colFamily, int maxVersions, /** Turn off all the MapFile readers */ public void close() throws IOException { LOG.info("closing HStore for " + this.regionName + "/" + this.colFamily); - this.lock.writeLock().lock(); + this.lock.obtainWriteLock(); try { for (MapFile.Reader map: maps.values()) { map.close(); @@ -247,7 +246,7 @@ public void close() throws IOException { LOG.info("HStore closed for " + this.regionName + "/" + this.colFamily); } finally { - this.lock.writeLock().unlock(); + this.lock.releaseWriteLock(); } } @@ -319,7 +318,7 @@ Vector<HStoreFile> flushCacheHelper(TreeMap<HStoreKey, BytesWritable> inputCache // C. Finally, make the new MapFile available. if(addToAvailableMaps) { - this.lock.writeLock().lock(); + this.lock.obtainWriteLock(); try { maps.put(logCacheFlushId, new MapFile.Reader(fs, mapfile.toString(), conf)); @@ -330,7 +329,7 @@ Vector<HStoreFile> flushCacheHelper(TreeMap<HStoreKey, BytesWritable> inputCache } } finally { - this.lock.writeLock().unlock(); + this.lock.releaseWriteLock(); } } return getAllMapFiles(); @@ -338,12 +337,12 @@ Vector<HStoreFile> flushCacheHelper(TreeMap<HStoreKey, BytesWritable> inputCache } public Vector<HStoreFile> getAllMapFiles() { - this.lock.readLock().lock(); + this.lock.obtainReadLock(); try { return new Vector<HStoreFile>(mapFiles.values()); } finally { - this.lock.readLock().unlock(); + this.lock.releaseReadLock(); } } @@ -385,12 +384,12 @@ void compactHelper(boolean deleteSequenceInfo) throws IOException { // Grab a list of files to compact. Vector<HStoreFile> toCompactFiles = null; - this.lock.writeLock().lock(); + this.lock.obtainWriteLock(); try { toCompactFiles = new Vector<HStoreFile>(mapFiles.values()); } finally { - this.lock.writeLock().unlock(); + this.lock.releaseWriteLock(); } // Compute the max-sequenceID seen in any of the to-be-compacted TreeMaps @@ -627,7 +626,7 @@ void processReadyCompaction() throws IOException { Path curCompactStore = HStoreFile.getHStoreDir(compactdir, regionName, colFamily); - this.lock.writeLock().lock(); + this.lock.obtainWriteLock(); try { Path doneFile = new Path(curCompactStore, COMPACTION_DONE); if(! fs.exists(doneFile)) { @@ -744,7 +743,7 @@ void processReadyCompaction() throws IOException { // 7. Releasing the write-lock - this.lock.writeLock().unlock(); + this.lock.releaseWriteLock(); } } @@ -760,7 +759,7 @@ void processReadyCompaction() throws IOException { * The returned object should map column names to byte arrays (byte[]). */ public void getFull(HStoreKey key, TreeMap<Text, BytesWritable> results) throws IOException { - this.lock.readLock().lock(); + this.lock.obtainReadLock(); try { MapFile.Reader[] maparray = maps.values().toArray(new MapFile.Reader[maps.size()]); @@ -789,7 +788,7 @@ public void getFull(HStoreKey key, TreeMap<Text, BytesWritable> results) throws } } finally { - this.lock.readLock().unlock(); + this.lock.releaseReadLock(); } } @@ -805,7 +804,7 @@ public BytesWritable[] get(HStoreKey key, int numVersions) throws IOException { } Vector<BytesWritable> results = new Vector<BytesWritable>(); - this.lock.readLock().lock(); + this.lock.obtainReadLock(); try { MapFile.Reader[] maparray = maps.values().toArray(new MapFile.Reader[maps.size()]); @@ -846,7 +845,7 @@ public BytesWritable[] get(HStoreKey key, int numVersions) throws IOException { } } finally { - this.lock.readLock().unlock(); + this.lock.releaseReadLock(); } } @@ -862,7 +861,7 @@ public long getLargestFileSize(Text midKey) { return maxSize; } - this.lock.readLock().lock(); + this.lock.obtainReadLock(); try { long mapIndex = 0L; @@ -889,7 +888,7 @@ public long getLargestFileSize(Text midKey) { LOG.warn(e); } finally { - this.lock.readLock().unlock(); + this.lock.releaseReadLock(); } return maxSize; } @@ -898,12 +897,12 @@ public long getLargestFileSize(Text midKey) { * @return Returns the number of map files currently in use */ public int getNMaps() { - this.lock.readLock().lock(); + this.lock.obtainReadLock(); try { return maps.size(); } finally { - this.lock.readLock().unlock(); + this.lock.releaseReadLock(); } } @@ -945,7 +944,7 @@ public HStoreScanner(long timestamp, Text[] targetCols, Text firstRow) super(timestamp, targetCols); - lock.readLock().lock(); + lock.obtainReadLock(); try { this.readers = new MapFile.Reader[mapFiles.size()]; @@ -1060,7 +1059,7 @@ public void close() { } } finally { - lock.readLock().unlock(); + lock.releaseReadLock(); scannerClosed = true; } }
4d4cee8d2dd6edc2cae5d22fbb3d672e5bd38bf3
Valadoc
gtkdoc-importer: Add support for variablelist
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index a91e1f5089..af547f4beb 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -1185,9 +1185,12 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { return table; } - private LinkedList<Block> parse_docbook_section () { + private LinkedList<Block>? parse_docbook_section () { if (!check_xml_open_tag ("section")) { + this.report_unexpected_token (current, "<section>"); + return null; } + string id = current.attributes.get ("id"); next (); @@ -1202,6 +1205,166 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { return content; } + private ListItem? parse_docbook_member () { + if (!check_xml_open_tag ("member")) { + this.report_unexpected_token (current, "<member>"); + return null; + } + next (); + + parse_docbook_spaces (); + + ListItem item = factory.create_list_item (); + Paragraph para = factory.create_paragraph (); + item.content.add (para); + + para.content.add (parse_inline_content ()); + + parse_docbook_spaces (); + + if (!check_xml_close_tag ("member")) { + this.report_unexpected_token (current, "</member>"); + return item; + } + + next (); + return item; + } + + private Content.List? parse_docbook_simplelist () { + if (!check_xml_open_tag ("simplelist")) { + this.report_unexpected_token (current, "<simplelist>"); + return null; + } + next (); + + parse_docbook_spaces (); + + Content.List list = factory.create_list (); + + while (current.type == TokenType.XML_OPEN && current.content == "member") { + ListItem item = parse_docbook_member (); + if (item == null) { + break; + } + + list.items.add (item); + parse_docbook_spaces (); + } + + + if (!check_xml_close_tag ("simplelist")) { + this.report_unexpected_token (current, "</simplelist>"); + return list; + } + + next (); + return list; + } + + private Paragraph? parse_docbook_term () { + if (!check_xml_open_tag ("term")) { + this.report_unexpected_token (current, "<term>"); + return null; + } + next (); + + parse_docbook_spaces (); + + Paragraph? p = factory.create_paragraph (); + Run run = parse_inline_content (); + run.style = Run.Style.ITALIC; + p.content.add (run); + + if (!check_xml_close_tag ("term")) { + this.report_unexpected_token (current, "</term>"); + return p; + } + + next (); + return p; + } + + private ListItem? parse_docbook_varlistentry () { + if (!check_xml_open_tag ("varlistentry")) { + this.report_unexpected_token (current, "<varlistentry>"); + return null; + } + next (); + + parse_docbook_spaces (); + + if (current.type != TokenType.XML_OPEN || current.content != "term") { + return null; + } + + Paragraph? term = parse_docbook_term (); + if (term == null) { + return null; + } + + parse_docbook_spaces (); + ListItem? desc = parse_docbook_listitem (); + if (desc == null) { + return null; + } + + parse_docbook_spaces (); + + Content.ListItem listitem = factory.create_list_item (); + Content.List list = factory.create_list (); + + listitem.content.add (term); + listitem.content.add (list); + list.items.add (desc); + + if (!check_xml_close_tag ("varlistentry")) { + this.report_unexpected_token (current, "</varlistentry>"); + return listitem; + } + + next (); + return listitem; + } + + private LinkedList<Block>? parse_docbook_variablelist () { + if (!check_xml_open_tag ("variablelist")) { + this.report_unexpected_token (current, "<variablelist>"); + return null; + } + next (); + + parse_docbook_spaces (); + + LinkedList<Block> content = new LinkedList<Block> (); + + if (current.type == TokenType.XML_OPEN && current.content == "title") { + append_block_content_not_null (content, parse_docbook_title ()); + parse_docbook_spaces (); + } + + Content.List list = factory.create_list (); + content.add (list); + + while (current.type == TokenType.XML_OPEN && current.content == "varlistentry") { + ListItem item = parse_docbook_varlistentry (); + if (item == null) { + break; + } + + list.items.add (item); + parse_docbook_spaces (); + } + + if (!check_xml_close_tag ("variablelist")) { + this.report_unexpected_token (current, "</variablelist>"); + return content; + } + + next (); + return content; + } + private LinkedList<Block> parse_block_content () { LinkedList<Block> content = new LinkedList<Block> (); @@ -1210,6 +1373,10 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { if (current.type == TokenType.XML_OPEN && current.content == "itemizedlist") { this.append_block_content_not_null (content, parse_docbook_itemizedlist ()); + } else if (current.type == TokenType.XML_OPEN && current.content == "variablelist") { + this.append_block_content_not_null_all (content, parse_docbook_variablelist ()); + } else if (current.type == TokenType.XML_OPEN && current.content == "simplelist") { + this.append_block_content_not_null (content, parse_docbook_simplelist ()); } else if (current.type == TokenType.XML_OPEN && current.content == "informaltable") { this.append_block_content_not_null (content, parse_docbook_informaltable ()); } else if (current.type == TokenType.XML_OPEN && current.content == "programlisting") {
c6cf7489853d603bb1a77ad699b3068cb4779bbf
hadoop
YARN-2958. Made RMStateStore not update the last- sequence number when updating the delegation token. Contributed by Varun- Saxena.--(cherry picked from commit 562a701945be3a672f9cb5a52cc6db2c1589ba2b)-
c
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 06fcedce51ff0..83acc08bfe3e2 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -279,6 +279,9 @@ Release 2.7.0 - UNRELEASED YARN-2922. ConcurrentModificationException in CapacityScheduler's LeafQueue. (Rohith Sharmaks via ozawa) + YARN-2958. Made RMStateStore not update the last sequence number when updating the + delegation token. (Varun Saxena via zjshen) + Release 2.6.0 - 2014-11-18 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/recovery/FileSystemRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java index 51e3916cf2307..77836620b2967 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java @@ -60,8 +60,6 @@ import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.EpochPBImpl; -import org.apache.hadoop.yarn.util.ConverterUtils; - import com.google.common.annotations.VisibleForTesting; @Private @@ -452,11 +450,10 @@ public synchronized void removeApplicationStateInternal( } @Override - public synchronized void storeRMDelegationTokenAndSequenceNumberState( - RMDelegationTokenIdentifier identifier, Long renewDate, - int latestSequenceNumber) throws Exception { - storeOrUpdateRMDelegationTokenAndSequenceNumberState( - identifier, renewDate,latestSequenceNumber, false); + public synchronized void storeRMDelegationTokenState( + RMDelegationTokenIdentifier identifier, Long renewDate) + throws Exception { + storeOrUpdateRMDelegationTokenState(identifier, renewDate, false); } @Override @@ -469,16 +466,15 @@ public synchronized void removeRMDelegationTokenState( } @Override - protected void updateRMDelegationTokenAndSequenceNumberInternal( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception { - storeOrUpdateRMDelegationTokenAndSequenceNumberState( - rmDTIdentifier, renewDate,latestSequenceNumber, true); + protected void updateRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception { + storeOrUpdateRMDelegationTokenState(rmDTIdentifier, renewDate, true); } - private void storeOrUpdateRMDelegationTokenAndSequenceNumberState( + private void storeOrUpdateRMDelegationTokenState( RMDelegationTokenIdentifier identifier, Long renewDate, - int latestSequenceNumber, boolean isUpdate) throws Exception { + boolean isUpdate) throws Exception { Path nodeCreatePath = getNodePath(rmDTSecretManagerRoot, DELEGATION_TOKEN_PREFIX + identifier.getSequenceNumber()); @@ -490,23 +486,24 @@ private void storeOrUpdateRMDelegationTokenAndSequenceNumberState( } else { LOG.info("Storing RMDelegationToken_" + identifier.getSequenceNumber()); writeFile(nodeCreatePath, identifierData.toByteArray()); - } - // store sequence number - Path latestSequenceNumberPath = getNodePath(rmDTSecretManagerRoot, - DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX + latestSequenceNumber); - LOG.info("Storing " + DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX - + latestSequenceNumber); - if (dtSequenceNumberPath == null) { - if (!createFile(latestSequenceNumberPath)) { - throw new Exception("Failed to create " + latestSequenceNumberPath); - } - } else { - if (!renameFile(dtSequenceNumberPath, latestSequenceNumberPath)) { - throw new Exception("Failed to rename " + dtSequenceNumberPath); + // store sequence number + Path latestSequenceNumberPath = getNodePath(rmDTSecretManagerRoot, + DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX + + identifier.getSequenceNumber()); + LOG.info("Storing " + DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX + + identifier.getSequenceNumber()); + if (dtSequenceNumberPath == null) { + if (!createFile(latestSequenceNumberPath)) { + throw new Exception("Failed to create " + latestSequenceNumberPath); + } + } else { + if (!renameFile(dtSequenceNumberPath, latestSequenceNumberPath)) { + throw new Exception("Failed to rename " + dtSequenceNumberPath); + } } + dtSequenceNumberPath = latestSequenceNumberPath; } - dtSequenceNumberPath = latestSequenceNumberPath; } @Override diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java index 0f880c8b0fba9..2c927146480e7 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java @@ -544,31 +544,30 @@ protected void removeApplicationStateInternal(ApplicationStateData appState) throw new IOException(e); } } - - @Override - protected void storeRMDelegationTokenAndSequenceNumberState( - RMDelegationTokenIdentifier tokenId, Long renewDate, - int latestSequenceNumber) throws IOException { + + private void storeOrUpdateRMDT(RMDelegationTokenIdentifier tokenId, + Long renewDate, boolean isUpdate) throws IOException { String tokenKey = getRMDTTokenNodeKey(tokenId); RMDelegationTokenIdentifierData tokenData = new RMDelegationTokenIdentifierData(tokenId, renewDate); - ByteArrayOutputStream bs = new ByteArrayOutputStream(); - DataOutputStream ds = new DataOutputStream(bs); - try { - ds.writeInt(latestSequenceNumber); - } finally { - ds.close(); - } if (LOG.isDebugEnabled()) { LOG.debug("Storing token to " + tokenKey); - LOG.debug("Storing " + latestSequenceNumber + " to " - + RM_DT_SEQUENCE_NUMBER_KEY); } try { WriteBatch batch = db.createWriteBatch(); try { batch.put(bytes(tokenKey), tokenData.toByteArray()); - batch.put(bytes(RM_DT_SEQUENCE_NUMBER_KEY), bs.toByteArray()); + if(!isUpdate) { + ByteArrayOutputStream bs = new ByteArrayOutputStream(); + try (DataOutputStream ds = new DataOutputStream(bs)) { + ds.writeInt(tokenId.getSequenceNumber()); + } + if (LOG.isDebugEnabled()) { + LOG.debug("Storing " + tokenId.getSequenceNumber() + " to " + + RM_DT_SEQUENCE_NUMBER_KEY); + } + batch.put(bytes(RM_DT_SEQUENCE_NUMBER_KEY), bs.toByteArray()); + } db.write(batch); } finally { batch.close(); @@ -579,11 +578,17 @@ protected void storeRMDelegationTokenAndSequenceNumberState( } @Override - protected void updateRMDelegationTokenAndSequenceNumberInternal( - RMDelegationTokenIdentifier tokenId, Long renewDate, - int latestSequenceNumber) throws IOException { - storeRMDelegationTokenAndSequenceNumberState(tokenId, renewDate, - latestSequenceNumber); + protected void storeRMDelegationTokenState( + RMDelegationTokenIdentifier tokenId, Long renewDate) + throws IOException { + storeOrUpdateRMDT(tokenId, renewDate, false); + } + + @Override + protected void updateRMDelegationTokenState( + RMDelegationTokenIdentifier tokenId, Long renewDate) + throws IOException { + storeOrUpdateRMDT(tokenId, renewDate, true); } @Override diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java index 917fdc13a3816..3646949b60492 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java @@ -149,23 +149,30 @@ public synchronized void removeApplicationStateInternal( } } - @Override - public synchronized void storeRMDelegationTokenAndSequenceNumberState( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception { + private void storeOrUpdateRMDT(RMDelegationTokenIdentifier rmDTIdentifier, + Long renewDate, boolean isUpdate) throws Exception { Map<RMDelegationTokenIdentifier, Long> rmDTState = state.rmSecretManagerState.getTokenState(); if (rmDTState.containsKey(rmDTIdentifier)) { IOException e = new IOException("RMDelegationToken: " + rmDTIdentifier - + "is already stored."); + + "is already stored."); LOG.info("Error storing info for RMDelegationToken: " + rmDTIdentifier, e); throw e; } rmDTState.put(rmDTIdentifier, renewDate); - state.rmSecretManagerState.dtSequenceNumber = latestSequenceNumber; + if(!isUpdate) { + state.rmSecretManagerState.dtSequenceNumber = + rmDTIdentifier.getSequenceNumber(); + } LOG.info("Store RMDT with sequence number " - + rmDTIdentifier.getSequenceNumber() - + ". And the latest sequence number is " + latestSequenceNumber); + + rmDTIdentifier.getSequenceNumber()); + } + + @Override + public synchronized void storeRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception { + storeOrUpdateRMDT(rmDTIdentifier, renewDate, false); } @Override @@ -179,12 +186,11 @@ public synchronized void removeRMDelegationTokenState( } @Override - protected void updateRMDelegationTokenAndSequenceNumberInternal( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception { + protected void updateRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception { removeRMDelegationTokenState(rmDTIdentifier); - storeRMDelegationTokenAndSequenceNumberState( - rmDTIdentifier, renewDate, latestSequenceNumber); + storeOrUpdateRMDT(rmDTIdentifier, renewDate, true); LOG.info("Update RMDT with sequence number " + rmDTIdentifier.getSequenceNumber()); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java index f80c497e80af5..d2c1e9d71f351 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java @@ -77,9 +77,9 @@ protected void removeApplicationStateInternal(ApplicationStateData appState) } @Override - public void storeRMDelegationTokenAndSequenceNumberState( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception { + public void storeRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception { // Do nothing } @@ -90,9 +90,9 @@ public void removeRMDelegationTokenState(RMDelegationTokenIdentifier rmDTIdentif } @Override - protected void updateRMDelegationTokenAndSequenceNumberInternal( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception { + protected void updateRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception { // Do nothing } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java index 3966dc495dd2a..bccde53ddff39 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java @@ -296,9 +296,8 @@ public void transition(RMStateStore store, RMStateStoreEvent event) { RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event; try { LOG.info("Storing RMDelegationToken and SequenceNumber"); - store.storeRMDelegationTokenAndSequenceNumberState( - dtEvent.getRmDTIdentifier(), dtEvent.getRenewDate(), - dtEvent.getLatestSequenceNumber()); + store.storeRMDelegationTokenState( + dtEvent.getRmDTIdentifier(), dtEvent.getRenewDate()); } catch (Exception e) { LOG.error("Error While Storing RMDelegationToken and SequenceNumber ", e); @@ -341,9 +340,8 @@ public void transition(RMStateStore store, RMStateStoreEvent event) { RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event; try { LOG.info("Updating RMDelegationToken and SequenceNumber"); - store.updateRMDelegationTokenAndSequenceNumberInternal( - dtEvent.getRmDTIdentifier(), dtEvent.getRenewDate(), - dtEvent.getLatestSequenceNumber()); + store.updateRMDelegationTokenState( + dtEvent.getRmDTIdentifier(), dtEvent.getRenewDate()); } catch (Exception e) { LOG.error("Error While Updating RMDelegationToken and SequenceNumber ", e); @@ -672,11 +670,10 @@ protected abstract void updateApplicationAttemptStateInternal( * RMDTSecretManager call this to store the state of a delegation token * and sequence number */ - public void storeRMDelegationTokenAndSequenceNumber( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) { + public void storeRMDelegationToken( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) { handleStoreEvent(new RMStateStoreRMDTEvent(rmDTIdentifier, renewDate, - latestSequenceNumber, RMStateStoreEventType.STORE_DELEGATION_TOKEN)); + RMStateStoreEventType.STORE_DELEGATION_TOKEN)); } /** @@ -684,17 +681,17 @@ public void storeRMDelegationTokenAndSequenceNumber( * Derived classes must implement this method to store the state of * RMDelegationToken and sequence number */ - protected abstract void storeRMDelegationTokenAndSequenceNumberState( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception; + protected abstract void storeRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception; /** * RMDTSecretManager call this to remove the state of a delegation token */ public void removeRMDelegationToken( - RMDelegationTokenIdentifier rmDTIdentifier, int sequenceNumber) { + RMDelegationTokenIdentifier rmDTIdentifier) { handleStoreEvent(new RMStateStoreRMDTEvent(rmDTIdentifier, null, - sequenceNumber, RMStateStoreEventType.REMOVE_DELEGATION_TOKEN)); + RMStateStoreEventType.REMOVE_DELEGATION_TOKEN)); } /** @@ -708,11 +705,10 @@ protected abstract void removeRMDelegationTokenState( * RMDTSecretManager call this to update the state of a delegation token * and sequence number */ - public void updateRMDelegationTokenAndSequenceNumber( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) { + public void updateRMDelegationToken( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) { handleStoreEvent(new RMStateStoreRMDTEvent(rmDTIdentifier, renewDate, - latestSequenceNumber, RMStateStoreEventType.UPDATE_DELEGATION_TOKEN)); + RMStateStoreEventType.UPDATE_DELEGATION_TOKEN)); } /** @@ -720,9 +716,9 @@ public void updateRMDelegationTokenAndSequenceNumber( * Derived classes must implement this method to update the state of * RMDelegationToken and sequence number */ - protected abstract void updateRMDelegationTokenAndSequenceNumberInternal( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception; + protected abstract void updateRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception; /** * RMDTSecretManager call this to store the state of a master key diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRMDTEvent.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRMDTEvent.java index 4cd4d2e25415b..a3519ff6f8fe1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRMDTEvent.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRMDTEvent.java @@ -23,18 +23,16 @@ public class RMStateStoreRMDTEvent extends RMStateStoreEvent { private RMDelegationTokenIdentifier rmDTIdentifier; private Long renewDate; - private int latestSequenceNumber; public RMStateStoreRMDTEvent(RMStateStoreEventType type) { super(type); } public RMStateStoreRMDTEvent(RMDelegationTokenIdentifier rmDTIdentifier, - Long renewDate, int latestSequenceNumber, RMStateStoreEventType type) { + Long renewDate, RMStateStoreEventType type) { this(type); this.rmDTIdentifier = rmDTIdentifier; this.renewDate = renewDate; - this.latestSequenceNumber = latestSequenceNumber; } public RMDelegationTokenIdentifier getRmDTIdentifier() { @@ -44,8 +42,4 @@ public RMDelegationTokenIdentifier getRmDTIdentifier() { public Long getRenewDate() { return renewDate; } - - public int getLatestSequenceNumber() { - return latestSequenceNumber; - } -} +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java index 2babc82a1d598..f3da21e51609e 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java @@ -698,12 +698,11 @@ public synchronized void removeApplicationStateInternal( } @Override - protected synchronized void storeRMDelegationTokenAndSequenceNumberState( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception { + protected synchronized void storeRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception { ArrayList<Op> opList = new ArrayList<Op>(); - addStoreOrUpdateOps( - opList, rmDTIdentifier, renewDate, latestSequenceNumber, false); + addStoreOrUpdateOps(opList, rmDTIdentifier, renewDate, false); doMultiWithRetries(opList); } @@ -727,29 +726,27 @@ protected synchronized void removeRMDelegationTokenState( } @Override - protected synchronized void updateRMDelegationTokenAndSequenceNumberInternal( - RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber) throws Exception { + protected synchronized void updateRMDelegationTokenState( + RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) + throws Exception { ArrayList<Op> opList = new ArrayList<Op>(); String nodeRemovePath = getNodePath(delegationTokensRootPath, DELEGATION_TOKEN_PREFIX + rmDTIdentifier.getSequenceNumber()); if (existsWithRetries(nodeRemovePath, true) == null) { // in case znode doesn't exist - addStoreOrUpdateOps( - opList, rmDTIdentifier, renewDate, latestSequenceNumber, false); + addStoreOrUpdateOps(opList, rmDTIdentifier, renewDate, false); LOG.debug("Attempted to update a non-existing znode " + nodeRemovePath); } else { // in case znode exists - addStoreOrUpdateOps( - opList, rmDTIdentifier, renewDate, latestSequenceNumber, true); + addStoreOrUpdateOps(opList, rmDTIdentifier, renewDate, true); } doMultiWithRetries(opList); } private void addStoreOrUpdateOps(ArrayList<Op> opList, RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, - int latestSequenceNumber, boolean isUpdate) throws Exception { + boolean isUpdate) throws Exception { // store RM delegation token String nodeCreatePath = getNodePath(delegationTokensRootPath, DELEGATION_TOKEN_PREFIX @@ -769,16 +766,15 @@ private void addStoreOrUpdateOps(ArrayList<Op> opList, } else { opList.add(Op.create(nodeCreatePath, identifierData.toByteArray(), zkAcl, CreateMode.PERSISTENT)); + // Update Sequence number only while storing DT + seqOut.writeInt(rmDTIdentifier.getSequenceNumber()); + if (LOG.isDebugEnabled()) { + LOG.debug((isUpdate ? "Storing " : "Updating ") + + dtSequenceNumberPath + ". SequenceNumber: " + + rmDTIdentifier.getSequenceNumber()); + } + opList.add(Op.setData(dtSequenceNumberPath, seqOs.toByteArray(), -1)); } - - - seqOut.writeInt(latestSequenceNumber); - if (LOG.isDebugEnabled()) { - LOG.debug((isUpdate ? "Storing " : "Updating ") + dtSequenceNumberPath + - ". SequenceNumber: " + latestSequenceNumber); - } - - opList.add(Op.setData(dtSequenceNumberPath, seqOs.toByteArray(), -1)); } finally { seqOs.close(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/RMDelegationTokenSecretManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/RMDelegationTokenSecretManager.java index 90706ff8c94b5..83defc5424707 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/RMDelegationTokenSecretManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/RMDelegationTokenSecretManager.java @@ -29,10 +29,8 @@ import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability; -import org.apache.hadoop.security.token.SecretManager.InvalidToken; import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSecretManager; import org.apache.hadoop.security.token.delegation.DelegationKey; -import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSecretManager.DelegationTokenInformation; import org.apache.hadoop.util.ExitUtil; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; @@ -109,8 +107,7 @@ protected void storeNewToken(RMDelegationTokenIdentifier identifier, try { LOG.info("storing RMDelegation token with sequence number: " + identifier.getSequenceNumber()); - rmContext.getStateStore().storeRMDelegationTokenAndSequenceNumber( - identifier, renewDate, identifier.getSequenceNumber()); + rmContext.getStateStore().storeRMDelegationToken(identifier, renewDate); } catch (Exception e) { LOG.error("Error in storing RMDelegationToken with sequence number: " + identifier.getSequenceNumber()); @@ -124,11 +121,10 @@ protected void updateStoredToken(RMDelegationTokenIdentifier id, try { LOG.info("updating RMDelegation token with sequence number: " + id.getSequenceNumber()); - rmContext.getStateStore().updateRMDelegationTokenAndSequenceNumber(id, - renewDate, id.getSequenceNumber()); + rmContext.getStateStore().updateRMDelegationToken(id, renewDate); } catch (Exception e) { - LOG.error("Error in updating persisted RMDelegationToken with sequence number: " - + id.getSequenceNumber()); + LOG.error("Error in updating persisted RMDelegationToken" + + " with sequence number: " + id.getSequenceNumber()); ExitUtil.terminate(1, e); } } @@ -139,8 +135,7 @@ protected void removeStoredToken(RMDelegationTokenIdentifier ident) try { LOG.info("removing RMDelegation token with sequence number: " + ident.getSequenceNumber()); - rmContext.getStateStore().removeRMDelegationToken(ident, - delegationTokenSequenceNumber); + rmContext.getStateStore().removeRMDelegationToken(ident); } catch (Exception e) { LOG.error("Error in removing RMDelegationToken with sequence number: " + ident.getSequenceNumber()); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java index 82ecac01ed03a..b01969bd08525 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java @@ -411,16 +411,15 @@ public void testRMDTSecretManagerStateStore( RMDelegationTokenIdentifier dtId1 = new RMDelegationTokenIdentifier(new Text("owner1"), new Text("renewer1"), new Text("realuser1")); + int sequenceNumber = 1111; + dtId1.setSequenceNumber(sequenceNumber); byte[] tokenBeforeStore = dtId1.getBytes(); Long renewDate1 = new Long(System.currentTimeMillis()); - int sequenceNumber = 1111; - store.storeRMDelegationTokenAndSequenceNumber(dtId1, renewDate1, - sequenceNumber); + store.storeRMDelegationToken(dtId1, renewDate1); modifyRMDelegationTokenState(); Map<RMDelegationTokenIdentifier, Long> token1 = new HashMap<RMDelegationTokenIdentifier, Long>(); token1.put(dtId1, renewDate1); - // store delegation key; DelegationKey key = new DelegationKey(1234, 4321 , "keyBytes".getBytes()); HashSet<DelegationKey> keySet = new HashSet<DelegationKey>(); @@ -440,9 +439,7 @@ public void testRMDTSecretManagerStateStore( // update RM delegation token; renewDate1 = new Long(System.currentTimeMillis()); - ++sequenceNumber; - store.updateRMDelegationTokenAndSequenceNumber( - dtId1, renewDate1, sequenceNumber); + store.updateRMDelegationToken(dtId1, renewDate1); token1.put(dtId1, renewDate1); RMDTSecretManagerState updateSecretManagerState = @@ -463,7 +460,7 @@ public void testRMDTSecretManagerStateStore( noKeySecretManagerState.getDTSequenceNumber()); // check to delete delegationToken - store.removeRMDelegationToken(dtId1, sequenceNumber); + store.removeRMDelegationToken(dtId1); RMDTSecretManagerState noKeyAndTokenSecretManagerState = store.loadState().getRMDTSecretManagerState(); token1.clear(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java index 204348478ab64..87df3d6fbceb2 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java @@ -337,20 +337,18 @@ public void testFencedState() throws Exception { RMDelegationTokenIdentifier dtId1 = new RMDelegationTokenIdentifier(new Text("owner1"), new Text("renewer1"), new Text("realuser1")); - Long renewDate1 = new Long(System.currentTimeMillis()); - int sequenceNumber = 1111; - store.storeRMDelegationTokenAndSequenceNumber(dtId1, renewDate1, - sequenceNumber); + Long renewDate1 = new Long(System.currentTimeMillis()); + dtId1.setSequenceNumber(1111); + store.storeRMDelegationToken(dtId1, renewDate1); assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState()); - store.updateRMDelegationTokenAndSequenceNumber(dtId1, renewDate1, - sequenceNumber); + store.updateRMDelegationToken(dtId1, renewDate1); assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState()); // remove delegation key; - store.removeRMDelegationToken(dtId1, sequenceNumber); + store.removeRMDelegationToken(dtId1); assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
af522d6852fef03bfd02233f2066156db4459b90
hbase
HBASE-11248-KeyOnlyKeyValue-toString() passes- wrong offset to keyToString() (Ram)--
c
https://github.com/apache/hbase
diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/KeyValue.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/KeyValue.java index 4cca2d46a275..0fdd9e46c18f 100644 --- a/hbase-common/src/main/java/org/apache/hadoop/hbase/KeyValue.java +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/KeyValue.java @@ -2741,8 +2741,7 @@ public String toString() { if (this.b == null || this.b.length == 0) { return "empty"; } - return keyToString(this.b, this.offset + ROW_OFFSET, getKeyLength()) + "/vlen=" - + getValueLength() + "/mvcc=" + 0; + return keyToString(this.b, this.offset, getKeyLength()) + "/vlen=0/mvcc=0"; } @Override
eb526e50a1925a11412e256f598ff787c42d2950
Delta Spike
DELTASPIKE-375 improve performance and use internal ClassUtils common code
c
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/event/EventEmitter.java b/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/event/EventEmitter.java index 899e3f78f..7ef367d63 100644 --- a/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/event/EventEmitter.java +++ b/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/event/EventEmitter.java @@ -18,6 +18,7 @@ */ package org.apache.deltaspike.servlet.impl.event; +import javax.enterprise.inject.spi.BeanManager; import java.lang.annotation.Annotation; import org.apache.deltaspike.core.api.provider.BeanManagerProvider; @@ -30,14 +31,27 @@ */ abstract class EventEmitter { + private volatile BeanManager beanManager; protected void fireEvent(Object event, Annotation... qualifier) { - /* - * No need to cache the BeanManager reference because the providers already does this on a context class loader - * level. - */ - BeanManagerProvider.getInstance().getBeanManager().fireEvent(event, qualifier); + getBeanManager().fireEvent(event, qualifier); + } + + protected BeanManager getBeanManager() + { + if (beanManager == null) + { + synchronized (this) + { + if (beanManager == null) + { + beanManager = BeanManagerProvider.getInstance().getBeanManager(); + } + } + } + + return beanManager; } } diff --git a/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/produce/ServletContextHolder.java b/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/produce/ServletContextHolder.java index 14044d844..1d4f29249 100644 --- a/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/produce/ServletContextHolder.java +++ b/deltaspike/modules/servlet/impl/src/main/java/org/apache/deltaspike/servlet/impl/produce/ServletContextHolder.java @@ -25,6 +25,8 @@ import javax.servlet.ServletContext; +import org.apache.deltaspike.core.util.ClassUtils; + /** * This class holds the {@link ServletContext} for each context class loader. * @@ -52,7 +54,7 @@ private ServletContextHolder() */ static void bind(ServletContext servletContext) { - ClassLoader classLoader = getContextClassLoader(); + ClassLoader classLoader = ClassUtils.getClassLoader(null); ServletContext existingContext = CONTEXT_BY_CLASSLOADER.put(classLoader, servletContext); if (existingContext != null) { @@ -69,7 +71,7 @@ static void bind(ServletContext servletContext) */ static ServletContext get() { - ClassLoader classLoader = getContextClassLoader(); + ClassLoader classLoader = ClassUtils.getClassLoader(null); ServletContext servletContext = CONTEXT_BY_CLASSLOADER.get(classLoader); if (servletContext == null) { @@ -84,7 +86,7 @@ static ServletContext get() */ static void release() { - ClassLoader classLoader = getContextClassLoader(); + ClassLoader classLoader = ClassUtils.getClassLoader(null); ServletContext removedContext = CONTEXT_BY_CLASSLOADER.remove(classLoader); if (removedContext == null) { @@ -92,14 +94,4 @@ static void release() } } - private static ClassLoader getContextClassLoader() - { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader == null) - { - throw new IllegalStateException("Unable to obtain the context class loader for the current thread"); - } - return classLoader; - } - }
5392bbbfc10ba4e8ef8058ef3abe122c5963d8fb
tapiji
Removes outdated PDE build project The PDE build based buildscript project is outdated now. It has already been replaced by a tycho based build approach. This change removes the outdated project files. (cherry picked from commit 40ac64a981cd719c07a30eb2bbb0c67a4e82a1a0)
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.build/build.properties b/org.eclipse.babel.tapiji.tools.build/build.properties deleted file mode 100644 index 8b9b0513..00000000 --- a/org.eclipse.babel.tapiji.tools.build/build.properties +++ /dev/null @@ -1,133 +0,0 @@ -############################################################################### -# Copyright (c) 2003, 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 Corporation - initial API and implementation -# Compuware Corporation - Sebastien Angers <[email protected]> -# - Enabled additional mirror slicingOptions in Headless PDE Build -# - Enabled 'raw' attribute for mirror step in Headless PDE Build -# - https://bugs.eclipse.org/338878 -############################################################################### - -#The type of the top level element we are building, generally "feature" -topLevelElementType = feature -#The id of the top level element we are building -topLevelElementId = org.eclipse.babel.tapiji.tools.java.feature - -############# PRODUCT/PACKAGING CONTROL ############# -#product=/plugin or feature id/path/to/.product -runPackager=true - -#Set the name of the archive that will result from the product build. -#archiveNamePrefix= - -# The prefix that will be used in the generated archive. -archivePrefix=tapiji_feature - -# The location underwhich all of the build output will be collected. -collectingFolder=${archivePrefix} - -# The list of {os, ws, arch} configurations to build. This -# value is a '&' separated list of ',' separate triples. For example, -# configs=win32,win32,x86 & linux,motif,x86 -# By default the value is *,*,* -configs = *, *, * - -#Allow cycles involving at most one bundle that needs to be compiled with the rest being binary bundles. -allowBinaryCycles = true - -############## BUILD NAMING CONTROL ################ -# The directory into which the build elements are fetched and where -# the build takes place. -buildDirectory=${basedir}/build - -#repoBaseLocation=${buildDirectory}/repository -#transformedRepoLocation=${buildDirectory}/transformedRepo - -# Type of build. Used in naming the build output. Typically this value is -# one of I, N, M, S, ... -buildType=I - -# ID of the build. Used in naming the build output. -buildId=TapiJIBuild - -# Label for the build. Used in naming the build output -buildLabel=${buildType}.${buildId} - -# Timestamp for the build. Used in naming the build output -timestamp=007 - -#Enable / disable the generation of a suffix for the features that use .qualifier. -#The generated suffix is computed according to the content of the feature -generateFeatureVersionSuffix=true - -#Folder containing repositories whose content is needed to compile against -#repoBaseLocation=${base}/repos - -#Folder where the content of the repositories from ${repoBaseLocation} will be made available as a form suitable to be compiled against -#transformedRepoLocation=${base}/transformedRepos - -#Os/Ws/Arch/nl of the eclipse specified by baseLocation -baseos=linux -basews=linux -basearch=x86_64 - -#this property indicates whether you want the set of plug-ins and features to be considered during the build to be limited to the ones reachable from the features / plugins being built -filteredDependencyCheck=false - -#this property indicates whether the resolution should be done in development mode (i.e. ignore multiple bundles with singletons) -resolution.devMode=false - -#pluginPath is a list of locations in which to find plugins and features. This list is separated by the platform file separator (; or :) -#a location is one of: -#- the location of the jar or folder that is the plugin or feature : /path/to/foo.jar or /path/to/foo -#- a directory that contains a /plugins or /features subdirectory -#- the location of a feature.xml, or for 2.1 style plugins, the plugin.xml or fragment.xml -#pluginPath= -skipBase=true - -############# MAP FILE CONTROL ################ -# This section defines CVS tags to use when fetching the map files from the repository. -# If you want to fetch the map file from repository / location, change the getMapFiles target in the customTargets.xml - -skipMaps=true -#mapsRepo=:pserver:[email protected]/path/to/repo -#mapsRoot=path/to/maps -#mapsCheckoutTag=HEAD - -#tagMaps=true -#mapsTagTag=v${buildId} - - -############ REPOSITORY CONTROL ############### -# This section defines properties parameterizing the repositories where plugins, fragments -# bundles and features are being obtained from. - -# The tags to use when fetching elements to build. -# By default thebuilder will use whatever is in the maps. -# This value takes the form of a comma separated list of repository identifier (like used in the map files) and the -# overriding value -# For example fetchTag=CVS=HEAD, SVN=v20050101 -# fetchTag=HEAD - -#skipFetch=true -fetchTag=origin/master - -############# JAVA COMPILER OPTIONS ############## -JavaSE-1.6=${java.home}/lib/rt.jar - -# Specify the output format of the compiler log when eclipse jdt is used -#logExtension=.log - -# Whether or not to include debug info in the output jars -#javacDebugInfo=false - -# Whether or not to fail the build if there are compiler errors -#javacFailOnError=true - -# Enable or disable verbose mode of the compiler -#javacVerbose=true diff --git a/org.eclipse.babel.tapiji.tools.build/build/maps/tapiji.map b/org.eclipse.babel.tapiji.tools.build/build/maps/tapiji.map deleted file mode 100644 index dc199f3c..00000000 --- a/org.eclipse.babel.tapiji.tools.build/build/maps/tapiji.map +++ /dev/null @@ -1,35 +0,0 @@ [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.core - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.editor - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.editor.nls - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.tapiji.tools.core - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.tapiji.tools.core.ui - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.tapiji.tools.java - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.tapiji.tools.java.ui - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.tapiji.tools.rbmanager - [email protected]=GIT,\ - repo=git://git.eclipse.org/gitroot/babel/plugins.git,\ - path=org.eclipse.babel.tapiji.tools.java.feature \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.build/customTargets.xml b/org.eclipse.babel.tapiji.tools.build/customTargets.xml deleted file mode 100644 index e619a96b..00000000 --- a/org.eclipse.babel.tapiji.tools.build/customTargets.xml +++ /dev/null @@ -1,180 +0,0 @@ -<project name="customTargets.template" default="noDefault"> - - <!-- ===================================================================== --> - <!-- Run a given ${target} on all elements being built --> - <!-- Add on <ant> task for each top level element being built. --> - <!-- ===================================================================== --> - <available property="allElementsFile" file="${builder}/allElements.xml" value="${builder}/allElements.xml"/> - <property name="allElementsFile" location="${eclipse.pdebuild.templates}/headless-build/allElements.xml"/> - - <import file="${allElementsFile}" /> - <target name="allElements"> - <antcall target="allElementsDelegator" /> - </target> - - <!-- ===================================================================== --> - <!-- ===================================================================== --> - <target name="getBaseComponents" depends="checkLocalBase" unless="skipBase"> - <get src="${eclipseBaseURL}" dest="${buildDirectory}/../temp-base.zip" /> - <unzip dest="${base}" overwrite="true" src="${buildDirectory}/../temp-base.zip" /> - </target> - - <target name="checkLocalBase"> - <available file="${base}" property="skipBase" /> - </target> - - <!-- ===================================================================== --> - <!-- Check out map files from correct repository --> - <!-- Replace values for mapsCheckoutTag as desired. --> - <!-- ===================================================================== --> - <target name="getMapFiles" unless="skipMaps"> - <mkdir dir="${buildDirectory}/maps" /> - <exec executable="git" dir="${buildDirectory}/maps" output="${buildDirectory}/maps/maps.tar"> - <arg line="archive --format=tar" /> - <arg line="--remote=git.eclipse.org/gitroot/babel/plugins.git" /> - <arg line="master org.eclipse.babel.tapiji.tools.build/maps" /> - </exec> - <untar src="${buildDirectory}/maps/maps.tar" dest="${buildDirectory}/maps" /> - </target> - - <target name="checkLocalMaps"> - <available property="skipMaps" file="${buildDirectory}/maps" /> - </target> - - <target name="tagMapFiles" if="tagMaps"> - <cvs dest="${buildDirectory}/maps/${mapsRoot}" command="tag ${mapsTagTag}" /> - </target> - - <!-- ===================================================================== --> - - <target name="clean" unless="noclean"> - <antcall target="allElements"> - <param name="target" value="cleanElement" /> - </antcall> - </target> - - <target name="gatherLogs"> - <mkdir dir="${buildDirectory}/${buildLabel}/compilelogs" /> - <antcall target="allElements"> - <param name="target" value="gatherLogs" /> - </antcall> - <unzip dest="${buildDirectory}/${buildLabel}/compilelogs" overwrite="true"> - <fileset dir="${buildDirectory}/features"> - <include name="**/*.log.zip" /> - </fileset> - </unzip> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do before setup --> - <!-- ===================================================================== --> - <target name="preSetup"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after setup but before starting the build proper --> - <!-- ===================================================================== --> - <target name="postSetup"> - <antcall target="getBaseComponents" /> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do before fetching the build elements --> - <!-- ===================================================================== --> - <target name="preFetch"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after fetching the build elements --> - <!-- ===================================================================== --> - <target name="postFetch"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do before the repositories are being processed --> - <!-- ===================================================================== --> - <target name="preProcessRepos"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after the repositories have been processed --> - <!-- ===================================================================== --> - <target name="postProcessRepos"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do before generating the build scripts. --> - <!-- ===================================================================== --> - <target name="preGenerate"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after generating the build scripts. --> - <!-- ===================================================================== --> - <target name="postGenerate"> - <antcall target="clean" /> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do before running the build.xmls for the elements being built. --> - <!-- ===================================================================== --> - <target name="preProcess"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after running the build.xmls for the elements being built. --> - <!-- ===================================================================== --> - <target name="postProcess"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do before running assemble. --> - <!-- ===================================================================== --> - <target name="preAssemble"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after running assemble. --> - <!-- ===================================================================== --> - <target name="postAssemble"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do before running package. --> - <!-- ===================================================================== --> - <target name="prePackage"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after running package. --> - <!-- ===================================================================== --> - <target name="postPackage"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do after the build is done. --> - <!-- ===================================================================== --> - <target name="postBuild"> - <antcall target="gatherLogs" /> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do to test the build results --> - <!-- ===================================================================== --> - <target name="test"> - </target> - - <!-- ===================================================================== --> - <!-- Steps to do to publish the build results --> - <!-- ===================================================================== --> - <target name="publish"> - </target> - - <!-- ===================================================================== --> - <!-- Default target --> - <!-- ===================================================================== --> - <target name="noDefault"> - <echo message="You must specify a target when invoking this file" /> - </target> - -</project>
72e6b0f964e7cb14e3b907b3022cd259e1994290
intellij-community
diff: allow to highlight changes without border--
a
https://github.com/JetBrains/intellij-community
diff --git a/platform/diff-impl/src/com/intellij/diff/util/DiffDividerDrawUtil.java b/platform/diff-impl/src/com/intellij/diff/util/DiffDividerDrawUtil.java index b6db2850a8853..4b4e150d312a4 100644 --- a/platform/diff-impl/src/com/intellij/diff/util/DiffDividerDrawUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/util/DiffDividerDrawUtil.java @@ -62,13 +62,7 @@ public static void paintPolygons(@NotNull Graphics2D gg, @NotNull Editor editor1, @NotNull Editor editor2, @NotNull DividerPaintable paintable) { - List<DividerPolygon> polygons = createVisiblePolygons(editor1, editor2, paintable); - - GraphicsConfig config = GraphicsUtil.setupAAPainting(gg); - for (DividerPolygon polygon : polygons) { - polygon.paint(gg, width); - } - config.restore(); + paintPolygons(gg, width, true, true, editor1, editor2, paintable); } public static void paintSimplePolygons(@NotNull Graphics2D gg, @@ -76,11 +70,21 @@ public static void paintSimplePolygons(@NotNull Graphics2D gg, @NotNull Editor editor1, @NotNull Editor editor2, @NotNull DividerPaintable paintable) { + paintPolygons(gg, width, true, false, editor1, editor2, paintable); + } + + public static void paintPolygons(@NotNull Graphics2D gg, + int width, + boolean paintBorder, + boolean curved, + @NotNull Editor editor1, + @NotNull Editor editor2, + @NotNull DividerPaintable paintable) { List<DividerPolygon> polygons = createVisiblePolygons(editor1, editor2, paintable); GraphicsConfig config = GraphicsUtil.setupAAPainting(gg); for (DividerPolygon polygon : polygons) { - polygon.paintSimple(gg, width); + polygon.paint(gg, width, paintBorder, curved); } config.restore(); } @@ -228,13 +232,15 @@ public DividerPolygon(int start1, int start2, int end1, int end2, @NotNull Color myColor = color; } - private void paint(Graphics2D g, int width) { + private void paint(Graphics2D g, int width, boolean paintBorder, boolean curve) { + Color borderColor = paintBorder ? DiffDrawUtil.getFramingColor(myColor) : myColor; // we need this shift, because editor background highlight is painted in range "Y(line) - 1 .. Y(line + 1) - 1" - DiffDrawUtil.drawCurveTrapezium(g, 0, width, myStart1 - 1, myEnd1 - 1, myStart2 - 1, myEnd2 - 1, myColor); - } - - private void paintSimple(Graphics2D g, int width) { - DiffDrawUtil.drawTrapezium(g, 0, width, myStart1 - 1, myEnd1 - 1, myStart2 - 1, myEnd2 - 1, myColor); + if (curve) { + DiffDrawUtil.drawCurveTrapezium(g, 0, width, myStart1 - 1, myEnd1 - 1, myStart2 - 1, myEnd2 - 1, myColor, borderColor); + } + else { + DiffDrawUtil.drawTrapezium(g, 0, width, myStart1 - 1, myEnd1 - 1, myStart2 - 1, myEnd2 - 1, myColor, borderColor); + } } private void paintOnScrollbar(Graphics2D g, int width) { diff --git a/platform/diff-impl/src/com/intellij/diff/util/DiffDrawUtil.java b/platform/diff-impl/src/com/intellij/diff/util/DiffDrawUtil.java index 57d26dbc4f242..f677ea9d4ae55 100644 --- a/platform/diff-impl/src/com/intellij/diff/util/DiffDrawUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/util/DiffDrawUtil.java @@ -70,15 +70,28 @@ public static void drawTrapezium(@NotNull Graphics2D g, int start1, int end1, int start2, int end2, @NotNull Color color) { + drawTrapezium(g, x1, x2, start1, end1, start2, end2, color, getFramingColor(color)); + } + + public static void drawTrapezium(@NotNull Graphics2D g, + int x1, int x2, + int start1, int end1, + int start2, int end2, + @Nullable Color fillColor, + @Nullable Color borderColor) { final int[] xPoints = new int[]{x1, x2, x2, x1}; final int[] yPoints = new int[]{start1, start2, end2, end1}; - g.setColor(color); - g.fillPolygon(xPoints, yPoints, xPoints.length); + if (fillColor != null) { + g.setColor(fillColor); + g.fillPolygon(xPoints, yPoints, xPoints.length); + } - g.setColor(getFramingColor(color)); - g.drawLine(x1, start1, x2, start2); - g.drawLine(x1, end1, x2, end2); + if (borderColor != null) { + g.setColor(borderColor); + g.drawLine(x1, start1, x2, start2); + g.drawLine(x1, end1, x2, end2); + } } public static void drawCurveTrapezium(@NotNull Graphics2D g,
06d24042b64d6fa0e179b5845990068f849d9ce5
hadoop
YARN-1185. Fixed FileSystemRMStateStore to not- leave partial files that prevent subsequent ResourceManager recovery.- Contributed by Omkar Vinit Joshi. svn merge --ignore-ancestry -c 1533803- ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1533805 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 27cf02c418127..8c0ea418f00a0 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -105,6 +105,9 @@ Release 2.2.1 - UNRELEASED YARN-1295. In UnixLocalWrapperScriptBuilder, using bash -c can cause Text file busy errors (Sandy Ryza) + YARN-1185. Fixed FileSystemRMStateStore to not leave partial files that + prevent subsequent ResourceManager recovery. (Omkar Vinit Joshi via vinodkv) + Release 2.2.0 - 2013-10-13 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/recovery/FileSystemRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java index 062f5cc55329e..e85ba924a1a74 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java @@ -22,6 +22,7 @@ import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; +import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -118,6 +119,9 @@ private void loadRMAppState(RMState rmState) throws Exception { for (FileStatus childNodeStatus : fs.listStatus(appDir.getPath())) { assert childNodeStatus.isFile(); String childNodeName = childNodeStatus.getPath().getName(); + if (checkAndRemovePartialRecord(childNodeStatus.getPath())) { + continue; + } byte[] childData = readFile(childNodeStatus.getPath(), childNodeStatus.getLen()); if (childNodeName.startsWith(ApplicationId.appIdStrPrefix)) { @@ -178,12 +182,28 @@ private void loadRMAppState(RMState rmState) throws Exception { } } + private boolean checkAndRemovePartialRecord(Path record) throws IOException { + // If the file ends with .tmp then it shows that it failed + // during saving state into state store. The file will be deleted as a + // part of this call + if (record.getName().endsWith(".tmp")) { + LOG.error("incomplete rm state store entry found :" + + record); + fs.delete(record, false); + return true; + } + return false; + } + private void loadRMDTSecretManagerState(RMState rmState) throws Exception { FileStatus[] childNodes = fs.listStatus(rmDTSecretManagerRoot); for(FileStatus childNodeStatus : childNodes) { assert childNodeStatus.isFile(); String childNodeName = childNodeStatus.getPath().getName(); + if (checkAndRemovePartialRecord(childNodeStatus.getPath())) { + continue; + } if(childNodeName.startsWith(DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX)) { rmState.rmSecretManagerState.dtSequenceNumber = Integer.parseInt(childNodeName.split("_")[1]); @@ -344,10 +364,19 @@ private byte[] readFile(Path inputPath, long len) throws Exception { return data; } + /* + * In order to make this write atomic as a part of write we will first write + * data to .tmp file and then rename it. Here we are assuming that rename is + * atomic for underlying file system. + */ private void writeFile(Path outputPath, byte[] data) throws Exception { - FSDataOutputStream fsOut = fs.create(outputPath, false); + Path tempPath = + new Path(outputPath.getParent(), outputPath.getName() + ".tmp"); + FSDataOutputStream fsOut = null; + fsOut = fs.create(tempPath, false); fsOut.write(data); fsOut.close(); + fs.rename(tempPath, outputPath); } private boolean renameFile(Path src, Path dst) throws Exception { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java similarity index 80% rename from hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestRMStateStore.java rename to hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java index d75fc7d9e18a6..72ef37fa23658 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java @@ -39,6 +39,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; @@ -75,9 +76,9 @@ import org.junit.Test; -public class TestRMStateStore extends ClientBaseWithFixes{ +public class RMStateStoreTestBase extends ClientBaseWithFixes{ - public static final Log LOG = LogFactory.getLog(TestRMStateStore.class); + public static final Log LOG = LogFactory.getLog(RMStateStoreTestBase.class); static class TestDispatcher implements Dispatcher, EventHandler<RMAppAttemptStoredEvent> { @@ -116,104 +117,6 @@ interface RMStateStoreHelper { boolean isFinalStateValid() throws Exception; } - @Test - public void testZKRMStateStoreRealZK() throws Exception { - TestZKRMStateStoreTester zkTester = new TestZKRMStateStoreTester(); - testRMAppStateStore(zkTester); - testRMDTSecretManagerStateStore(zkTester); - } - - @Test - public void testFSRMStateStore() throws Exception { - HdfsConfiguration conf = new HdfsConfiguration(); - MiniDFSCluster cluster = - new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); - try { - TestFSRMStateStoreTester fsTester = new TestFSRMStateStoreTester(cluster); - testRMAppStateStore(fsTester); - testRMDTSecretManagerStateStore(fsTester); - } finally { - cluster.shutdown(); - } - } - - class TestZKRMStateStoreTester implements RMStateStoreHelper { - ZooKeeper client; - ZKRMStateStore store; - - class TestZKRMStateStore extends ZKRMStateStore { - public TestZKRMStateStore(Configuration conf, String workingZnode) - throws Exception { - init(conf); - start(); - assertTrue(znodeWorkingPath.equals(workingZnode)); - } - - @Override - public ZooKeeper getNewZooKeeper() throws IOException { - return client; - } - } - - public RMStateStore getRMStateStore() throws Exception { - String workingZnode = "/Test"; - YarnConfiguration conf = new YarnConfiguration(); - conf.set(YarnConfiguration.ZK_RM_STATE_STORE_ADDRESS, hostPort); - conf.set(YarnConfiguration.ZK_RM_STATE_STORE_PARENT_PATH, workingZnode); - this.client = createClient(); - this.store = new TestZKRMStateStore(conf, workingZnode); - return this.store; - } - - @Override - public boolean isFinalStateValid() throws Exception { - List<String> nodes = client.getChildren(store.znodeWorkingPath, false); - return nodes.size() == 1; - } - } - - class TestFSRMStateStoreTester implements RMStateStoreHelper { - Path workingDirPathURI; - FileSystemRMStateStore store; - MiniDFSCluster cluster; - - class TestFileSystemRMStore extends FileSystemRMStateStore { - TestFileSystemRMStore(Configuration conf) throws Exception { - init(conf); - Assert.assertNull(fs); - assertTrue(workingDirPathURI.equals(fsWorkingPath)); - start(); - Assert.assertNotNull(fs); - } - } - - public TestFSRMStateStoreTester(MiniDFSCluster cluster) throws Exception { - Path workingDirPath = new Path("/Test"); - this.cluster = cluster; - FileSystem fs = cluster.getFileSystem(); - fs.mkdirs(workingDirPath); - Path clusterURI = new Path(cluster.getURI()); - workingDirPathURI = new Path(clusterURI, workingDirPath); - fs.close(); - } - - @Override - public RMStateStore getRMStateStore() throws Exception { - YarnConfiguration conf = new YarnConfiguration(); - conf.set(YarnConfiguration.FS_RM_STATE_STORE_URI, - workingDirPathURI.toString()); - this.store = new TestFileSystemRMStore(conf); - return store; - } - - @Override - public boolean isFinalStateValid() throws Exception { - FileSystem fs = cluster.getFileSystem(); - FileStatus[] files = fs.listStatus(workingDirPathURI); - return files.length == 1; - } - } - void waitNotify(TestDispatcher dispatcher) { long startTime = System.currentTimeMillis(); while(!dispatcher.notified) { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java new file mode 100644 index 0000000000000..a1a6eab3fd3d5 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java @@ -0,0 +1,120 @@ +/** + * 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.resourcemanager.recovery; + +import static org.junit.Assert.assertTrue; +import junit.framework.Assert; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FSDataOutputStream; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hdfs.HdfsConfiguration; +import org.apache.hadoop.hdfs.MiniDFSCluster; +import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.util.ConverterUtils; +import org.junit.Test; + +public class TestFSRMStateStore extends RMStateStoreTestBase { + + public static final Log LOG = LogFactory.getLog(TestFSRMStateStore.class); + + class TestFSRMStateStoreTester implements RMStateStoreHelper { + + Path workingDirPathURI; + FileSystemRMStateStore store; + MiniDFSCluster cluster; + + class TestFileSystemRMStore extends FileSystemRMStateStore { + + TestFileSystemRMStore(Configuration conf) throws Exception { + init(conf); + Assert.assertNull(fs); + assertTrue(workingDirPathURI.equals(fsWorkingPath)); + start(); + Assert.assertNotNull(fs); + } + } + + public TestFSRMStateStoreTester(MiniDFSCluster cluster) throws Exception { + Path workingDirPath = new Path("/Test"); + this.cluster = cluster; + FileSystem fs = cluster.getFileSystem(); + fs.mkdirs(workingDirPath); + Path clusterURI = new Path(cluster.getURI()); + workingDirPathURI = new Path(clusterURI, workingDirPath); + fs.close(); + } + + @Override + public RMStateStore getRMStateStore() throws Exception { + YarnConfiguration conf = new YarnConfiguration(); + conf.set(YarnConfiguration.FS_RM_STATE_STORE_URI, + workingDirPathURI.toString()); + this.store = new TestFileSystemRMStore(conf); + return store; + } + + @Override + public boolean isFinalStateValid() throws Exception { + FileSystem fs = cluster.getFileSystem(); + FileStatus[] files = fs.listStatus(workingDirPathURI); + return files.length == 1; + } + } + + @Test + public void testFSRMStateStore() throws Exception { + HdfsConfiguration conf = new HdfsConfiguration(); + MiniDFSCluster cluster = + new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); + try { + TestFSRMStateStoreTester fsTester = new TestFSRMStateStoreTester(cluster); + // If the state store is FileSystemRMStateStore then add corrupted entry. + // It should discard the entry and remove it from file system. + FSDataOutputStream fsOut = null; + FileSystemRMStateStore fileSystemRMStateStore = + (FileSystemRMStateStore) fsTester.getRMStateStore(); + String appAttemptIdStr3 = "appattempt_1352994193343_0001_000003"; + ApplicationAttemptId attemptId3 = + ConverterUtils.toApplicationAttemptId(appAttemptIdStr3); + Path rootDir = + new Path(fileSystemRMStateStore.fsWorkingPath, "FSRMStateRoot"); + Path appRootDir = new Path(rootDir, "RMAppRoot"); + Path appDir = + new Path(appRootDir, attemptId3.getApplicationId().toString()); + Path tempAppAttemptFile = + new Path(appDir, attemptId3.toString() + ".tmp"); + fsOut = fileSystemRMStateStore.fs.create(tempAppAttemptFile, false); + fsOut.write("Some random data ".getBytes()); + fsOut.close(); + + testRMAppStateStore(fsTester); + Assert.assertFalse(fileSystemRMStateStore.fsWorkingPath + .getFileSystem(conf).exists(tempAppAttemptFile)); + testRMDTSecretManagerStateStore(fsTester); + } finally { + cluster.shutdown(); + } + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java new file mode 100644 index 0000000000000..a6929a8936635 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java @@ -0,0 +1,80 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.resourcemanager.recovery; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.zookeeper.ZooKeeper; +import org.junit.Test; + +public class TestZKRMStateStore extends RMStateStoreTestBase { + + public static final Log LOG = LogFactory.getLog(TestZKRMStateStore.class); + + class TestZKRMStateStoreTester implements RMStateStoreHelper { + + ZooKeeper client; + ZKRMStateStore store; + + class TestZKRMStateStoreInternal extends ZKRMStateStore { + + public TestZKRMStateStoreInternal(Configuration conf, String workingZnode) + throws Exception { + init(conf); + start(); + assertTrue(znodeWorkingPath.equals(workingZnode)); + } + + @Override + public ZooKeeper getNewZooKeeper() throws IOException { + return client; + } + } + + public RMStateStore getRMStateStore() throws Exception { + String workingZnode = "/Test"; + YarnConfiguration conf = new YarnConfiguration(); + conf.set(YarnConfiguration.ZK_RM_STATE_STORE_ADDRESS, hostPort); + conf.set(YarnConfiguration.ZK_RM_STATE_STORE_PARENT_PATH, workingZnode); + this.client = createClient(); + this.store = new TestZKRMStateStoreInternal(conf, workingZnode); + return this.store; + } + + @Override + public boolean isFinalStateValid() throws Exception { + List<String> nodes = client.getChildren(store.znodeWorkingPath, false); + return nodes.size() == 1; + } + } + + @Test + public void testZKRMStateStoreRealZK() throws Exception { + TestZKRMStateStoreTester zkTester = new TestZKRMStateStoreTester(); + testRMAppStateStore(zkTester); + testRMDTSecretManagerStateStore(zkTester); + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java index 7c807a5b60202..82e550c9173cc 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java @@ -24,7 +24,7 @@ import org.apache.hadoop.ha.ClientBaseWithFixes; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.conf.YarnConfiguration; -import org.apache.hadoop.yarn.server.resourcemanager.recovery.TestRMStateStore.TestDispatcher; +import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreTestBase.TestDispatcher; import org.apache.hadoop.util.ZKUtil; import org.apache.zookeeper.CreateMode; @@ -43,17 +43,20 @@ public class TestZKRMStateStoreZKClientConnections extends ClientBaseWithFixes { + private static final int ZK_OP_WAIT_TIME = 3000; private Log LOG = LogFactory.getLog(TestZKRMStateStoreZKClientConnections.class); class TestZKClient { + ZKRMStateStore store; boolean forExpire = false; TestForwardingWatcher watcher; CyclicBarrier syncBarrier = new CyclicBarrier(2); protected class TestZKRMStateStore extends ZKRMStateStore { + public TestZKRMStateStore(Configuration conf, String workingZnode) throws Exception { init(conf); @@ -87,6 +90,7 @@ public synchronized void processWatchEvent(WatchedEvent event) private class TestForwardingWatcher extends ClientBaseWithFixes.CountdownWatcher { + public void process(WatchedEvent event) { super.process(event); try { @@ -187,7 +191,7 @@ public void testZKSessionTimeout() throws Exception { } } - @Test (timeout = 20000) + @Test(timeout = 20000) public void testSetZKAcl() { TestZKClient zkClientTester = new TestZKClient(); YarnConfiguration conf = new YarnConfiguration(); @@ -196,10 +200,11 @@ public void testSetZKAcl() { zkClientTester.store.zkClient.delete(zkClientTester.store .znodeWorkingPath, -1); fail("Shouldn't be able to delete path"); - } catch (Exception e) {/* expected behavior */} + } catch (Exception e) {/* expected behavior */ + } } - @Test (timeout = 20000) + @Test(timeout = 20000) public void testInvalidZKAclConfiguration() { TestZKClient zkClientTester = new TestZKClient(); YarnConfiguration conf = new YarnConfiguration();
d601eb65a29ff3cae3d23f8dcac401834b94e8e1
Vala
gio-2.0: nullability fixes for g_file_replace_contents Fixes bug 611282.
c
https://github.com/GNOME/vala/
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi index dad2a774af..e62d5175d1 100644 --- a/vapi/gio-2.0.vapi +++ b/vapi/gio-2.0.vapi @@ -1062,8 +1062,8 @@ namespace GLib { 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 (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; diff --git a/vapi/packages/gio-2.0/gio-2.0.metadata b/vapi/packages/gio-2.0/gio-2.0.metadata index a5921ef94a..d2de38807f 100644 --- a/vapi/packages/gio-2.0/gio-2.0.metadata +++ b/vapi/packages/gio-2.0/gio-2.0.metadata @@ -73,8 +73,8 @@ g_file_read_finish transfer_ownership="1" 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" -g_file_replace_contents_finish.new_etag transfer_ownership="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_finish transfer_ownership="1" g_file_resolve_relative_path transfer_ownership="1" g_file_start_mountable async="1"
2b97a4cce4dc1bd0528e960f364edfa132d6bfa3
hadoop
svn merge -c 1371390 FIXES: YARN-14. Symlinks to- peer distributed cache files no longer work (Jason Lowe via bobby)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1371395 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 1ae8a9dd1bf08..9cfad504cc408 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -36,3 +36,16 @@ Release 2.1.0-alpha - Unreleased YARN-12. Fix findbugs warnings in FairScheduler. (Junping Du via acmurthy) +Release 0.23.3 - Unreleased + + INCOMPATIBLE CHANGES + + NEW FEATURES + + IMPROVEMENTS + + BUG FIXES + + YARN-14. Symlinks to peer distributed cache files no longer work + (Jason Lowe via bobby) + 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/container/Container.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/Container.java index e5ba3f2993609..af0f92ee6fc10 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/Container.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/Container.java @@ -18,6 +18,7 @@ package org.apache.hadoop.yarn.server.nodemanager.containermanager.container; +import java.util.List; import java.util.Map; import org.apache.hadoop.fs.Path; @@ -38,7 +39,7 @@ public interface Container extends EventHandler<ContainerEvent> { Credentials getCredentials(); - Map<Path,String> getLocalizedResources(); + Map<Path,List<String>> getLocalizedResources(); ContainerStatus cloneAndGetContainerStatus(); 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/container/ContainerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java index 1cbdbaa8146bc..c9802080854f9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java @@ -84,10 +84,10 @@ public class ContainerImpl implements Container { private static final Log LOG = LogFactory.getLog(Container.class); private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); - private final Map<LocalResourceRequest,String> pendingResources = - new HashMap<LocalResourceRequest,String>(); - private final Map<Path,String> localizedResources = - new HashMap<Path,String>(); + private final Map<LocalResourceRequest,List<String>> pendingResources = + new HashMap<LocalResourceRequest,List<String>>(); + private final Map<Path,List<String>> localizedResources = + new HashMap<Path,List<String>>(); private final List<LocalResourceRequest> publicRsrcs = new ArrayList<LocalResourceRequest>(); private final List<LocalResourceRequest> privateRsrcs = @@ -327,7 +327,7 @@ public String getUser() { } @Override - public Map<Path,String> getLocalizedResources() { + public Map<Path,List<String>> getLocalizedResources() { this.readLock.lock(); try { assert ContainerState.LOCALIZED == getContainerState(); // TODO: FIXME!! @@ -496,20 +496,25 @@ public ContainerState transition(ContainerImpl container, try { for (Map.Entry<String,LocalResource> rsrc : cntrRsrc.entrySet()) { try { - LocalResourceRequest req = - new LocalResourceRequest(rsrc.getValue()); - container.pendingResources.put(req, rsrc.getKey()); - switch (rsrc.getValue().getVisibility()) { - case PUBLIC: - container.publicRsrcs.add(req); - break; - case PRIVATE: - container.privateRsrcs.add(req); - break; - case APPLICATION: - container.appRsrcs.add(req); - break; - } + LocalResourceRequest req = + new LocalResourceRequest(rsrc.getValue()); + List<String> links = container.pendingResources.get(req); + if (links == null) { + links = new ArrayList<String>(); + container.pendingResources.put(req, links); + } + links.add(rsrc.getKey()); + switch (rsrc.getValue().getVisibility()) { + case PUBLIC: + container.publicRsrcs.add(req); + break; + case PRIVATE: + container.privateRsrcs.add(req); + break; + case APPLICATION: + container.appRsrcs.add(req); + break; + } } catch (URISyntaxException e) { LOG.info("Got exception parsing " + rsrc.getKey() + " and value " + rsrc.getValue()); @@ -560,15 +565,16 @@ static class LocalizedTransition implements public ContainerState transition(ContainerImpl container, ContainerEvent event) { ContainerResourceLocalizedEvent rsrcEvent = (ContainerResourceLocalizedEvent) event; - String sym = container.pendingResources.remove(rsrcEvent.getResource()); - if (null == sym) { + List<String> syms = + container.pendingResources.remove(rsrcEvent.getResource()); + if (null == syms) { LOG.warn("Localized unknown resource " + rsrcEvent.getResource() + " for container " + container.getContainerID()); assert false; // fail container? return ContainerState.LOCALIZING; } - container.localizedResources.put(rsrcEvent.getLocation(), sym); + container.localizedResources.put(rsrcEvent.getLocation(), syms); if (!container.pendingResources.isEmpty()) { return ContainerState.LOCALIZING; } @@ -728,15 +734,16 @@ static class LocalizedResourceDuringKillTransition implements @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerResourceLocalizedEvent rsrcEvent = (ContainerResourceLocalizedEvent) event; - String sym = container.pendingResources.remove(rsrcEvent.getResource()); - if (null == sym) { + List<String> syms = + container.pendingResources.remove(rsrcEvent.getResource()); + if (null == syms) { LOG.warn("Localized unknown resource " + rsrcEvent.getResource() + " for container " + container.getContainerID()); assert false; // fail container? return; } - container.localizedResources.put(rsrcEvent.getLocation(), sym); + container.localizedResources.put(rsrcEvent.getLocation(), syms); } } 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 821d4a042b3cc..b06788341fe5c 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 @@ -111,7 +111,8 @@ public ContainerLaunch(Configuration configuration, Dispatcher dispatcher, @SuppressWarnings("unchecked") // dispatcher not typed public Integer call() { final ContainerLaunchContext launchContext = container.getLaunchContext(); - final Map<Path,String> localResources = container.getLocalizedResources(); + final Map<Path,List<String>> localResources = + container.getLocalizedResources(); ContainerId containerID = container.getContainerID(); String containerIdStr = ConverterUtils.toString(containerID); final String user = launchContext.getUser(); @@ -533,7 +534,7 @@ public void sanitizeEnv(Map<String, String> environment, } static void writeLaunchEnv(OutputStream out, - Map<String,String> environment, Map<Path,String> resources, + Map<String,String> environment, Map<Path,List<String>> resources, List<String> command) throws IOException { ShellScriptBuilder sb = new ShellScriptBuilder(); @@ -543,8 +544,10 @@ static void writeLaunchEnv(OutputStream out, } } if (resources != null) { - for (Map.Entry<Path,String> link : resources.entrySet()) { - sb.symlink(link.getKey(), link.getValue()); + for (Map.Entry<Path,List<String>> entry : resources.entrySet()) { + for (String linkName : entry.getValue()) { + sb.symlink(entry.getKey(), linkName); + } } } 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/container/TestContainer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java index bc6ec196e17ea..cb7c19dc2faee 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java @@ -29,12 +29,15 @@ import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.AbstractMap.SimpleEntry; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; @@ -111,11 +114,12 @@ public void testLocalizationLaunch() throws Exception { wc = new WrappedContainer(8, 314159265358979L, 4344, "yak"); assertEquals(ContainerState.NEW, wc.c.getContainerState()); wc.initContainer(); - Map<Path, String> localPaths = wc.localizeResources(); + Map<Path, List<String>> localPaths = wc.localizeResources(); // all resources should be localized assertEquals(ContainerState.LOCALIZED, wc.c.getContainerState()); - for (Entry<Path,String> loc : wc.c.getLocalizedResources().entrySet()) { + for (Entry<Path, List<String>> loc : wc.c.getLocalizedResources() + .entrySet()) { assertEquals(localPaths.remove(loc.getKey()), loc.getValue()); } assertTrue(localPaths.isEmpty()); @@ -578,10 +582,12 @@ public void initContainer() { // Localize resources // Skip some resources so as to consider them failed - public Map<Path, String> doLocalizeResources(boolean checkLocalizingState, - int skipRsrcCount) throws URISyntaxException { + public Map<Path, List<String>> doLocalizeResources( + boolean checkLocalizingState, int skipRsrcCount) + throws URISyntaxException { Path cache = new Path("file:///cache"); - Map<Path, String> localPaths = new HashMap<Path, String>(); + Map<Path, List<String>> localPaths = + new HashMap<Path, List<String>>(); int counter = 0; for (Entry<String, LocalResource> rsrc : localResources.entrySet()) { if (counter++ < skipRsrcCount) { @@ -592,7 +598,7 @@ public Map<Path, String> doLocalizeResources(boolean checkLocalizingState, } LocalResourceRequest req = new LocalResourceRequest(rsrc.getValue()); Path p = new Path(cache, rsrc.getKey()); - localPaths.put(p, rsrc.getKey()); + localPaths.put(p, Arrays.asList(rsrc.getKey())); // rsrc copied to p c.handle(new ContainerResourceLocalizedEvent(c.getContainerID(), req, p)); @@ -602,7 +608,8 @@ public Map<Path, String> doLocalizeResources(boolean checkLocalizingState, } - public Map<Path, String> localizeResources() throws URISyntaxException { + public Map<Path, List<String>> localizeResources() + throws URISyntaxException { return doLocalizeResources(true, 0); } 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/launcher/TestContainerLaunch.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java index bdd77f8a20b4b..822835dc3d08b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java @@ -28,6 +28,7 @@ import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -95,9 +96,10 @@ public void testSpecialCharSymlinks() throws IOException { writer.println(timeoutCommand); writer.close(); - Map<Path, String> resources = new HashMap<Path, String>(); + Map<Path, List<String>> resources = + new HashMap<Path, List<String>>(); Path path = new Path(shellFile.getAbsolutePath()); - resources.put(path, badSymlink); + resources.put(path, Arrays.asList(badSymlink)); FileOutputStream fos = new FileOutputStream(tempFile); 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/MockContainer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/MockContainer.java index 1b2e0653d06ff..519ff1834840d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/MockContainer.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/MockContainer.java @@ -19,6 +19,7 @@ package org.apache.hadoop.yarn.server.nodemanager.webapp; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; @@ -43,7 +44,8 @@ public class MockContainer implements Container { private ContainerState state; private String user; private ContainerLaunchContext launchContext; - private final Map<Path, String> resource = new HashMap<Path, String>(); + private final Map<Path, List<String>> resource = + new HashMap<Path, List<String>>(); private RecordFactory recordFactory; public MockContainer(ApplicationAttemptId appAttemptId, @@ -92,7 +94,7 @@ public Credentials getCredentials() { } @Override - public Map<Path, String> getLocalizedResources() { + public Map<Path, List<String>> getLocalizedResources() { return resource; }
4b946ebdf22a25d8f01c87845ae177d7343ae616
hadoop
MAPREDUCE-2784. [Gridmix] Bug fixes in- ExecutionSummarizer and ResourceUsageMatcher. (amarrk)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1237579 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt index d95872f18fceb..64176dc7b116b 100644 --- a/hadoop-mapreduce-project/CHANGES.txt +++ b/hadoop-mapreduce-project/CHANGES.txt @@ -176,6 +176,9 @@ Release 0.23.1 - Unreleased on the webapps. (Bhallamudi Venkata Siva Kamesh and Jason Lowe via vinodkv) BUG FIXES + MAPREDUCE-2784. [Gridmix] Bug fixes in ExecutionSummarizer and + ResourceUsageMatcher. (amarrk) + MAPREDUCE-3194. "mapred mradmin" command is broken in mrv2 (Jason Lowe via bobby) diff --git a/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/ExecutionSummarizer.java b/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/ExecutionSummarizer.java index f59bf9e66c72c..fc362c5643a31 100644 --- a/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/ExecutionSummarizer.java +++ b/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/ExecutionSummarizer.java @@ -149,10 +149,15 @@ void finalize(JobFactory factory, String inputPath, long dataSize, throws IOException { numJobsInInputTrace = factory.numJobsInTrace; endTime = System.currentTimeMillis(); - Path inputTracePath = new Path(inputPath); - FileSystem fs = inputTracePath.getFileSystem(conf); - inputTraceLocation = fs.makeQualified(inputTracePath).toString(); - inputTraceSignature = getTraceSignature(inputTraceLocation); + if ("-".equals(inputPath)) { + inputTraceLocation = Summarizer.NA; + inputTraceSignature = Summarizer.NA; + } else { + Path inputTracePath = new Path(inputPath); + FileSystem fs = inputTracePath.getFileSystem(conf); + inputTraceLocation = fs.makeQualified(inputTracePath).toString(); + inputTraceSignature = getTraceSignature(inputPath); + } jobSubmissionPolicy = Gridmix.getJobSubmissionPolicy(conf).name(); resolver = userResolver.getClass().getName(); if (dataSize > 0) { diff --git a/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Gridmix.java b/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Gridmix.java index 902351cd7bf8e..b4a0e0b5e2dab 100644 --- a/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Gridmix.java +++ b/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Gridmix.java @@ -314,9 +314,13 @@ public Integer run() throws Exception { } }); - // print the run summary - System.out.print("\n\n"); - System.out.println(summarizer.toString()); + // print the gridmix summary if the run was successful + if (val == 0) { + // print the run summary + System.out.print("\n\n"); + System.out.println(summarizer.toString()); + } + return val; } diff --git a/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/emulators/resourceusage/ResourceUsageMatcher.java b/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/emulators/resourceusage/ResourceUsageMatcher.java index 10d6e733f1c00..917cd09372a68 100644 --- a/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/emulators/resourceusage/ResourceUsageMatcher.java +++ b/hadoop-mapreduce-project/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/emulators/resourceusage/ResourceUsageMatcher.java @@ -52,15 +52,23 @@ public class ResourceUsageMatcher { @SuppressWarnings("unchecked") public void configure(Configuration conf, ResourceCalculatorPlugin monitor, ResourceUsageMetrics metrics, Progressive progress) { - Class[] plugins = - conf.getClasses(RESOURCE_USAGE_EMULATION_PLUGINS, - ResourceUsageEmulatorPlugin.class); + Class[] plugins = conf.getClasses(RESOURCE_USAGE_EMULATION_PLUGINS); if (plugins == null) { System.out.println("No resource usage emulator plugins configured."); } else { - for (Class<? extends ResourceUsageEmulatorPlugin> plugin : plugins) { - if (plugin != null) { - emulationPlugins.add(ReflectionUtils.newInstance(plugin, conf)); + for (Class clazz : plugins) { + if (clazz != null) { + if (ResourceUsageEmulatorPlugin.class.isAssignableFrom(clazz)) { + ResourceUsageEmulatorPlugin plugin = + (ResourceUsageEmulatorPlugin) ReflectionUtils.newInstance(clazz, + conf); + emulationPlugins.add(plugin); + } else { + throw new RuntimeException("Misconfigured resource usage plugins. " + + "Class " + clazz.getClass().getName() + " is not a resource " + + "usage plugin as it does not extend " + + ResourceUsageEmulatorPlugin.class.getName()); + } } } } diff --git a/hadoop-mapreduce-project/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestGridmixSummary.java b/hadoop-mapreduce-project/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestGridmixSummary.java index 452d2f5604201..64af603bec538 100644 --- a/hadoop-mapreduce-project/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestGridmixSummary.java +++ b/hadoop-mapreduce-project/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestGridmixSummary.java @@ -159,7 +159,7 @@ public void update(Object item) { @Override protected Thread createReaderThread() { - return null; + return new Thread(); } } @@ -243,7 +243,7 @@ public void testExecutionSummarizer() throws IOException { tid, es.getInputTraceSignature()); // test trace location Path qPath = fs.makeQualified(testTraceFile); - assertEquals("Mismatch in trace signature", + assertEquals("Mismatch in trace filename", qPath.toString(), es.getInputTraceLocation()); // test expected data size assertEquals("Mismatch in expected data size", @@ -275,7 +275,7 @@ public void testExecutionSummarizer() throws IOException { es.finalize(factory, testTraceFile.toString(), 0L, resolver, dataStats, conf); // test missing expected data size - assertEquals("Mismatch in trace signature", + assertEquals("Mismatch in trace data size", Summarizer.NA, es.getExpectedDataSize()); assertFalse("Mismatch in trace signature", tid.equals(es.getInputTraceSignature())); @@ -295,6 +295,12 @@ public void testExecutionSummarizer() throws IOException { assertEquals("Mismatch in trace signature", tid, es.getInputTraceSignature()); + // finalize trace identifier '-' input + es.finalize(factory, "-", 0L, resolver, dataStats, conf); + assertEquals("Mismatch in trace signature", + Summarizer.NA, es.getInputTraceSignature()); + assertEquals("Mismatch in trace file location", + Summarizer.NA, es.getInputTraceLocation()); } // test the ExecutionSummarizer
c5eb3ffd538efde455c7f72444094a890fe318a5
internetarchive$heritrix3
[HER-1053] compressed HTTP fetch: "Accept-encoding: gzip" [HER-728] Offer replay stream that has been un-chunked (whether because response was HTTP/1.1 or used chunked in HTTP/1.0 against spec) [HER-1876] Offer HTTP/1.1 option - for chunked transfer-encoding (but not persistent connections) * FetchHTTP add 'acceptCompression' and 'useHTTP11' properties, both default false * Recorder track whether recorded-input is transfer-encoded (chunked) or content-encoded (gzip etc) offer alternate replay streams for (1) raw 'messageBody'; (2) entity (un-chunked if necessary) (3) content (decompressed if necessary) always content & GenericReplayCharSequence for CharSequence replays * GenericReplayCharSequence always use a stream (rather than random-access buffer) always decode to prefix buffer first, so short content never touches disk no matter the encoding * InMemoryReplayCharSequence deleted; 'Generic' now works similarly for small content and anyway random-access for single-byte-encodings is now rarely possible (given deconding streams) * RecordingInputStream, RecordingOutputStream adjust for changed stream names, functionality moved to Recorder * ReplayCharSequence use Charset instances rather than names * ReplayInputStream add convenience constructor (and tmp-file-destroy) for copying any other inputStream into a seekable ReplayInputStream
p
https://github.com/internetarchive/heritrix3
diff --git a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java b/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java index d61d729b7..9294e08a4 100644 --- a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java +++ b/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java @@ -20,26 +20,29 @@ package org.archive.io; import java.io.BufferedReader; -import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; -import java.nio.ByteBuffer; +import java.io.Writer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; import java.text.NumberFormat; import java.util.logging.Level; import java.util.logging.Logger; +import org.apache.commons.io.IOUtils; import org.archive.util.DevUtils; +import com.google.common.base.Charsets; +import com.google.common.primitives.Ints; + /** * (Replay)CharSequence view on recorded streams. * @@ -47,8 +50,8 @@ * * <p>Call {@link close()} on this class when done to clean up resources. * - * @author stack - * @author nlevitt + * @contributor stack + * @contributor nlevitt * @version $Revision$, $Date$ */ public class GenericReplayCharSequence implements ReplayCharSequence { @@ -66,7 +69,7 @@ public class GenericReplayCharSequence implements ReplayCharSequence { * * <p>See <a ref="http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html">Encoding</a>. */ - private static final String WRITE_ENCODING = "UTF-16BE"; + public static final Charset WRITE_ENCODING = Charsets.UTF_16BE; private static final long MAP_MAX_BYTES = 64 * 1024 * 1024; // 64M @@ -78,7 +81,7 @@ public class GenericReplayCharSequence implements ReplayCharSequence { * <code>MAP_MAX_BYTES - MAP_TARGET_LEFT_PADDING</code> * bytes to the right of the target. */ - private static final long MAP_TARGET_LEFT_PADDING_BYTES = (long) (MAP_MAX_BYTES * 0.2); + private static final long MAP_TARGET_LEFT_PADDING_BYTES = (long) (MAP_MAX_BYTES * 0.01); /** * Total length of character stream to replay minus the HTTP headers @@ -108,11 +111,7 @@ public class GenericReplayCharSequence implements ReplayCharSequence { private long bytesPerChar; - private ByteBuffer mappedBuffer = null; - - private CharsetDecoder decoder = null; - - private ByteBuffer tempBuf = null; + private CharBuffer mappedBuffer = null; /** * File that has decoded content. @@ -133,90 +132,53 @@ public class GenericReplayCharSequence implements ReplayCharSequence { /** * Constructor. * - * @param buffer In-memory buffer of recordings prefix. We read from - * here first and will only go to the backing file if <code>size</code> - * requested is greater than <code>buffer.length</code>. - * @param size Total size of stream to replay in bytes. Used to find - * EOS. This is total length of content including HTTP headers if - * present. * @param contentReplayInputStream inputStream of content - * @param charsetName Encoding to use reading the passed prefix - * buffer and backing file. For now, should be java canonical name for the - * encoding. Must not be null. + * @param charset Encoding to use reading the passed prefix + * buffer and backing file. Must not be null. * @param backingFilename Path to backing file with content in excess of * whats in <code>buffer</code>. * * @throws IOException */ - public GenericReplayCharSequence( - ReplayInputStream contentReplayInputStream, String backingFilename, - String charsetName) throws IOException { + public GenericReplayCharSequence(InputStream contentReplayInputStream, + int prefixMax, + String backingFilename, + Charset charset) throws IOException { super(); logger.fine("new GenericReplayCharSequence() characterEncoding=" - + charsetName + " backingFilename=" + backingFilename); - Charset charset; - try { - charset = Charset.forName(charsetName); - } catch (IllegalArgumentException e) { - logger.log(Level.WARNING,"charset problem: "+charsetName,e); - // TODO: better detection or default - charset = Charset.forName(FALLBACK_CHARSET_NAME); - } - if (charset.newEncoder().maxBytesPerChar() == 1.0) { - logger.fine("charset=" + charsetName - + ": supports random access, using backing file directly"); - this.bytesPerChar = 1; - this.backingFileIn = new FileInputStream(backingFilename); - this.decoder = charset.newDecoder(); - this.prefixBuffer = this.decoder.decode( - ByteBuffer.wrap(contentReplayInputStream.getBuffer())); - } else { - logger.fine("charset=" + charsetName - + ": may not support random access, decoding to separate file"); - - // decodes only up to Integer.MAX_VALUE characters - decodeToFile(contentReplayInputStream, backingFilename, charsetName); - - this.bytesPerChar = 2; - this.backingFileIn = new FileInputStream(decodedFile); - this.decoder = Charset.forName(WRITE_ENCODING).newDecoder(); - this.prefixBuffer = CharBuffer.wrap(""); + + charset + " backingFilename=" + backingFilename); + + if(charset==null) { + charset = ReplayCharSequence.FALLBACK_CHARSET; } + // decodes only up to Integer.MAX_VALUE characters + decode(contentReplayInputStream, prefixMax, backingFilename, charset); - this.tempBuf = ByteBuffer.wrap(new byte[(int) this.bytesPerChar]); - this.backingFileChannel = backingFileIn.getChannel(); + this.bytesPerChar = 2; - // we only support the first Integer.MAX_VALUE characters - long wouldBeLength = prefixBuffer.limit() + backingFileChannel.size() / bytesPerChar; - if (wouldBeLength <= Integer.MAX_VALUE) { - this.length = (int) wouldBeLength; - } else { - logger.warning("input stream is longer than Integer.MAX_VALUE=" - + NumberFormat.getInstance().format(Integer.MAX_VALUE) - + " characters -- only first " - + NumberFormat.getInstance().format(Integer.MAX_VALUE) - + " are accessible through this GenericReplayCharSequence"); - this.length = Integer.MAX_VALUE; + if(length>prefixBuffer.position()) { + this.backingFileIn = new FileInputStream(decodedFile); + this.backingFileChannel = backingFileIn.getChannel(); + this.mapByteOffset = 0; + updateMemoryMappedBuffer(); } - - this.mapByteOffset = 0; - updateMemoryMappedBuffer(); } private void updateMemoryMappedBuffer() { - long fileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters - long mapSize = Math.min(fileLength * bytesPerChar - mapByteOffset, MAP_MAX_BYTES); + long charLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters + long mapSize = Math.min((charLength * bytesPerChar) - mapByteOffset, MAP_MAX_BYTES); logger.fine("updateMemoryMappedBuffer: mapOffset=" + NumberFormat.getInstance().format(mapByteOffset) + " mapSize=" + NumberFormat.getInstance().format(mapSize)); try { - System.gc(); - System.runFinalization(); + // TODO: stress-test without these possibly-costly requests! +// System.gc(); +// System.runFinalization(); // TODO: Confirm the READ_ONLY works. I recall it not working. // The buffers seem to always say that the buffer is writable. mappedBuffer = backingFileChannel.map( FileChannel.MapMode.READ_ONLY, mapByteOffset, mapSize) - .asReadOnlyBuffer(); + .asReadOnlyBuffer().asCharBuffer(); } catch (IOException e) { // TODO convert this to a runtime error? DevUtils.logger.log(Level.SEVERE, @@ -237,46 +199,65 @@ private void updateMemoryMappedBuffer() { * * @throws IOException */ - private void decodeToFile(ReplayInputStream inStream, - String backingFilename, String encoding) throws IOException { + protected void decode(InputStream inStream, int prefixMax, + String backingFilename, Charset charset) throws IOException { + // TODO: consider if BufferedReader is helping any + // TODO: consider adding TBW 'LimitReader' to stop reading at + // Integer.MAX_VALUE characters because of charAt(int) limit BufferedReader reader = new BufferedReader(new InputStreamReader( - inStream, encoding)); - - this.decodedFile = new File(backingFilename + "." + WRITE_ENCODING); + inStream, charset)); logger.fine("decodeToFile: backingFilename=" + backingFilename - + " encoding=" + encoding + " decodedFile=" + decodedFile); + + " encoding=" + charset + " decodedFile=" + decodedFile); - FileOutputStream fos; - try { - fos = new FileOutputStream(this.decodedFile); - } catch (FileNotFoundException e) { - // Windows workaround attempt - System.gc(); - System.runFinalization(); - this.decodedFile = new File(decodedFile.getAbsolutePath()+".win"); - logger.info("Windows 'file with a user-mapped section open' " - + "workaround gc/finalization/name-extension performed."); - // try again - fos = new FileOutputStream(this.decodedFile); - } - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, - WRITE_ENCODING)); - - int c; + this.prefixBuffer = CharBuffer.allocate(prefixMax); + long count = 0; - while ((c = reader.read()) >= 0 && count < Integer.MAX_VALUE) { - writer.write(c); - count++; - if (count % 100000000 == 0) { - logger.fine("wrote " + count + " characters so far..."); + while(count < prefixMax) { + int read = reader.read(prefixBuffer); + if(read<0) { + break; + } + count += read; + } + + if(reader.ready()) { + // more to decode to file overflow + this.decodedFile = new File(backingFilename + "." + WRITE_ENCODING); + + FileOutputStream fos; + try { + fos = new FileOutputStream(this.decodedFile); + } catch (FileNotFoundException e) { + // Windows workaround attempt + System.gc(); + System.runFinalization(); + this.decodedFile = new File(decodedFile.getAbsolutePath()+".win"); + logger.info("Windows 'file with a user-mapped section open' " + + "workaround gc/finalization/name-extension performed."); + // try again + fos = new FileOutputStream(this.decodedFile); } + + Writer writer = new OutputStreamWriter(fos,WRITE_ENCODING); + count += IOUtils.copyLarge(reader, writer); + writer.close(); + reader.close(); + } + + this.length = Ints.saturatedCast(count); + if(count>Integer.MAX_VALUE) { + logger.warning("input stream is longer than Integer.MAX_VALUE=" + + NumberFormat.getInstance().format(Integer.MAX_VALUE) + + " characters -- only first " + + NumberFormat.getInstance().format(Integer.MAX_VALUE) + + " are accessible through this GenericReplayCharSequence"); } - writer.close(); - logger.fine("decodeToFile: wrote " + count + " characters to " - + decodedFile); + logger.fine("decode: decoded " + count + " characters" + + ((decodedFile==null) ? "" + : " ("+(count-prefixBuffer.length())+" to "+decodedFile+")")); } /** @@ -296,10 +277,13 @@ public char charAt(int index) { } // otherwise we gotta get it from disk via memory map - long fileIndex = (long) index - (long) prefixBuffer.limit(); - long fileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters - if (fileIndex * bytesPerChar < mapByteOffset - || fileIndex * bytesPerChar - mapByteOffset >= mappedBuffer.limit()) { + long charFileIndex = (long) index - (long) prefixBuffer.limit(); + long charFileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters + if (charFileIndex * bytesPerChar < mapByteOffset) { + logger.log(Level.WARNING,"left-fault; probably don't want to use CharSequence that far backward"); + } + if (charFileIndex * bytesPerChar < mapByteOffset + || charFileIndex - (mapByteOffset / bytesPerChar) >= mappedBuffer.limit()) { // fault /* * mapByteOffset is bounded by 0 and file size +/- size of the map, @@ -307,30 +291,13 @@ public char charAt(int index) { * MAP_TARGET_LEFT_PADDING_BYTES</code> as it can while also not * being smaller than it needs to be. */ - mapByteOffset = Math.max(0, fileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES); - mapByteOffset = Math.min(mapByteOffset, fileLength * bytesPerChar - MAP_MAX_BYTES); + mapByteOffset = Math.min(charFileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES, + charFileLength * bytesPerChar - MAP_MAX_BYTES); + mapByteOffset = Math.max(0, mapByteOffset); updateMemoryMappedBuffer(); } - // CharsetDecoder always decodes up to the end of the ByteBuffer, so we - // create a new ByteBuffer with only the bytes we're interested in. - mappedBuffer.position((int) (fileIndex * bytesPerChar - mapByteOffset)); - mappedBuffer.get(tempBuf.array()); - tempBuf.position(0); // decoder starts at this position - - try { - CharBuffer cbuf = decoder.decode(tempBuf); - return cbuf.get(); - } catch (CharacterCodingException e) { - logger.log(Level.FINE,"unable to get character at index=" + index + " (fileIndex=" + fileIndex + "): " + e, e); - decodingExceptions++; - if(codingException==null) { - codingException = e; - } - // U+FFFD REPLACEMENT CHARACTER -- - // "used to replace an incoming character whose value is unknown or unrepresentable in Unicode" - return (char) 0xfffd; - } + return mappedBuffer.get((int)(charFileIndex-(mapByteOffset/bytesPerChar))); } public CharSequence subSequence(int start, int end) { diff --git a/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java b/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java deleted file mode 100644 index 41f805090..000000000 --- a/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * This file is part of the Heritrix web crawler (crawler.archive.org). - * - * Licensed to the Internet Archive (IA) by one or more individual - * contributors. - * - * The IA 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.archive.io; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CodingErrorAction; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class InMemoryReplayCharSequence implements ReplayCharSequence { - - protected static Logger logger = - Logger.getLogger(InMemoryReplayCharSequence.class.getName()); - - /** - * CharBuffer of decoded content. - * - * Content of this buffer is unicode. - */ - private CharBuffer charBuffer = null; - - protected long decodingExceptionsCount = 0; - protected CharacterCodingException codingException = null; - - /** - * Constructor for all in-memory operation. - * - * @param buffer - * @param size Total size of stream to replay in bytes. Used to find - * EOS. This is total length of content including HTTP headers if - * present. - * @param responseBodyStart Where the response body starts in bytes. - * Used to skip over the HTTP headers if present. - * @param encoding Encoding to use reading the passed prefix buffer and - * backing file. For now, should be java canonical name for the - * encoding. Must not be null. - * - * @throws IOException - */ - public InMemoryReplayCharSequence(byte[] buffer, long size, - long responseBodyStart, String encoding) throws IOException { - super(); - this.charBuffer = decodeInMemory(buffer, size, responseBodyStart, - encoding); - } - - /** - * Decode passed buffer into a CharBuffer. - * - * This method decodes a memory buffer returning a memory buffer. - * - * @param buffer - * @param size Total size of stream to replay in bytes. Used to find - * EOS. This is total length of content including HTTP headers if - * present. - * @param responseBodyStart Where the response body starts in bytes. - * Used to skip over the HTTP headers if present. - * @param encoding Encoding to use reading the passed prefix buffer and - * backing file. For now, should be java canonical name for the - * encoding. Must not be null. - * - * @return A CharBuffer view on decodings of the contents of passed - * buffer. - */ - private CharBuffer decodeInMemory(byte[] buffer, long size, - long responseBodyStart, String encoding) { - ByteBuffer bb = ByteBuffer.wrap(buffer); - // Move past the HTTP header if present. - bb.position((int) responseBodyStart); - bb.mark(); - // Set the end-of-buffer to be end-of-content. - bb.limit((int) size); - Charset charset; - try { - charset = Charset.forName(encoding); - } catch (IllegalArgumentException e) { - logger.log(Level.WARNING,"charset problem: "+encoding,e); - // TODO: better detection or default - charset = Charset.forName(FALLBACK_CHARSET_NAME); - } - try { - return charset.newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(bb).asReadOnlyBuffer(); - } catch (CharacterCodingException cce) { - bb.reset(); - decodingExceptionsCount++; - codingException = cce; - return charset.decode(bb).asReadOnlyBuffer(); - } - } - - public void close() { - this.charBuffer = null; - } - - protected void finalize() throws Throwable { - super.finalize(); - // Maybe TODO: eliminate close here, requiring explicit close instead - close(); - } - - public int length() { - return this.charBuffer.limit(); - } - - public char charAt(int index) { - return this.charBuffer.get(index); - } - - public CharSequence subSequence(int start, int end) { - return new CharSubSequence(this, start, end); - } - - public String toString() { - StringBuffer sb = new StringBuffer(length()); - sb.append(this); - return sb.toString(); - } - - /** - * Return 1 if there were decoding problems (a full count isn't possible). - * - * @see org.archive.io.ReplayCharSequence#getDecodeExceptionCount() - */ - @Override - public long getDecodeExceptionCount() { - return decodingExceptionsCount; - } - - /* (non-Javadoc) - * @see org.archive.io.ReplayCharSequence#getCodingException() - */ - @Override - public CharacterCodingException getCodingException() { - return codingException; - } - - @Override - public boolean isOpen() { - return this.charBuffer != null; - } -} diff --git a/commons/src/main/java/org/archive/io/RecordingInputStream.java b/commons/src/main/java/org/archive/io/RecordingInputStream.java index 9f3991cc8..f28f3d270 100644 --- a/commons/src/main/java/org/archive/io/RecordingInputStream.java +++ b/commons/src/main/java/org/archive/io/RecordingInputStream.java @@ -18,8 +18,6 @@ */ package org.archive.io; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; @@ -149,8 +147,8 @@ public ReplayInputStream getReplayInputStream() throws IOException { return this.recordingOutputStream.getReplayInputStream(); } - public ReplayInputStream getContentReplayInputStream() throws IOException { - return this.recordingOutputStream.getContentReplayInputStream(); + public ReplayInputStream getMessageBodyReplayInputStream() throws IOException { + return this.recordingOutputStream.getMessageBodyReplayInputStream(); } public long readFully() throws IOException { @@ -249,11 +247,11 @@ public long getSize() { } public void markContentBegin() { - this.recordingOutputStream.markContentBegin(); + this.recordingOutputStream.markMessageBodyBegin(); } public long getContentBegin() { - return this.recordingOutputStream.getContentBegin(); + return this.recordingOutputStream.getMessageBodyBegin(); } public void startDigest() { @@ -302,22 +300,6 @@ public byte[] getDigestValue() { return this.recordingOutputStream.getDigestValue(); } - public ReplayCharSequence getReplayCharSequence() throws IOException { - return getReplayCharSequence(null); - } - - /** - * @param characterEncoding Encoding of recorded stream. - * @return A ReplayCharSequence Will return null if an IOException. Call - * close on returned RCS when done. - * @throws IOException - */ - public ReplayCharSequence getReplayCharSequence(String characterEncoding) - throws IOException { - return this.recordingOutputStream. - getReplayCharSequence(characterEncoding); - } - public long getResponseContentLength() { return this.recordingOutputStream.getResponseContentLength(); } @@ -326,18 +308,6 @@ public void closeRecorder() throws IOException { this.recordingOutputStream.closeRecorder(); } - /** - * @param tempFile - * @throws IOException - */ - public void copyContentBodyTo(File tempFile) throws IOException { - FileOutputStream fos = new FileOutputStream(tempFile); - ReplayInputStream ris = getContentReplayInputStream(); - ris.readFullyTo(fos); - fos.close(); - ris.close(); - } - /** * @return True if we've been opened. */ diff --git a/commons/src/main/java/org/archive/io/RecordingOutputStream.java b/commons/src/main/java/org/archive/io/RecordingOutputStream.java index ab211e697..d3756da0a 100644 --- a/commons/src/main/java/org/archive/io/RecordingOutputStream.java +++ b/commons/src/main/java/org/archive/io/RecordingOutputStream.java @@ -70,10 +70,10 @@ public class RecordingOutputStream extends OutputStream { * Later passed to ReplayInputStream on creation. It uses it to know when * EOS. */ - private long size = 0; + protected long size = 0; - private String backingFilename; - private OutputStream diskStream = null; + protected String backingFilename; + protected OutputStream diskStream = null; /** * Buffer we write recordings to. @@ -106,7 +106,7 @@ public class RecordingOutputStream extends OutputStream { private MessageDigest digest = null; /** - * Define for SHA1 alogarithm. + * Define for SHA1 algarithm. */ private static final String SHA1 = "SHA1"; @@ -130,7 +130,7 @@ public class RecordingOutputStream extends OutputStream { /** * When recording HTTP, where the content-body starts. */ - private long contentBeginMark; + protected long messageBodyBeginMark; /** * Stream to record. @@ -186,7 +186,7 @@ public void open(OutputStream wrappedStream) throws IOException { this.markPosition = 0; this.maxPosition = 0; this.size = 0; - this.contentBeginMark = -1; + this.messageBodyBeginMark = -1; // ensure recording turned on this.recording = true; // Always begins false; must use startDigest() to begin @@ -245,7 +245,7 @@ public void write(byte[] b, int off, int len) throws IOException { */ protected void checkLimits() throws RecorderIOException { // too much material before finding end of headers? - if (contentBeginMark<0) { + if (messageBodyBeginMark<0) { // no mark yet if(position>MAX_HEADER_MATERIAL) { throw new RecorderTooMuchHeaderException(); @@ -344,10 +344,10 @@ private void tailRecord(byte[] b, int off, int len) throws IOException { } public void close() throws IOException { - if(contentBeginMark<0) { + if(messageBodyBeginMark<0) { // if unset, consider 0 posn as content-start // (so that a -1 never survives to replay step) - contentBeginMark = 0; + messageBodyBeginMark = 0; } if (this.out != null) { this.out.close(); @@ -396,7 +396,7 @@ public ReplayInputStream getReplayInputStream(long skip) throws IOException { // -- the size will zero so any attempt at a read will get back EOF. assert this.out == null: "Stream is still open."; ReplayInputStream replay = new ReplayInputStream(this.buffer, - this.size, this.contentBeginMark, this.backingFilename); + this.size, this.messageBodyBeginMark, this.backingFilename); replay.skip(skip); return replay; } @@ -407,8 +407,8 @@ public ReplayInputStream getReplayInputStream(long skip) throws IOException { * @throws IOException * @return An RIS. */ - public ReplayInputStream getContentReplayInputStream() throws IOException { - return getReplayInputStream(this.contentBeginMark); + public ReplayInputStream getMessageBodyReplayInputStream() throws IOException { + return getReplayInputStream(this.messageBodyBeginMark); } public long getSize() { @@ -416,20 +416,20 @@ public long getSize() { } /** - * Remember the current position as the start of the "response + * Remember the current position as the start of the "message * body". Useful when recording HTTP traffic as a way to start * replays after the headers. */ - public void markContentBegin() { - this.contentBeginMark = this.position; + public void markMessageBodyBegin() { + this.messageBodyBeginMark = this.position; startDigest(); } /** - * Return stored content-begin-mark (which is also end-of-headers) + * Return stored message-body-begin-mark (which is also end-of-headers) */ - public long getContentBegin() { - return this.contentBeginMark; + public long getMessageBodyBegin() { + return this.messageBodyBeginMark; } /** @@ -499,51 +499,8 @@ public byte[] getDigestValue() { return this.digest.digest(); } - public ReplayCharSequence getReplayCharSequence() throws IOException { - return getReplayCharSequence(null); - } - - public ReplayCharSequence getReplayCharSequence(String characterEncoding) - throws IOException { - return getReplayCharSequence(characterEncoding, this.contentBeginMark); - } - - /** - * @param characterEncoding Encoding of recorded stream. - * @return A ReplayCharSequence Will return null if an IOException. Call - * close on returned RCS when done. - * @throws IOException - */ - public ReplayCharSequence getReplayCharSequence(String characterEncoding, - long startOffset) throws IOException { - if (characterEncoding == null) { - characterEncoding = "UTF-8"; - } - logger.fine("this.size=" + this.size + " this.buffer.length=" + this.buffer.length); - if (this.size <= this.buffer.length) { - logger.fine("using InMemoryReplayCharSequence"); - // raw data is all in memory; do in memory - return new InMemoryReplayCharSequence( - this.buffer, - this.size, - startOffset, - characterEncoding); - } - else { - logger.fine("using GenericReplayCharSequence"); - // raw data overflows to disk; use temp file - ReplayInputStream ris = getReplayInputStream(startOffset); - ReplayCharSequence rcs = new GenericReplayCharSequence( - ris, - this.backingFilename, - characterEncoding); - ris.close(); - return rcs; - } - } - public long getResponseContentLength() { - return this.size - this.contentBeginMark; + return this.size - this.messageBodyBeginMark; } /** @@ -553,6 +510,10 @@ public boolean isOpen() { return this.out != null; } + public int getBufferLength() { + return this.buffer.length; + } + /** * When used alongside a mark-supporting RecordingInputStream, remember * a position reachable by a future reset(). diff --git a/commons/src/main/java/org/archive/io/ReplayCharSequence.java b/commons/src/main/java/org/archive/io/ReplayCharSequence.java index f5f15176b..99a04ec84 100644 --- a/commons/src/main/java/org/archive/io/ReplayCharSequence.java +++ b/commons/src/main/java/org/archive/io/ReplayCharSequence.java @@ -22,6 +22,9 @@ import java.io.Closeable; import java.io.IOException; import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; + +import com.google.common.base.Charsets; /** @@ -37,8 +40,7 @@ public interface ReplayCharSequence extends CharSequence, Closeable { /** charset to use in replay when declared value * is absent/illegal/unavailable */ -// String FALLBACK_CHARSET_NAME = "UTF-8"; - String FALLBACK_CHARSET_NAME = "ISO8859_1"; + public Charset FALLBACK_CHARSET = Charsets.ISO_8859_1; // TODO: should this be UTF-8? /** * Call this method when done so implementation has chance to clean up diff --git a/commons/src/main/java/org/archive/io/ReplayInputStream.java b/commons/src/main/java/org/archive/io/ReplayInputStream.java index 04656d4bd..d50d00673 100644 --- a/commons/src/main/java/org/archive/io/ReplayInputStream.java +++ b/commons/src/main/java/org/archive/io/ReplayInputStream.java @@ -21,8 +21,13 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.IOUtils; +import org.archive.util.ArchiveUtils; +import org.archive.util.FileUtils; + /** * Replays the bytes recorded from a RecordingInputStream or @@ -34,6 +39,7 @@ */ public class ReplayInputStream extends SeekInputStream { + private static final int DEFAULT_BUFFER_SIZE = 256*1024; // 256KiB private BufferedSeekInputStream diskStream; private byte[] buffer; private long position; @@ -89,9 +95,43 @@ public ReplayInputStream(byte[] buffer, long size, String backingFilename) this.buffer = buffer; this.size = size; if (size > buffer.length) { - RandomAccessInputStream rais = new RandomAccessInputStream( - new File(backingFilename)); - diskStream = new BufferedSeekInputStream(rais, 4096); + setupDiskStream(new File(backingFilename)); + } + } + + protected void setupDiskStream(File backingFile) throws IOException { + RandomAccessInputStream rais = new RandomAccessInputStream(backingFile); + diskStream = new BufferedSeekInputStream(rais, 4096); + } + + File backingFile; + + /** + * Create a ReplayInputStream from the given source stream. Requires + * reading the entire stream (and possibly overflowing to a temporary + * file). Primary reason for doing so would be to have a repositionable + * version of the original stream's contents. + * @param fillStream + * @throws IOException + */ + public ReplayInputStream(InputStream fillStream) throws IOException { + this.buffer = new byte[DEFAULT_BUFFER_SIZE]; + long count = ArchiveUtils.readFully(fillStream, buffer); + if(fillStream.available()>0) { + this.backingFile = File.createTempFile("tid"+Thread.currentThread().getId(), "ris"); + count += FileUtils.readFullyToFile(fillStream, backingFile); + setupDiskStream(backingFile); + } + this.size = count; + } + + /** + * Close & destroy any internally-generated temporary files. + */ + public void destroy() { + IOUtils.closeQuietly(this); + if(backingFile!=null) { + FileUtils.deleteSoonerOrLater(backingFile); } } diff --git a/commons/src/main/java/org/archive/util/Recorder.java b/commons/src/main/java/org/archive/util/Recorder.java index 6247ba837..59ceeec21 100644 --- a/commons/src/main/java/org/archive/util/Recorder.java +++ b/commons/src/main/java/org/archive/util/Recorder.java @@ -22,15 +22,26 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.OutputStream; +import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.zip.DeflaterInputStream; +import java.util.zip.GZIPInputStream; +import org.apache.commons.httpclient.ChunkedInputStream; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.archive.io.GenericReplayCharSequence; import org.archive.io.RecordingInputStream; import org.archive.io.RecordingOutputStream; import org.archive.io.ReplayCharSequence; import org.archive.io.ReplayInputStream; +import com.google.common.base.Charsets; + /** * Pairs together a RecordingInputStream and RecordingOutputStream @@ -47,8 +58,8 @@ public class Recorder { protected static Logger logger = Logger.getLogger("org.archive.util.HttpRecorder"); - private static final int DEFAULT_OUTPUT_BUFFER_SIZE = 4096; - private static final int DEFAULT_INPUT_BUFFER_SIZE = 65536; + private static final int DEFAULT_OUTPUT_BUFFER_SIZE = 16384; + private static final int DEFAULT_INPUT_BUFFER_SIZE = 524288; private RecordingInputStream ris = null; private RecordingOutputStream ros = null; @@ -71,10 +82,16 @@ public class Recorder { private static final String RECORDING_INPUT_STREAM_SUFFIX = ".ris"; /** - * Response character encoding. + * recording-input (ris) content character encoding. */ private String characterEncoding = null; + + /** whether recording-input (ris) message-body is chunked */ + protected boolean inputIsChunked = false; + /** recording-input (ris) entity content-encoding (eg gzip, deflate), if any */ + protected String contentEncoding = null; + private ReplayCharSequence replayCharSequence; @@ -143,6 +160,12 @@ public Recorder(File tempDir, String backingFilenameBase) { public InputStream inputWrap(InputStream is) throws IOException { logger.fine(Thread.currentThread().getName() + " wrapping input"); + + // discard any state from previously-recorded input + this.characterEncoding = null; + this.inputIsChunked = false; + this.contentEncoding = null; + this.ris.open(is); return this.ris; } @@ -278,12 +301,43 @@ public void setCharacterEncoding(String characterEncoding) { } /** - * @return Returns the characterEncoding. + * @return Returns the characterEncoding of input recording. */ public String getCharacterEncoding() { return this.characterEncoding; } + + /** + * @param characterEncoding Character encoding of input recording. + */ + public void setInputIsChunked(boolean chunked) { + this.inputIsChunked = chunked; + } + + /** + * @param contentEncoding declared content-encoding of input recording. + */ + public void setContentEncoding(String contentEncoding) { + this.contentEncoding = contentEncoding; + } + + /** + * @return Returns the characterEncoding. + */ + public String getContentEncoding() { + return this.contentEncoding; + } + + /** + * @return + * @throws IOException + * @deprecated use getContentReplayCharSequence + */ + public ReplayCharSequence getReplayCharSequence() throws IOException { + return getContentReplayCharSequence(); + } + /** * @return A ReplayCharSequence. Caller may call * {@link ReplayCharSequence#close()} when finished. However, in @@ -293,15 +347,50 @@ public String getCharacterEncoding() { * @throws IOException * @see {@link #endReplays()} */ - public ReplayCharSequence getReplayCharSequence() throws IOException { + public ReplayCharSequence getContentReplayCharSequence() throws IOException { if (replayCharSequence == null || !replayCharSequence.isOpen()) { - replayCharSequence = getRecordedInput().getReplayCharSequence(this.characterEncoding); + replayCharSequence = getContentReplayCharSequence(this.characterEncoding); } return replayCharSequence; } + /** + * @param characterEncoding Encoding of recorded stream. + * @return A ReplayCharSequence Will return null if an IOException. Call + * close on returned RCS when done. + * @throws IOException + */ + public ReplayCharSequence getContentReplayCharSequence(String encoding) throws IOException { + Charset charset = Charsets.UTF_8; + if (encoding != null) { + try { + charset = Charset.forName(encoding); + } catch (IllegalArgumentException e) { + logger.log(Level.WARNING,"charset problem: "+encoding,e); + // TODO: better detection or default + charset = ReplayCharSequence.FALLBACK_CHARSET; + } + } + + logger.fine("using GenericReplayCharSequence"); + // raw data overflows to disk; use temp file + InputStream ris = getContentReplayInputStream(); + ReplayCharSequence rcs = new GenericReplayCharSequence( + ris, + this.ros.getBufferLength()/2, + this.backingFileBasename + RECORDING_OUTPUT_STREAM_SUFFIX, + charset); + ris.close(); + return rcs; + + } + + /** + * Get a raw replay of all recorded data (including, for example, HTTP + * protocol headers) + * * @return A replay input stream. * @throws IOException */ @@ -309,6 +398,103 @@ public ReplayInputStream getReplayInputStream() throws IOException { return getRecordedInput().getReplayInputStream(); } + /** + * Get a raw replay of the 'message-body'. For the common case of + * HTTP, this is the raw, possibly chunked-transfer-encoded message + * contents not including the leading headers. + * + * @return A replay input stream. + * @throws IOException + */ + public ReplayInputStream getMessageBodyReplayInputStream() throws IOException { + return getRecordedInput().getMessageBodyReplayInputStream(); + } + + /** + * Get a raw replay of the 'entity'. For the common case of + * HTTP, this is the message-body after any (usually-unnecessary) + * transfer-decoding but before any content-encoding (eg gzip) decoding + * + * @return A replay input stream. + * @throws IOException + */ + public InputStream getEntityReplayInputStream() throws IOException { + if(inputIsChunked) { + return new ChunkedInputStream(getRecordedInput().getMessageBodyReplayInputStream()); + } else { + return getRecordedInput().getMessageBodyReplayInputStream(); + } + } + + /** + * Get a replay cued up for the 'content' (after all leading headers) + * + * TODO: handle chunking + * TODO: handle decompression, either here or in a parallel method + * + * @return A replay input stream. + * @throws IOException + */ + public InputStream getContentReplayInputStream() throws IOException { + InputStream entityStream = getEntityReplayInputStream(); + if(StringUtils.isEmpty(contentEncoding)) { + return entityStream; + } else if ("gzip".equalsIgnoreCase(contentEncoding) || "x-gzip".equalsIgnoreCase(contentEncoding)) { + try { + return new GZIPInputStream(entityStream); + } catch (IOException ioe) { + logger.log(Level.WARNING,"gzip problem; using raw entity instead",ioe); + IOUtils.closeQuietly(entityStream); // close partially-read stream + return getEntityReplayInputStream(); + } + } else if ("deflate".equalsIgnoreCase(contentEncoding)) { + return new DeflaterInputStream(entityStream); + } else if ("identity".equalsIgnoreCase(contentEncoding)) { + return entityStream; + } else { + logger.log(Level.WARNING,"Unknown content-encoding '"+contentEncoding+"' declared; using raw entity instead"); + return entityStream; + } + } + + /** + * Return a short prefix of the presumed-textual content as a String. + * + * @param size max length of String to return + * @return String prefix, or empty String (with logged exception) on any error + */ + public String getContentReplayPrefixString(int size) { + try { + InputStreamReader isr = (characterEncoding == null) + ? new InputStreamReader(getContentReplayInputStream(), Charsets.ISO_8859_1) + : new InputStreamReader(getContentReplayInputStream(), characterEncoding); + char[] chars = new char[size]; + int count = isr.read(chars); + isr.close(); + return new String(chars,0,count); + } catch (IOException e) { + logger.log(Level.SEVERE,"unable to get replay prefix string", e); + return ""; + } + } + + /** + * @param tempFile + * @throws IOException + */ + public void copyContentBodyTo(File tempFile) throws IOException { + InputStream inStream = null; + OutputStream outStream = null; + try { + inStream = getContentReplayInputStream(); + outStream = FileUtils.openOutputStream(tempFile); + IOUtils.copy(inStream, outStream); + } finally { + IOUtils.closeQuietly(inStream); + IOUtils.closeQuietly(outStream); + } + } + /** * Record the input stream for later playback by an extractor, etc. * This is convenience method used to setup an artificial HttpRecorder diff --git a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java index 28a53bbdd..9e769c296 100644 --- a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java +++ b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java @@ -195,7 +195,8 @@ public void setMaxLengthBytes(long timeout) { /** * Accept Headers to include in each request. Each must be the complete - * header, e.g., 'Accept-Language: en'. + * header, e.g., 'Accept-Language: en'. (Thus, this can also be used to + * other headers not beginning 'Accept-' as well.) */ { setAcceptHeaders(new LinkedList<String>()); @@ -322,6 +323,34 @@ public void setShouldFetchBodyRule(DecideRule rule) { */ private static final String MIDFETCH_ABORT_LOG = "midFetchAbort"; + /** + * Use HTTP/1.1. Note: even when offering an HTTP/1.1 request, + * Heritrix may not properly handle persistent/keep-alive connections, + * so the sendConnectionClose parameter should remain 'true'. + */ + { + setUseHTTP11(false); + } + public boolean getUseHTTP11() { + return (Boolean) kp.get("useHTTP11"); + } + public void setUseHTTP11(boolean useHTTP11) { + kp.put("useHTTP11",useHTTP11); + } + + /** + * Set headers to accept compressed responses. + */ + { + setAcceptCompression(false); + } + public boolean getAcceptCompression() { + return (Boolean) kp.get("acceptCompression"); + } + public void setAcceptCompression(boolean acceptCompression) { + kp.put("acceptCompression",acceptCompression); + } + /** * Send 'Connection: close' header with every request. */ @@ -622,6 +651,7 @@ protected void readResponseBody(HttpState state, // Set the response charset into the HttpRecord if available. setCharacterEncoding(curi, rec, method); setSizes(curi, rec); + setOtherCodings(curi, rec, method); } if (digestContent) { @@ -765,6 +795,32 @@ private void setCharacterEncoding(CrawlURI uri, final Recorder rec, } rec.setCharacterEncoding(encoding); } + + /** + * Set the transfer, content encodings based on headers (if necessary). + * + * @param rec + * Recorder for this request. + * @param method + * Method used for the request. + */ + private void setOtherCodings(CrawlURI uri, final Recorder rec, + final HttpMethod method) { + Header transferCodingHeader = ((HttpMethodBase) method).getResponseHeader("Transfer-Encoding"); + if (transferCodingHeader !=null) { + String te = transferCodingHeader.getValue().trim(); + if(te.equalsIgnoreCase("chunked")) { + rec.setInputIsChunked(true); + } else { + logger.log(Level.WARNING,"Unknown transfer-encoding '"+te+"' for "+uri.getURI()); + } + } + Header contentEncodingHeader = ((HttpMethodBase) method).getResponseHeader("Content-Encoding"); + if (contentEncodingHeader!=null) { + String ce = contentEncodingHeader.getValue().trim(); + rec.setContentEncoding(ce); + } + } /** * Cleanup after a failed method execute. @@ -862,8 +918,9 @@ protected HostConfiguration configureMethod(CrawlURI curi, ignoreCookies ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY); - // Use only HTTP/1.0 (to avoid receiving chunked responses) - method.getParams().setVersion(HttpVersion.HTTP_1_0); + method.getParams().setVersion(getUseHTTP11() + ? HttpVersion.HTTP_1_1 + : HttpVersion.HTTP_1_0); UserAgentProvider uap = getUserAgentProvider(); String from = uap.getFrom(); @@ -1398,6 +1455,11 @@ public String report() { private void setAcceptHeaders(CrawlURI curi, HttpMethod get) { + if(getAcceptCompression()) { + // we match the Firefox header exactly (ordering and whitespace) + // as a favor to caches + get.setRequestHeader("Accept-Encoding","gzip,deflate"); + } List<String> acceptHeaders = getAcceptHeaders(); if (acceptHeaders.isEmpty()) { return;
dd7cae7c19717429099c98536c0186a0677ed593
elasticsearch
move DatabaseReaders initialization to- IngestGeoIpPlugin-onModule--
p
https://github.com/elastic/elasticsearch
diff --git a/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java b/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java index ab87d51318b33..0ffc3cf3a595b 100644 --- a/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java +++ b/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java @@ -37,24 +37,17 @@ import java.io.Closeable; import java.io.IOException; -import java.io.InputStream; import java.net.InetAddress; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.PathMatcher; -import java.nio.file.StandardOpenOption; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.stream.Stream; import static org.elasticsearch.ingest.core.ConfigurationUtils.readOptionalList; import static org.elasticsearch.ingest.core.ConfigurationUtils.readStringProperty; @@ -230,31 +223,8 @@ public static final class Factory implements Processor.Factory<GeoIpProcessor>, private final Map<String, DatabaseReader> databaseReaders; - public Factory(Path configDirectory) { - - // TODO(simonw): same as fro grok we should load this outside of the factory in a static method and hass the map to the ctor - Path geoIpConfigDirectory = configDirectory.resolve("ingest-geoip"); - if (Files.exists(geoIpConfigDirectory) == false && Files.isDirectory(geoIpConfigDirectory)) { - throw new IllegalStateException("the geoip directory [" + geoIpConfigDirectory + "] containing databases doesn't exist"); - } - - try (Stream<Path> databaseFiles = Files.list(geoIpConfigDirectory)) { - Map<String, DatabaseReader> databaseReaders = new HashMap<>(); - PathMatcher pathMatcher = geoIpConfigDirectory.getFileSystem().getPathMatcher("glob:**.mmdb"); - // Use iterator instead of forEach otherwise IOException needs to be caught twice... - Iterator<Path> iterator = databaseFiles.iterator(); - while (iterator.hasNext()) { - Path databasePath = iterator.next(); - if (Files.isRegularFile(databasePath) && pathMatcher.matches(databasePath)) { - try (InputStream inputStream = Files.newInputStream(databasePath, StandardOpenOption.READ)) { - databaseReaders.put(databasePath.getFileName().toString(), new DatabaseReader.Builder(inputStream).build()); - } - } - } - this.databaseReaders = Collections.unmodifiableMap(databaseReaders); - } catch (IOException e) { - throw new RuntimeException(e); - } + public Factory(Map<String, DatabaseReader> databaseReaders) { + this.databaseReaders = databaseReaders; } public GeoIpProcessor create(Map<String, Object> config) throws Exception { diff --git a/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IngestGeoIpPlugin.java b/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IngestGeoIpPlugin.java index 4b6a60902ea94..6fdb870334296 100644 --- a/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IngestGeoIpPlugin.java +++ b/plugins/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IngestGeoIpPlugin.java @@ -19,9 +19,22 @@ package org.elasticsearch.ingest.geoip; +import com.maxmind.geoip2.DatabaseReader; import org.elasticsearch.node.NodeModule; import org.elasticsearch.plugins.Plugin; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.nio.file.StandardOpenOption; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.stream.Stream; + public class IngestGeoIpPlugin extends Plugin { @Override @@ -34,7 +47,31 @@ public String description() { return "Plugin that allows to plug in ingest processors"; } - public void onModule(NodeModule nodeModule) { - nodeModule.registerProcessor(GeoIpProcessor.TYPE, (environment, templateService) -> new GeoIpProcessor.Factory(environment.configFile())); + public void onModule(NodeModule nodeModule) throws IOException { + Path geoIpConfigDirectory = nodeModule.getNode().getEnvironment().configFile().resolve("ingest-geoip"); + Map<String, DatabaseReader> databaseReaders = loadDatabaseReaders(geoIpConfigDirectory); + nodeModule.registerProcessor(GeoIpProcessor.TYPE, (environment, templateService) -> new GeoIpProcessor.Factory(databaseReaders)); + } + + static Map<String, DatabaseReader> loadDatabaseReaders(Path geoIpConfigDirectory) throws IOException { + if (Files.exists(geoIpConfigDirectory) == false && Files.isDirectory(geoIpConfigDirectory)) { + throw new IllegalStateException("the geoip directory [" + geoIpConfigDirectory + "] containing databases doesn't exist"); + } + + Map<String, DatabaseReader> databaseReaders = new HashMap<>(); + try (Stream<Path> databaseFiles = Files.list(geoIpConfigDirectory)) { + PathMatcher pathMatcher = geoIpConfigDirectory.getFileSystem().getPathMatcher("glob:**.mmdb"); + // Use iterator instead of forEach otherwise IOException needs to be caught twice... + Iterator<Path> iterator = databaseFiles.iterator(); + while (iterator.hasNext()) { + Path databasePath = iterator.next(); + if (Files.isRegularFile(databasePath) && pathMatcher.matches(databasePath)) { + try (InputStream inputStream = Files.newInputStream(databasePath, StandardOpenOption.READ)) { + databaseReaders.put(databasePath.getFileName().toString(), new DatabaseReader.Builder(inputStream).build()); + } + } + } + } + return Collections.unmodifiableMap(databaseReaders); } } diff --git a/plugins/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpProcessorFactoryTests.java b/plugins/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpProcessorFactoryTests.java index 78dd86d4fdc8c..20ffe7fe43a90 100644 --- a/plugins/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpProcessorFactoryTests.java +++ b/plugins/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpProcessorFactoryTests.java @@ -19,11 +19,13 @@ package org.elasticsearch.ingest.geoip; +import com.maxmind.geoip2.DatabaseReader; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Before; +import org.junit.BeforeClass; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -40,19 +42,20 @@ public class GeoIpProcessorFactoryTests extends ESTestCase { - private Path configDir; + private static Map<String, DatabaseReader> databaseReaders; - @Before - public void prepareConfigDirectory() throws Exception { - this.configDir = createTempDir(); + @BeforeClass + public static void loadDatabaseReaders() throws IOException { + Path configDir = createTempDir(); Path geoIpConfigDir = configDir.resolve("ingest-geoip"); Files.createDirectories(geoIpConfigDir); Files.copy(new ByteArrayInputStream(StreamsUtils.copyToBytesFromClasspath("/GeoLite2-City.mmdb")), geoIpConfigDir.resolve("GeoLite2-City.mmdb")); Files.copy(new ByteArrayInputStream(StreamsUtils.copyToBytesFromClasspath("/GeoLite2-Country.mmdb")), geoIpConfigDir.resolve("GeoLite2-Country.mmdb")); + databaseReaders = IngestGeoIpPlugin.loadDatabaseReaders(geoIpConfigDir); } - public void testBuild_defaults() throws Exception { - GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(configDir); + public void testBuildDefaults() throws Exception { + GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(databaseReaders); Map<String, Object> config = new HashMap<>(); config.put("source_field", "_field"); @@ -64,8 +67,8 @@ public void testBuild_defaults() throws Exception { assertThat(processor.getFields(), sameInstance(GeoIpProcessor.Factory.DEFAULT_FIELDS)); } - public void testBuild_targetField() throws Exception { - GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(configDir); + public void testBuildTargetField() throws Exception { + GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(databaseReaders); Map<String, Object> config = new HashMap<>(); config.put("source_field", "_field"); config.put("target_field", "_field"); @@ -74,8 +77,8 @@ public void testBuild_targetField() throws Exception { assertThat(processor.getTargetField(), equalTo("_field")); } - public void testBuild_dbFile() throws Exception { - GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(configDir); + public void testBuildDbFile() throws Exception { + GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(databaseReaders); Map<String, Object> config = new HashMap<>(); config.put("source_field", "_field"); config.put("database_file", "GeoLite2-Country.mmdb"); @@ -85,8 +88,8 @@ public void testBuild_dbFile() throws Exception { assertThat(processor.getDbReader().getMetadata().getDatabaseType(), equalTo("GeoLite2-Country")); } - public void testBuild_nonExistingDbFile() throws Exception { - GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(configDir); + public void testBuildNonExistingDbFile() throws Exception { + GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(databaseReaders); Map<String, Object> config = new HashMap<>(); config.put("source_field", "_field"); @@ -99,8 +102,8 @@ public void testBuild_nonExistingDbFile() throws Exception { } } - public void testBuild_fields() throws Exception { - GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(configDir); + public void testBuildFields() throws Exception { + GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(databaseReaders); Set<GeoIpProcessor.Field> fields = EnumSet.noneOf(GeoIpProcessor.Field.class); List<String> fieldNames = new ArrayList<>(); @@ -118,8 +121,8 @@ public void testBuild_fields() throws Exception { assertThat(processor.getFields(), equalTo(fields)); } - public void testBuild_illegalFieldOption() throws Exception { - GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(configDir); + public void testBuildIllegalFieldOption() throws Exception { + GeoIpProcessor.Factory factory = new GeoIpProcessor.Factory(databaseReaders); Map<String, Object> config = new HashMap<>(); config.put("source_field", "_field");
83ade7b96fd5866d48973460ff8a71efca685366
Mylyn Reviews
322734: Force synchronisation after submit After submit the task editor still shows no attachment an thus no review section. After synchronize the task the attachment and the review display correctly. As a workaround force the synchronization of the task and re-open the editor.
c
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java index b690ed5c..bcacbf50 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java @@ -117,7 +117,9 @@ public void afterSubmit(ITask task) { taskRepository, task, attachment, "review result", //$NON-NLS-1$ attachmentAttribute, new NullProgressMonitor()); + TasksUiInternal.closeTaskEditorInAllPages(task, false); TasksUiInternal.synchronizeTask(connector, task, false, null); + TasksUiInternal.openTaskInBackground(task, true); } } catch (CoreException e) { e.printStackTrace();
e917c77d296109edead50146691b09c91d3ea748
ReactiveX-RxJava
Add takeUntil support in Single--
a
https://github.com/ReactiveX/RxJava
diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java index 8f0db3e56b..813dc61a0d 100644 --- a/src/main/java/rx/Single.java +++ b/src/main/java/rx/Single.java @@ -12,6 +12,9 @@ */ package rx; +import java.util.Collection; +import java.util.concurrent.*; + import rx.Observable.Operator; import rx.annotations.Beta; import rx.annotations.Experimental; @@ -23,15 +26,13 @@ import rx.internal.util.ScalarSynchronousSingle; import rx.internal.util.UtilityFunctions; import rx.observers.SafeSubscriber; +import rx.observers.SerializedSubscriber; import rx.plugins.RxJavaObservableExecutionHook; import rx.plugins.RxJavaPlugins; import rx.schedulers.Schedulers; import rx.singles.BlockingSingle; import rx.subscriptions.Subscriptions; -import java.util.Collection; -import java.util.concurrent.*; - /** * The Single class implements the Reactive Pattern for a single value response. See {@link Observable} for the * implementation of the Reactive Pattern for a stream or vector of values. @@ -1800,6 +1801,156 @@ public void onError(Throwable error) { } }); } + + /** + * Returns a Single that emits the item emitted by the source Single until an Observable emits an item. Upon + * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to + * {@link SingleSubscriber#onSuccess(Object)}. + * <p> + * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * + * @param other + * the Observable whose first emitted item will cause {@code takeUntil} to emit the item from the source + * Single + * @param <E> + * the type of items emitted by {@code other} + * @return a Single that emits the item emitted by the source Single until such time as {@code other} emits + * its first item + * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> + */ + public final <E> Single<T> takeUntil(final Observable<? extends E> other) { + return lift(new Operator<T, T>() { + @Override + public Subscriber<? super T> call(Subscriber<? super T> child) { + final Subscriber<T> serial = new SerializedSubscriber<T>(child, false); + + final Subscriber<T> main = new Subscriber<T>(serial, false) { + @Override + public void onNext(T t) { + serial.onNext(t); + } + @Override + public void onError(Throwable e) { + try { + serial.onError(e); + } finally { + serial.unsubscribe(); + } + } + @Override + public void onCompleted() { + try { + serial.onCompleted(); + } finally { + serial.unsubscribe(); + } + } + }; + + final Subscriber<E> so = new Subscriber<E>() { + + @Override + public void onCompleted() { + onError(new CancellationException("Stream was canceled before emitting a terminal event.")); + } + + @Override + public void onError(Throwable e) { + main.onError(e); + } + + @Override + public void onNext(E e) { + onError(new CancellationException("Stream was canceled before emitting a terminal event.")); + } + }; + + serial.add(main); + serial.add(so); + + child.add(serial); + + other.unsafeSubscribe(so); + + return main; + } + }); + } + + /** + * Returns a Single that emits the item emitted by the source Single until a second Single emits an item. Upon + * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to + * {@link SingleSubscriber#onSuccess(Object)}. + * <p> + * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * + * @param other + * the Single whose emitted item will cause {@code takeUntil} to emit the item from the source Single + * @param <E> + * the type of item emitted by {@code other} + * @return a Single that emits the item emitted by the source Single until such time as {@code other} emits its item + * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> + */ + public final <E> Single<T> takeUntil(final Single<? extends E> other) { + return lift(new Operator<T, T>() { + @Override + public Subscriber<? super T> call(Subscriber<? super T> child) { + final Subscriber<T> serial = new SerializedSubscriber<T>(child, false); + + final Subscriber<T> main = new Subscriber<T>(serial, false) { + @Override + public void onNext(T t) { + serial.onNext(t); + } + @Override + public void onError(Throwable e) { + try { + serial.onError(e); + } finally { + serial.unsubscribe(); + } + } + @Override + public void onCompleted() { + try { + serial.onCompleted(); + } finally { + serial.unsubscribe(); + } + } + }; + + final SingleSubscriber<E> so = new SingleSubscriber<E>() { + @Override + public void onSuccess(E value) { + onError(new CancellationException("Stream was canceled before emitting a terminal event.")); + } + + @Override + public void onError(Throwable e) { + main.onError(e); + } + }; + + serial.add(main); + serial.add(so); + + child.add(serial); + + other.subscribe(so); + + return main; + } + }); + } /** * Converts this Single into an {@link Observable}. diff --git a/src/test/java/rx/SingleTest.java b/src/test/java/rx/SingleTest.java index 393088562c..0b934e65e6 100644 --- a/src/test/java/rx/SingleTest.java +++ b/src/test/java/rx/SingleTest.java @@ -15,6 +15,12 @@ import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; + +import java.io.IOException; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + import rx.Single.OnSubscribe; import rx.exceptions.CompositeException; import rx.functions.*; @@ -22,13 +28,9 @@ import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.singles.BlockingSingle; +import rx.subjects.PublishSubject; import rx.subscriptions.Subscriptions; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.*; - import static org.junit.Assert.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; @@ -1353,4 +1355,362 @@ public Observable<?> call(Throwable throwable) { int numberOfErrors = retryCounter.getOnErrorEvents().size(); assertEquals(retryCount, numberOfErrors); } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilSuccess() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + other.sendOnSuccess("one"); + + result.assertError(CancellationException.class); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilSourceSuccess() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + source.sendOnSuccess("one"); + + result.assertValue("one"); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilNext() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + other.sendOnNext("one"); + + result.assertError(CancellationException.class); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilSourceSuccessObservable() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + source.sendOnSuccess("one"); + + result.assertValue("one"); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilSourceError() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + Throwable error = new Throwable(); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + source.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilSourceErrorObservable() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + Throwable error = new Throwable(); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + source.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilOtherError() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + Throwable error = new Throwable(); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + other.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilOtherErrorObservable() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + Throwable error = new Throwable(); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + other.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings("unchecked") + public void takeUntilOtherCompleted() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + + TestSubscriber<String> result = new TestSubscriber<String>(); + Single<String> stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + other.sendOnCompleted(); + + result.assertError(CancellationException.class); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + + } + + private static class TestObservable implements Observable.OnSubscribe<String> { + + Observer<? super String> observer = null; + Subscription s; + + public TestObservable(Subscription s) { + this.s = s; + } + + /* used to simulate subscription */ + public void sendOnCompleted() { + observer.onCompleted(); + } + + /* used to simulate subscription */ + public void sendOnNext(String value) { + observer.onNext(value); + } + + /* used to simulate subscription */ + public void sendOnError(Throwable e) { + observer.onError(e); + } + + @Override + public void call(Subscriber<? super String> observer) { + this.observer = observer; + observer.add(s); + } + } + + private static class TestSingle implements Single.OnSubscribe<String> { + + SingleSubscriber<? super String> subscriber = null; + Subscription s; + + public TestSingle(Subscription s) { + this.s = s; + } + + /* used to simulate subscription */ + public void sendOnSuccess(String value) { + subscriber.onSuccess(value); + } + + /* used to simulate subscription */ + public void sendOnError(Throwable e) { + subscriber.onError(e); + } + + @Override + public void call(SingleSubscriber<? super String> observer) { + this.subscriber = observer; + observer.add(s); + } + } + + @Test + public void takeUntilFires() { + PublishSubject<Integer> source = PublishSubject.create(); + PublishSubject<Integer> until = PublishSubject.create(); + + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + + source.take(1).toSingle().takeUntil(until.take(1).toSingle()).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + until.onNext(1); + + ts.assertError(CancellationException.class); + + assertFalse("Source still has observers", source.hasObservers()); + assertFalse("Until still has observers", until.hasObservers()); + assertFalse("TestSubscriber is unsubscribed", ts.isUnsubscribed()); + } + + @Test + public void takeUntilFiresObservable() { + PublishSubject<Integer> source = PublishSubject.create(); + PublishSubject<Integer> until = PublishSubject.create(); + + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + + source.take(1).toSingle().takeUntil(until.take(1)).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + until.onNext(1); + + ts.assertError(CancellationException.class); + + assertFalse("Source still has observers", source.hasObservers()); + assertFalse("Until still has observers", until.hasObservers()); + assertFalse("TestSubscriber is unsubscribed", ts.isUnsubscribed()); + } + + @Test + public void takeUntilDownstreamUnsubscribes() { + PublishSubject<Integer> source = PublishSubject.create(); + PublishSubject<Integer> until = PublishSubject.create(); + + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + + source.take(1).toSingle().takeUntil(until).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + source.onNext(1); + + ts.assertValue(1); + ts.assertNoErrors(); + ts.assertTerminalEvent(); + + assertFalse("Source still has observers", source.hasObservers()); + assertFalse("Until still has observers", until.hasObservers()); + assertFalse("TestSubscriber is unsubscribed", ts.isUnsubscribed()); + } + + @Test + public void takeUntilDownstreamUnsubscribesObservable() { + PublishSubject<Integer> source = PublishSubject.create(); + PublishSubject<Integer> until = PublishSubject.create(); + + TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); + + source.take(1).toSingle().takeUntil(until.take(1).toSingle()).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + source.onNext(1); + + ts.assertValue(1); + ts.assertNoErrors(); + ts.assertTerminalEvent(); + + assertFalse("Source still has observers", source.hasObservers()); + assertFalse("Until still has observers", until.hasObservers()); + assertFalse("TestSubscriber is unsubscribed", ts.isUnsubscribed()); + } + + @Test + public void takeUntilSimple() { + PublishSubject<String> stringSubject = PublishSubject.create(); + Single<String> single = stringSubject.toSingle(); + + Subscription singleSubscription = single.takeUntil(Single.just("Hello")).subscribe( + new Action1<String>() { + @Override + public void call(String s) { + fail(); + } + }, + new Action1<Throwable>() { + @Override + public void call(Throwable throwable) { + assertTrue(throwable instanceof CancellationException); + } + } + ); + assertTrue(singleSubscription.isUnsubscribed()); + } + + @Test + public void takeUntilObservable() { + PublishSubject<String> stringSubject = PublishSubject.create(); + Single<String> single = stringSubject.toSingle(); + PublishSubject<String> otherSubject = PublishSubject.create(); + + Subscription singleSubscription = single.takeUntil(otherSubject.asObservable()).subscribe( + new Action1<String>() { + @Override + public void call(String s) { + fail(); + } + }, + new Action1<Throwable>() { + @Override + public void call(Throwable throwable) { + assertTrue(throwable instanceof CancellationException); + } + } + ); + otherSubject.onNext("Hello"); + assertTrue(singleSubscription.isUnsubscribed()); + } }
dd6b2b0860bba3c0fac44092cf388c607b908df1
intellij-community
IDEA-139609 Gradle: New Module Wizard: "Select- Gradle Projec"t dialog: selection is not confirmed by double-clicking or- pressing Enter--
c
https://github.com/JetBrains/intellij-community
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsView.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsView.java index 56e1c622d2d0c..b10f41f615d61 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsView.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsView.java @@ -24,6 +24,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.awt.event.InputEvent; import java.util.List; /** @@ -51,4 +52,12 @@ public interface ExternalProjectsView { boolean getGroupTasks(); ProjectSystemId getSystemId(); + + void handleDoubleClickOrEnter(@NotNull ExternalSystemNode node, @Nullable String actionId, InputEvent inputEvent); + + void addListener(@NotNull ExternalProjectsView.Listener listener); + + interface Listener { + void onDoubleClickOrEnter(@NotNull ExternalSystemNode node, InputEvent inputEvent); + } } diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewAdapter.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewAdapter.java index 207ec6bbf6e60..9d8d0c409dde5 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewAdapter.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewAdapter.java @@ -24,6 +24,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.awt.event.InputEvent; import java.util.List; /** @@ -90,4 +91,14 @@ public boolean getGroupTasks() { public ProjectSystemId getSystemId() { return delegate.getSystemId(); } + + @Override + public void handleDoubleClickOrEnter(@NotNull ExternalSystemNode node, @Nullable String actionId, InputEvent inputEvent) { + delegate.handleDoubleClickOrEnter(node, actionId, inputEvent); + } + + @Override + public void addListener(@NotNull Listener listener) { + delegate.addListener(listener); + } } diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewImpl.java index b1ad9adf29d16..716116a0229a9 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewImpl.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalProjectsViewImpl.java @@ -24,6 +24,7 @@ import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.externalSystem.ExternalSystemUiAware; +import com.intellij.openapi.externalSystem.action.ExternalSystemActionUtil; import com.intellij.openapi.externalSystem.action.ExternalSystemViewGearAction; import com.intellij.openapi.externalSystem.model.*; import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo; @@ -69,6 +70,7 @@ import javax.swing.tree.TreeSelectionModel; import java.awt.*; +import java.awt.event.InputEvent; import java.util.*; import java.util.List; @@ -89,6 +91,8 @@ public class ExternalProjectsViewImpl extends SimpleToolWindowPanel implements D private final ProjectSystemId myExternalSystemId; @NotNull private final ExternalSystemUiAware myUiAware; + @NotNull + private final Set<Listener> listeners = ContainerUtil.newHashSet(); @Nullable private ExternalProjectsStructure myStructure; @@ -277,6 +281,21 @@ public void run() { scheduleStructureUpdate(); } + @Override + public void handleDoubleClickOrEnter(@NotNull ExternalSystemNode node, @Nullable String actionId, InputEvent inputEvent) { + if (actionId != null) { + ExternalSystemActionUtil.executeAction(actionId, inputEvent); + } + for (Listener listener : listeners) { + listener.onDoubleClickOrEnter(node, inputEvent); + } + } + + @Override + public void addListener(@NotNull Listener listener) { + listeners.add(listener); + } + private ActionGroup createAdditionalGearActionsGroup() { ActionManager actionManager = ActionManager.getInstance(); DefaultActionGroup group = new DefaultActionGroup(); diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalSystemNode.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalSystemNode.java index 33da6647dda0c..43b9b4c67d4d1 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalSystemNode.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/view/ExternalSystemNode.java @@ -373,9 +373,7 @@ public Navigatable getNavigatable() { @Override public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) { String actionId = getActionId(); - if (actionId != null) { - ExternalSystemActionUtil.executeAction(actionId, inputEvent); - } + getExternalProjectsView().handleDoubleClickOrEnter(this, actionId, inputEvent); } @Override diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalProjectDialog.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalProjectDialog.java index 53349141be809..3d04e11ff9dba 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalProjectDialog.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalProjectDialog.java @@ -16,15 +16,18 @@ package org.jetbrains.plugins.gradle.service.project.wizard; import com.intellij.openapi.externalSystem.model.project.ProjectData; +import com.intellij.openapi.externalSystem.view.ExternalSystemNode; import com.intellij.openapi.externalSystem.view.ProjectNode; import com.intellij.openapi.project.Project; import com.intellij.ui.treeStructure.NullNode; import com.intellij.ui.treeStructure.SimpleNode; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.util.GradleConstants; import javax.swing.*; import java.awt.event.ActionEvent; +import java.awt.event.InputEvent; /** * @author Vladislav.Soroka @@ -69,6 +72,13 @@ protected void doOKAction() { super.doOKAction(); } + @Override + protected void handleDoubleClickOrEnter(@NotNull ExternalSystemNode node, @Nullable String actionId, InputEvent inputEvent) { + if(node instanceof ProjectNode ) { + doOKAction(); + } + } + public ProjectData getResult() { return myResult; } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalSystemNodeDialog.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalSystemNodeDialog.java index e54483a1f7d96..5cb6a0558ec5c 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalSystemNodeDialog.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/SelectExternalSystemNodeDialog.java @@ -20,7 +20,10 @@ import com.intellij.openapi.externalSystem.model.project.ProjectData; import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManager; import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager; -import com.intellij.openapi.externalSystem.view.*; +import com.intellij.openapi.externalSystem.view.ExternalProjectsStructure; +import com.intellij.openapi.externalSystem.view.ExternalProjectsView; +import com.intellij.openapi.externalSystem.view.ExternalProjectsViewAdapter; +import com.intellij.openapi.externalSystem.view.ExternalSystemNode; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.ui.ScrollPaneFactory; @@ -30,11 +33,13 @@ import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBUI; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.util.GradleConstants; import javax.swing.*; import javax.swing.tree.TreeSelectionModel; +import java.awt.event.InputEvent; import java.util.Collection; import java.util.List; @@ -77,6 +82,11 @@ public ExternalProjectsStructure getStructure() { public void updateUpTo(ExternalSystemNode node) { treeStructure.updateUpTo(node); } + + @Override + public void handleDoubleClickOrEnter(@NotNull ExternalSystemNode node, @Nullable String actionId, InputEvent inputEvent) { + SelectExternalSystemNodeDialog.this.handleDoubleClickOrEnter(node, actionId, inputEvent); + } }); final Collection<ExternalProjectInfo> projectsData = @@ -107,6 +117,9 @@ public boolean accept(SimpleNode each) { init(); } + protected void handleDoubleClickOrEnter(@NotNull ExternalSystemNode node, @Nullable String actionId, InputEvent inputEvent) { + } + protected SimpleNode getSelectedNode() { return myTree.getNodeFor(myTree.getSelectionPath()); }
05ef7eb774bd373c627ec0a5601ffb4bb245a45c
intellij-community
Major changes in data structures.- Reimplementation & beautification.--
p
https://github.com/JetBrains/intellij-community
diff --git a/jps/antLayout/antlayout.iml b/jps/antLayout/antlayout.iml index 1c77fe401738c..63b6c029c41ca 100644 --- a/jps/antLayout/antlayout.iml +++ b/jps/antLayout/antlayout.iml @@ -5,7 +5,7 @@ <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> </content> - <orderEntry type="inheritedJdk" /> + <orderEntry type="jdk" jdkName="IDEA jdk" jdkType="JavaSDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Ant" level="project" /> </component> diff --git a/jps/jps.iml b/jps/jps.iml index 725fd836a13f0..6bc3adbc818f0 100644 --- a/jps/jps.iml +++ b/jps/jps.iml @@ -7,22 +7,15 @@ <sourceFolder url="file://$MODULE_DIR$/testSrc" isTestSource="true" /> <excludeFolder url="file://$MODULE_DIR$/build" /> </content> - <orderEntry type="inheritedJdk" /> + <orderEntry type="jdk" jdkName="IDEA jdk" jdkType="JavaSDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Groovy" level="project" /> <orderEntry type="library" name="Ant" level="project" /> <orderEntry type="library" name="Javac2" level="project" /> <orderEntry type="module" module-name="antlayout" /> <orderEntry type="library" scope="TEST" name="JUnit" level="project" /> - <orderEntry type="module-library"> - <library name="Gant"> - <CLASSES> - <root url="jar:///usr/share/groovy/lib/gant-1.8.1.jar!/" /> - </CLASSES> - <JAVADOC /> - <SOURCES /> - </library> - </orderEntry> + <orderEntry type="library" exported="" name="Gant" level="application" /> + <orderEntry type="library" name="Gant" level="application" /> </component> </module> diff --git a/jps/plugins/gwt/gwt.iml b/jps/plugins/gwt/gwt.iml index ced8806f42f00..8a514adfdbda9 100644 --- a/jps/plugins/gwt/gwt.iml +++ b/jps/plugins/gwt/gwt.iml @@ -5,7 +5,7 @@ <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> </content> - <orderEntry type="inheritedJdk" /> + <orderEntry type="jdk" jdkName="IDEA jdk" jdkType="JavaSDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="module" module-name="jps" /> <orderEntry type="library" name="Groovy" level="project" /> diff --git a/jps/plugins/javaee/javaee.iml b/jps/plugins/javaee/javaee.iml index f8fe61eb4d9e4..b21e687f59bb2 100644 --- a/jps/plugins/javaee/javaee.iml +++ b/jps/plugins/javaee/javaee.iml @@ -5,7 +5,7 @@ <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> </content> - <orderEntry type="inheritedJdk" /> + <orderEntry type="jdk" jdkName="IDEA jdk" jdkType="JavaSDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Groovy" level="project" /> <orderEntry type="module" module-name="jps" /> diff --git a/jps/plugins/jpa/jpa.iml b/jps/plugins/jpa/jpa.iml index f8fe61eb4d9e4..b21e687f59bb2 100644 --- a/jps/plugins/jpa/jpa.iml +++ b/jps/plugins/jpa/jpa.iml @@ -5,7 +5,7 @@ <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> </content> - <orderEntry type="inheritedJdk" /> + <orderEntry type="jdk" jdkName="IDEA jdk" jdkType="JavaSDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Groovy" level="project" /> <orderEntry type="module" module-name="jps" /> diff --git a/jps/src/org/jetbrains/ether/DirectoryScanner.java b/jps/src/org/jetbrains/ether/DirectoryScanner.java index bc318ae1a0c74..ca50b38b626a6 100644 --- a/jps/src/org/jetbrains/ether/DirectoryScanner.java +++ b/jps/src/org/jetbrains/ether/DirectoryScanner.java @@ -3,8 +3,7 @@ import javax.xml.transform.Result; import java.io.File; import java.io.FileFilter; -import java.util.ArrayList; -import java.util.List; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -15,43 +14,92 @@ * Time: 2:01 * To change this template use File | Settings | File Templates. */ + public class DirectoryScanner { - private static FileFilter myDirectoryFilter = new FileFilter() { - public boolean accept (File f) { - final String name = f.getName(); - return f.isDirectory() && !name.equals(".") && !name.equals("..") ; + public static class Result { + final Set<ProjectWrapper.FileWrapper> myFiles; + long myLatest; + long myEarliest; + + public Result () { + myFiles = new HashSet<ProjectWrapper.FileWrapper> (); + myLatest = 0; + myEarliest = Long.MAX_VALUE; + } + + public void update (final ProjectWrapper.FileWrapper w) { + final long t = w.getStamp (); + + if (t > myLatest) + myLatest = t; + + if (t< myEarliest) + myEarliest = t; + + myFiles.add(w); + } + + public long getEarliest () { + return myEarliest; + } + + public long getLatest () { + return myLatest; + } + + public Set<ProjectWrapper.FileWrapper> getFiles () { + return myFiles; + } + } + + private static class Crawler { + final Result myResult; + final FileFilter myFilter; + final ProjectWrapper myProjectWrapper; + + public Crawler (final FileFilter ff, final ProjectWrapper pw) { + myResult = new Result(); + myFilter = ff; + myProjectWrapper = pw; + } + + public Result getResult () { + return myResult; } - }; - private static FileFilter filterByExtensions (final String[] exts) { - return new FileFilter (){ - public boolean accept (File path) { - final String filename = path.getName(); + public void run(File root) { + if (root.exists()) { + final File[] files = root.listFiles(myFilter); - for (int i = 0; i<exts.length; i++) { - if (filename.endsWith(exts[i])) - return true; + for (int i = 0; i < files.length; i++) { + myResult.update (myProjectWrapper.new FileWrapper(files[i])); } - return false; + final File[] subdirs = root.listFiles(myDirectoryFilter); + + for (int i = 0; i < subdirs.length; i++) { + run(subdirs[i]); + } } - }; + } } - public static class Result { - public List<String> myFiles = new ArrayList<String> (); - public long myEarliest = Long.MAX_VALUE; - public long myLatest = 0; - } + private static FileFilter myDirectoryFilter = new FileFilter() { + public boolean accept(File f) { + final String name = f.getName(); + + return f.isDirectory() && !name.equals(".") && !name.equals(".."); + } + }; private static FileFilter myTrueFilter = new FileFilter() { - public boolean accept (File s) { - return true; - } - }; + public boolean accept(File s) { + return s.isFile(); + } + }; - private static FileFilter createFilter (final List<String> excludes) { + private static FileFilter createFilter(final Collection<String> excludes) { if (excludes == null) { return myTrueFilter; } @@ -62,7 +110,7 @@ private static FileFilter createFilter (final List<String> excludes) { StringBuffer alternative = new StringBuffer(); if (exclude != null) { - for (int i = 0; i<exclude.length(); i++) { + for (int i = 0; i < exclude.length(); i++) { final char c = exclude.charAt(i); switch (c) { @@ -104,11 +152,11 @@ private static FileFilter createFilter (final List<String> excludes) { final Pattern patt = Pattern.compile(buf.toString()); return new FileFilter() { - public boolean accept (File f) { + public boolean accept(File f) { final Matcher m = patt.matcher(f.getAbsolutePath()); final boolean ok = !m.matches(); - return ok; + return ok && f.isFile(); } }; } @@ -116,36 +164,21 @@ public boolean accept (File f) { return myTrueFilter; } - public static Result getFiles (final String root, final List<String> excludes) { - final Result result = new Result (); - final FileFilter ff = createFilter(excludes); - - new Object(){ - public void run (File root) { - if (root.exists()) { - final File[] files = root.listFiles(ff); + public static Result getFiles(final String root, final Set<String> excludes, final ProjectWrapper pw) { + final Crawler cw = new Crawler(createFilter(excludes), pw); - for (int i = 0; i<files.length; i++) { - long t = files[i].lastModified(); + if (root != null) + cw.run(new File(pw.getAbsolutePath(root))); - if (t > result.myLatest) - result.myLatest = t; - - if (t < result.myEarliest) - result.myEarliest = t; - - result.myFiles.add(files[i].getAbsolutePath()); - } + return cw.getResult(); + } - final File[] subdirs = root.listFiles(myDirectoryFilter); + public static Result getFiles(final Set<String> roots, final Set<String> excludes, final ProjectWrapper pw) { + final Crawler cw = new Crawler(createFilter(excludes), pw); - for (int i=0; i<subdirs.length; i++) { - run (subdirs [i]); - } - } - } - }.run(new File (root)); + for (String root : roots) + cw.run(new File(pw.getAbsolutePath(root))); - return result; + return cw.getResult(); } } diff --git a/jps/src/org/jetbrains/ether/Main.java b/jps/src/org/jetbrains/ether/Main.java index 2809ad79383b9..816e657b6e76d 100644 --- a/jps/src/org/jetbrains/ether/Main.java +++ b/jps/src/org/jetbrains/ether/Main.java @@ -134,14 +134,14 @@ public static void main(String[] args) { } for (String prj : projects) { - final ProjectWrapper project = new ProjectWrapper(prj); boolean saved = false; + ProjectWrapper project = null; switch (getAction()) { case CLEAN: - System.out.println("Cleaning project \"" + prj + "\""); - project.load(); + project = ProjectWrapper.load(prj); + project.clean(); project.save(); saved = true; @@ -149,7 +149,7 @@ public static void main(String[] args) { case REBUILD: System.out.println("Rebuilding project \"" + prj + "\""); - project.load(); + project = ProjectWrapper.load(prj); project.rebuild(); project.save(); saved = true; @@ -162,13 +162,13 @@ public static void main(String[] args) { final String module = ((Options.Value) make).get(); System.out.println("Making module \"" + module + "\" in project \"" + prj + "\""); - project.load(); + project = ProjectWrapper.load(prj); project.makeModule(module, doForce(), doTests()); project.save(); saved = true; } else if (make instanceof Options.Switch) { System.out.println("Making project \"" + prj + "\""); - project.load(); + project = ProjectWrapper.load(prj); project.make(doForce(), doTests()); project.save(); saved = true; @@ -179,14 +179,14 @@ public static void main(String[] args) { final Options.Argument inspect = doInspect(); if (inspect instanceof Options.Switch) { - project.load(); + project = ProjectWrapper.load(prj); project.report(); if (doSave()) { project.save(); saved = true; } } else if (inspect instanceof Options.Value) { - project.load(); + project = ProjectWrapper.load(prj); project.report(((Options.Value) inspect).get()); if (doSave()) { project.save(); @@ -195,7 +195,7 @@ public static void main(String[] args) { } if (doSave() && !saved) { - project.load(); + project = ProjectWrapper.load(prj); project.save(); } } diff --git a/jps/src/org/jetbrains/ether/ModuleStatus.java b/jps/src/org/jetbrains/ether/ModuleStatus.java deleted file mode 100644 index 5435bada96398..0000000000000 --- a/jps/src/org/jetbrains/ether/ModuleStatus.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.jetbrains.ether; - -import java.io.Serializable; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 19.11.10 - * Time: 3:40 - * To change this template use File | Settings | File Templates. - */ -public class ModuleStatus { - private static Pattern myPattern = Pattern.compile("([^ ]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)"); - - String myName; - long mySourceStamp; - long myOutputStamp; - long myTestSourceStamp; - long myTestOutputStamp; - - public ModuleStatus(String name, long ss, long os, long tss, long tos) { - myName = name; - mySourceStamp = ss; - myOutputStamp = os; - myTestSourceStamp = tss; - myTestOutputStamp = tos; - } - - public String getName () { - return myName; - } - - public String toString () { - return myName + " " + mySourceStamp + " " + myOutputStamp + " " + myTestSourceStamp + " " + myTestOutputStamp; - } - - public ModuleStatus(final String s) { - final Matcher m = myPattern.matcher(s); - - if (m.matches()) { - myName = m.group(1); - mySourceStamp = Long.parseLong(m.group(2)); - myOutputStamp = Long.parseLong(m.group(3)); - myTestSourceStamp = Long.parseLong(m.group(4)); - myTestOutputStamp = Long.parseLong(m.group(5)); - } - else - System.err.println("Error converting string \"" + s + "\" to ModuleStatus"); - } - - private static boolean wiseCompare (long input, long output) { - final boolean result = (input > 0 && output == Long.MAX_VALUE) || (output <= input); - return result; - } - - public boolean isOutdated(boolean tests) { - final boolean result = wiseCompare(mySourceStamp, myOutputStamp) || (tests && wiseCompare(myTestSourceStamp, myTestOutputStamp)); - return result; - } -} diff --git a/jps/src/org/jetbrains/ether/ProjectSnapshot.java b/jps/src/org/jetbrains/ether/ProjectSnapshot.java deleted file mode 100644 index 421f298272bea..0000000000000 --- a/jps/src/org/jetbrains/ether/ProjectSnapshot.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.jetbrains.ether; - -import java.io.*; -import java.util.HashMap; -import java.util.Map; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 19.11.10 - * Time: 3:05 - * To change this template use File | Settings | File Templates. - */ -public class ProjectSnapshot { - String myProjectStructure; - Map<String, ModuleStatus> myModuleHistories; - - public ProjectSnapshot(final String prjStruct, final Map<String, ModuleStatus> moduleHistories) { - myProjectStructure = prjStruct; - myModuleHistories = moduleHistories; - } - - public String toString () { - StringBuffer buf = new StringBuffer(); - - buf.append(myModuleHistories.size() + "\n"); - - for (ModuleStatus h : myModuleHistories.values()) { - buf.append(h.toString() + "\n"); - } - - buf.append(myProjectStructure); - - return buf.toString(); - } - - public ProjectSnapshot(final String s) { - BufferedReader rd = new BufferedReader(new StringReader(s)); - - try { - final int n = Integer.parseInt(rd.readLine()); - - myModuleHistories = new HashMap<String, ModuleStatus>(); - - for (int i = 0; i<n; i++) { - ModuleStatus h = new ModuleStatus(rd.readLine()); - myModuleHistories.put(h.getName(), h); - } - - StringBuffer buf = new StringBuffer(); - - while (true) { - final String str = rd.readLine(); - - if (str == null) - break; - - buf.append(str); - buf.append("\n"); - } - - - myProjectStructure = buf.toString(); - } - catch (IOException e) { - e.printStackTrace(); - } - } - - public boolean structureChanged (final ProjectSnapshot p) { - return ! p.myProjectStructure.equals(myProjectStructure); - } -} diff --git a/jps/src/org/jetbrains/ether/ProjectWrapper.java b/jps/src/org/jetbrains/ether/ProjectWrapper.java index eeeaaff01707c..cf31cadfb1e43 100644 --- a/jps/src/org/jetbrains/ether/ProjectWrapper.java +++ b/jps/src/org/jetbrains/ether/ProjectWrapper.java @@ -1,11 +1,9 @@ package org.jetbrains.ether; -import com.sun.org.apache.xpath.internal.operations.Mod; import org.codehaus.gant.GantBinding; -import org.jetbrains.jps.ClasspathItem; -import org.jetbrains.jps.Module; -import org.jetbrains.jps.Project; +import org.jetbrains.jps.*; import org.jetbrains.jps.idea.IdeaProjectLoader; +import org.jetbrains.jps.resolvers.PathEntry; import java.io.*; import java.util.*; @@ -17,6 +15,7 @@ * Time: 2:58 * To change this template use File | Settings | File Templates. */ + public class ProjectWrapper { // Home directory private static final String myHomeDir = System.getProperty("user.home"); @@ -24,16 +23,182 @@ public class ProjectWrapper { // JPS directory private static final String myJPSDir = ".jps"; + // IDEA project structure directory name + private static final String myIDEADir = ".idea"; + // JPS directory initialization - private static void initJPSDirectory () { + private static void initJPSDirectory() { final File f = new File(myHomeDir + File.separator + myJPSDir); - if (! f.exists()) + if (!f.exists()) f.mkdir(); } + private static <T> List<T> sort(final Collection<T> coll, final Comparator<? super T> comp) { + List<T> list = new ArrayList<T>(); + + for (T elem : coll) { + if (elem != null) { + list.add(elem); + } + } + + Collections.sort(list, comp); + + return list; + } + + private static <T extends Comparable<? super T>> List<T> sort(final Collection<T> coll) { + return sort(coll, new Comparator<T>() { + public int compare(T a, T b) { + return a.compareTo(b); + } + }); + } + + private interface Writable extends Comparable { + public void write(BufferedWriter w); + } + + private static void writeln(final BufferedWriter w, final Collection<String> c, final String desc) { + writeln(w, Integer.toString(c.size())); + + if (c instanceof List) { + for (String e : c) { + writeln(w, e); + } + } else { + final List<String> sorted = sort(c); + + for (String e : sorted) { + writeln(w, e); + } + } + } + + private static void writeln(final BufferedWriter w, final Collection<? extends Writable> c) { + writeln(w, Integer.toString(c.size())); + + if (c instanceof List) { + for (Writable e : c) { + e.write(w); + } + } else { + final List<? extends Writable> sorted = sort(c); + + for (Writable e : sorted) { + e.write(w); + } + } + } + + private static void writeln(final BufferedWriter w, final String s) { + try { + w.write(s); + w.newLine(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private interface Constructor<T> { + public T read(BufferedReader r); + } + + private static Constructor<String> myStringConstructor = new Constructor<String>() { + public String read(final BufferedReader r) { + try { + return r.readLine(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + }; + + private static <T> Collection<T> readMany(final BufferedReader r, final Constructor<T> c, final Collection<T> acc) { + final int size = readInt(r); + + for (int i = 0; i < size; i++) { + acc.add(c.read(r)); + } + + return acc; + } + + private static String lookString(final BufferedReader r) { + try { + r.mark(256); + final String s = r.readLine(); + r.reset(); + + return s; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + private static void readTag(final BufferedReader r, final String tag) { + try { + final String s = r.readLine(); + + if (!s.equals(tag)) + System.err.println("Parsing error: expected \"" + tag + "\", but found \"" + s + "\""); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static String readString(final BufferedReader r) { + try { + return r.readLine(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + private static long readLong(final BufferedReader r) { + final String s = readString(r); + + try { + return Long.parseLong(s); + } catch (Exception n) { + System.err.println("Parsing error: expected long, but found \"" + s + "\""); + return 0; + } + } + + private static int readInt(final BufferedReader r) { + final String s = readString(r); + + try { + return Integer.parseInt(s); + } catch (Exception n) { + System.err.println("Parsing error: expected integer, but found \"" + s + "\""); + return 0; + } + } + + private static String readStringAttribute(final BufferedReader r, final String tag) { + try { + final String s = r.readLine(); + + if (s.startsWith(tag)) + return s.substring(tag.length()); + + System.err.println("Parsing error: expected \"" + tag + "\", but found \"" + s + "\""); + + return null; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + // File separator replacement - private static final char myFileSeparatorReplacement = '-'; + private static final char myFileSeparatorReplacement = '.'; // Original JPS Project private final Project myProject; @@ -41,60 +206,596 @@ private static void initJPSDirectory () { // Project directory private final String myRoot; - // Project snapshot file + // Project snapshot file name private final String myProjectSnapshot; - // Project history - private ProjectSnapshot mySnapshot; - private ProjectSnapshot myPresent; + public interface ClasspathItemWrapper extends Writable { + public List<String> getClassPath(ClasspathKind kind); + } + + public final Constructor<LibraryWrapper> myLibraryWrapperConstructor = + new Constructor<LibraryWrapper>() { + public LibraryWrapper read(final BufferedReader r) { + return new LibraryWrapper(r); + } + }; + + public class LibraryWrapper implements ClasspathItemWrapper { + final String myName; + final List<String> myClassPath; + + public void write(final BufferedWriter w) { + writeln(w, "Library:" + myName); + writeln(w, "Classpath:"); + writeln(w, myClassPath, null); + } + + public LibraryWrapper(final BufferedReader r) { + myName = readStringAttribute(r, "Library:"); + + readTag(r, "Classpath:"); + myClassPath = (List<String>) readMany(r, myStringConstructor, new ArrayList<String>()); + } + + public LibraryWrapper(final Library lib) { + lib.forceInit(); + myName = lib.getName(); + myClassPath = (List<String>) getRelativePaths(lib.getClasspath(), new ArrayList<String>()); + } + + public String getName() { + return myName; + } + + public List<String> getClassPath(final ClasspathKind kind) { + return myClassPath; + } + + public int compareTo(Object o) { + return getName().compareTo(((LibraryWrapper) o).getName()); + } + } + + public final Constructor<ClasspathItemWrapper> myClasspathItemWrapperConstructor = + new Constructor<ClasspathItemWrapper>() { + public ClasspathItemWrapper read(final BufferedReader r) { + final String s = lookString(r); + if (s.startsWith("Library:")) { + return new LibraryWrapper(r); + } + if (s.startsWith("Module:")) { + return new ModuleWrapper(r); + } else { + return new GenericClasspathItemWrapper(r); + } + } + }; + + public class GenericClasspathItemWrapper implements ClasspathItemWrapper { + final List<String> myClassPath; + final String myType; + + public GenericClasspathItemWrapper(final ClasspathItem item) { + if (item instanceof PathEntry) + myType = "PathEntry"; + else if (item instanceof JavaSdk) + myType = "JavaSdk"; + else if (item instanceof Sdk) + myType = "Sdk"; + else + myType = null; + + myClassPath = (List<String>) getRelativePaths(item.getClasspathRoots(null), new ArrayList<String>()); + } + + public GenericClasspathItemWrapper(final BufferedReader r) { + myType = readString(r); + + readTag(r, "Classpath:"); + myClassPath = (List<String>) readMany(r, myStringConstructor, new ArrayList<String>()); + } + + public String getType() { + return myType; + } + + public List<String> getClassPath(final ClasspathKind kind) { + return myClassPath; + } + + public void write(final BufferedWriter w) { + writeln(w, myType); + writeln(w, "Classpath:"); + writeln(w, myClassPath, ""); + } + + public int compareTo(Object o) { + final GenericClasspathItemWrapper w = (GenericClasspathItemWrapper) o; + final int c = getType().compareTo(w.getType()); + return + c == 0 ? + (new Object() { + public int compare(Iterator<String> x, Iterator<String> y) { + if (x.hasNext()) { + if (y.hasNext()) { + final int c = x.next().compareTo(y.next()); + + return c == 0 ? compare(x, y) : c; + } + + return 1; + } else if (y.hasNext()) { + return -1; + } + + return 0; + } + } + ).compare(getClassPath(null).iterator(), w.getClassPath(null).iterator()) + : c; + } + } + + public final Constructor<FileWrapper> myFileWrapperConstructor = + new Constructor<FileWrapper>() { + public FileWrapper read(final BufferedReader r) { + return new FileWrapper(r); + } + }; + + public class FileWrapper implements Writable { + final String myName; + final long myModificationTime; + + FileWrapper(final File f) { + myName = getRelativePath(f.getAbsolutePath()); + myModificationTime = f.lastModified(); + } + + FileWrapper(final BufferedReader r) { + myName = readString(r); + myModificationTime = 0; // readLong(r); + } + + public String getName() { + return myName; + } + + public long getStamp() { + return myModificationTime; + } + + public void write(final BufferedWriter w) { + writeln(w, getName()); + // writeln(w, Long.toString(getStamp())); + } + + public int compareTo(Object o) { + return getName().compareTo(((FileWrapper) o).getName()); + } + } + + public final Constructor<ModuleWrapper> myModuleWrapperConstructor = + new Constructor<ModuleWrapper>() { + public ModuleWrapper read(final BufferedReader r) { + return new ModuleWrapper(r); + } + }; + + public class ModuleWrapper implements ClasspathItemWrapper { + + private class Properties implements Writable { + + final Set<String> myRoots; + final Set<FileWrapper> mySources; + + final String myOutput; + final Set<FileWrapper> myOutputs; + + final long myLatestSource; + final long myEarliestSource; + + final long myLatestOutput; + final long myEarliestOutput; + + public void write(final BufferedWriter w) { + writeln(w, "Roots:"); + writeln(w, myRoots, null); + + writeln(w, "Sources:"); + writeln(w, mySources); + + writeln(w, "Output:"); + writeln(w, myOutput == null ? "" : myOutput); + + writeln(w, "Outputs:"); + writeln(w, myOutputs); + + //writeln(w, "EarliestSource:"); + //writeln(w, Long.toString(myEarliestSource)); + + //writeln(w, "LatestSource:"); + //writeln(w, Long.toString(myLatestSource)); + + //writeln(w, "EarliestOutput:"); + //writeln(w, Long.toString(myEarliestOutput)); + + //writeln(w, "LatestOutput:"); + //writeln(w, Long.toString(myLatestOutput)); + } + + public Properties(final BufferedReader r) { + readTag(r, "Roots:"); + myRoots = (Set<String>) readMany(r, myStringConstructor, new HashSet<String>()); + + readTag(r, "Sources:"); + mySources = (Set<FileWrapper>) readMany(r, myFileWrapperConstructor, new HashSet<FileWrapper>()); + + readTag(r, "Output:"); + final String s = readString(r); + myOutput = s.equals("") ? null : s; + + readTag(r, "Outputs:"); + myOutputs = (Set<FileWrapper>) readMany(r, myFileWrapperConstructor, new HashSet<FileWrapper>()); + + //readTag(r, "EarliestSource:"); + myEarliestSource = 0;//readLong(r); - public ProjectWrapper(final String prjDir) { + //readTag(r, "LatestSource:"); + myLatestSource = 0;//readLong(r); + + //readTag(r, "EarliestOutput:"); + myEarliestOutput = 0;//readLong(r); + + //readTag(r, "LatestOutput:"); + myLatestOutput = 0;//readLong(r); + } + + public Properties(final List<String> sources, final String output, final Set<String> excludes) { + myRoots = (Set<String>) getRelativePaths(sources, new HashSet<String>()); + + { + final DirectoryScanner.Result result = DirectoryScanner.getFiles(myRoots, excludes, ProjectWrapper.this); + mySources = result.getFiles(); + myEarliestSource = result.getEarliest(); + myLatestSource = result.getLatest(); + } + + { + myOutput = getRelativePath(output); + final DirectoryScanner.Result result = DirectoryScanner.getFiles(myOutput, excludes, ProjectWrapper.this); + myOutputs = result.getFiles(); + myEarliestOutput = result.getEarliest(); + myLatestOutput = result.getLatest(); + } + } + + public Set<String> getRoots() { + return myRoots; + } + + public Set<FileWrapper> getSources() { + return mySources; + } + + public String getOutputPath() { + return myOutput; + } + + public Set<FileWrapper> getOutputs() { + return myOutputs; + } + + public long getEarliestOutput() { + return myEarliestOutput; + } + + public long getLatestOutput() { + return myLatestOutput; + } + + public long getEarliestSource() { + return myEarliestSource; + } + + public long getLatestSource() { + return myLatestSource; + } + + public boolean emptySource() { + return mySources.isEmpty(); + } + + public boolean emptyOutput() { + return myOutputs.isEmpty(); + } + + public boolean isOutdated() { + return (!emptySource() && emptyOutput()) || (getLatestSource() > getEarliestOutput()); + } + + public int compareTo(Object o) { + return 0; + } + } + + final String myName; + final Properties mySource; + final Properties myTest; + + final Set<String> myExcludes; + + final Module myModule; + List<ClasspathItemWrapper> myDependsOn; + + final Set<LibraryWrapper> myLibraries; + + public void write(final BufferedWriter w) { + writeln(w, "Module:" + myName); + + writeln(w, "SourceProperties:"); + mySource.write(w); + + writeln(w, "TestProperties:"); + myTest.write(w); + + writeln(w, "Excludes:"); + writeln(w, myExcludes, null); + + writeln(w, "Libraries:"); + writeln(w, myLibraries); + + writeln(w, "Dependencies:"); + writeln(w, dependsOn()); + } + + public ModuleWrapper(final BufferedReader r) { + myModule = null; + myName = readStringAttribute(r, "Module:"); + + readTag(r, "SourceProperties:"); + mySource = new Properties(r); + + readTag(r, "TestProperties:"); + myTest = new Properties(r); + + readTag(r, "Excludes:"); + myExcludes = (Set<String>) readMany(r, myStringConstructor, new HashSet<String>()); + + readTag(r, "Libraries:"); + myLibraries = (Set<LibraryWrapper>) readMany(r, myLibraryWrapperConstructor, new HashSet<LibraryWrapper>()); + + readTag(r, "Dependencies:"); + myDependsOn = (List<ClasspathItemWrapper>) readMany(r, myClasspathItemWrapperConstructor, new ArrayList<ClasspathItemWrapper>()); + } + + public ModuleWrapper(final Module m) { + m.forceInit(); + myModule = m; + myDependsOn = null; + myName = m.getName(); + myExcludes = (Set<String>) getRelativePaths(m.getExcludes(), new HashSet<String>()); + mySource = new Properties(m.getSourceRoots(), m.getOutputPath(), myExcludes); + myTest = new Properties(m.getTestRoots(), m.getTestOutputPath(), myExcludes); + + myLibraries = new HashSet<LibraryWrapper>(); + + for (Library lib : m.getLibraries().values()) { + myLibraries.add(new LibraryWrapper(lib)); + } + } + + public String getName() { + return myName; + } + + public Set<String> getSourceRoots() { + return mySource.getRoots(); + } + + public Set<FileWrapper> getSourceFiles() { + return mySource.getSources(); + } + + public String getOutputPath() { + return mySource.getOutputPath(); + } + + public Set<String> getTestSourceRoots() { + return myTest.getRoots(); + } + + public Set<FileWrapper> getTestSourceFiles() { + return myTest.getSources(); + } + + public String getTestOutputPath() { + return myTest.getOutputPath(); + } + + public List<ClasspathItemWrapper> dependsOn() { + if (myDependsOn != null) + return myDependsOn; + + myDependsOn = new ArrayList<ClasspathItemWrapper>(); + + for (Module.ModuleDependency dep : myModule.getDependencies()) { + final ClasspathItem cpi = dep.getItem(); + + if (cpi instanceof Module) { + myDependsOn.add(getModule(((Module) cpi).getName())); + } else if (cpi instanceof Library) { + myDependsOn.add(new LibraryWrapper((Library) cpi)); + } else { + myDependsOn.add(new GenericClasspathItemWrapper(cpi)); + } + } + + return myDependsOn; + } + + public List<String> getClassPath(final ClasspathKind kind) { + final List<String> result = new ArrayList<String>(); + + result.add(getOutputPath()); + + if (kind.isTestsIncluded()) { + result.add(getTestOutputPath()); + } + + return result; + } + + public boolean isOutdated(final boolean tests) { + return mySource.isOutdated() || (tests && myTest.isOutdated()); + } + + public int compareTo(Object o) { + return getName().compareTo(((ModuleWrapper) o).getName()); + } + } + + final Map<String, ModuleWrapper> myModules = new HashMap<String, ModuleWrapper>(); + final Map<String, LibraryWrapper> myLibraries = new HashMap<String, LibraryWrapper>(); + final ProjectWrapper myHistory; + + public ModuleWrapper getModule(final String name) { + return myModules.get(name); + } + + public LibraryWrapper getLibrary(final String name) { + return myLibraries.get(name); + } + + public Collection<LibraryWrapper> getLibraries() { + return myLibraries.values(); + } + + public Collection<ModuleWrapper> getModules() { + return myModules.values(); + } + + private ProjectWrapper(final String prjDir) { myProject = new Project(new GantBinding()); - myRoot = new File (prjDir).getAbsolutePath(); + myRoot = new File(prjDir).getAbsolutePath(); myProjectSnapshot = myHomeDir + File.separator + myJPSDir + File.separator + myRoot.replace(File.separatorChar, myFileSeparatorReplacement); + + IdeaProjectLoader.loadFromPath(myProject, getAbsolutePath(myIDEADir)); + + for (Module m : myProject.getModules().values()) { + myModules.put(m.getName(), new ModuleWrapper(m)); + } + + for (Library l : myProject.getLibraries().values()) { + myLibraries.put(l.getName(), new LibraryWrapper(l)); + } + + myHistory = loadSnapshot(); } - private String getProjectSnapshotFileName() { - return myProjectSnapshot; + public String getAbsolutePath(final String relative) { + if (relative == null) + return relative; + + if (new File(relative).isAbsolute()) + return relative; + + return myRoot + File.separator + relative; } - private ProjectSnapshot loadSnapshot() { - initJPSDirectory(); + public String getRelativePath(final String absolute) { + if (absolute == null) + return absolute; - ProjectSnapshot result = null; + if (absolute.startsWith(myRoot)) { + return absolute.substring(myRoot.length() + 1); + } - try { - final String path = getProjectSnapshotFileName(); + return absolute; + } - byte[] buffer = new byte[(int) new File(path).length()]; + public Collection<String> getAbsolutePaths(final Collection<String> paths, final Collection<String> result) { + for (String path : paths) { + if (path != null) + result.add(getAbsolutePath(path)); + } - BufferedInputStream f = new BufferedInputStream(new FileInputStream(path)); + return result; + } - f.read(buffer); + public Collection<String> getRelativePaths(final Collection<String> paths, final Collection<String> result) { + for (String path : paths) { + if (path != null) + result.add(getRelativePath(path)); + } + + return result; + } + + private boolean isHistory() { + return myProject == null; + } + + private ProjectWrapper(final BufferedReader r) { + myProject = null; + myHistory = null; - f.close(); + myRoot = readStringAttribute(r, "Root:"); + myProjectSnapshot = myHomeDir + File.separator + myJPSDir + File.separator + myRoot.replace(File.separatorChar, myFileSeparatorReplacement); - result = new ProjectSnapshot(new String(buffer)); + readTag(r, "Libraries:"); + final Set<LibraryWrapper> libs = (Set<LibraryWrapper>) readMany(r, myLibraryWrapperConstructor, new HashSet<LibraryWrapper>()); + + for (LibraryWrapper l : libs) { + myLibraries.put(l.getName(), l); } - catch (FileNotFoundException e) { + readTag(r, "Modules:"); + final Set<ModuleWrapper> mods = (Set<ModuleWrapper>) readMany(r, myModuleWrapperConstructor, new HashSet<ModuleWrapper>()); + + for (ModuleWrapper m : mods) { + myModules.put(m.getName(), m); } - catch (IOException e) { + } + + public void write(final BufferedWriter w) { + writeln(w, "Root:" + myRoot); + + writeln(w, "Libraries:"); + writeln(w, getLibraries()); + + writeln(w, "Modules:"); + writeln(w, getModules()); + } + + private String getProjectSnapshotFileName() { + return myProjectSnapshot; + } + + private ProjectWrapper loadSnapshot() { + initJPSDirectory(); + + try { + final BufferedReader r = new BufferedReader(new FileReader(getProjectSnapshotFileName())); + final ProjectWrapper w = new ProjectWrapper(r); + r.close(); + + return w; + } catch (FileNotFoundException e) { + } catch (IOException e) { e.printStackTrace(); } - return result; + return null; } private void saveSnapshot() { initJPSDirectory(); - final ProjectSnapshot snapshot = StatusCollector.collectHistory(myProject); - try { BufferedWriter bw = new BufferedWriter(new FileWriter(getProjectSnapshotFileName())); - bw.write(snapshot.toString()); + write(bw); bw.close(); } catch (IOException e) { @@ -102,14 +803,12 @@ private void saveSnapshot() { } } - public void load() { - IdeaProjectLoader.loadFromPath(myProject, myRoot); - mySnapshot = loadSnapshot(); - myPresent = StatusCollector.collectHistory(myProject); + public static ProjectWrapper load(final String path) { + return new ProjectWrapper(path); } public void report(final String module) { - final ModuleStatus m = myPresent.myModuleHistories.get(module); + final ModuleWrapper m = getModule(module); if (m == null) { System.out.println("No module \"" + module + "\" found in project \""); @@ -120,10 +819,36 @@ public void report(final String module) { } private boolean structureChanged() { - if (mySnapshot == null) + if (myHistory == null) return true; - return myPresent.structureChanged(mySnapshot); + try { + final StringWriter my = new StringWriter(); + final StringWriter history = new StringWriter(); + + myHistory.write(new BufferedWriter(my)); + write(new BufferedWriter(history)); + + my.close(); + history.close(); + + final String myString = my.getBuffer().toString(); + final String hisString = history.getBuffer().toString(); + + FileWriter f1 = new FileWriter("/home/db/tmp/1.jps"); + FileWriter f2 = new FileWriter("/home/db/tmp/2.jps"); + + f1.write(myString); + f2.write(hisString); + + f1.close(); + f2.close(); + + return !myString.equals(hisString); + } catch (IOException e) { + e.printStackTrace(); + return true; + } } public void report() { @@ -131,7 +856,7 @@ public void report() { System.out.println("Project \"" + myRoot + "\" report:"); - if (mySnapshot == null) { + if (myHistory == null) { System.out.println(" no project history found"); } else { if (structureChanged()) { @@ -141,9 +866,9 @@ public void report() { } if (moduleReport) { - for (ModuleStatus mh : myPresent.myModuleHistories.values()) { - System.out.println(" module " + mh.myName + " " + (mh.isOutdated(false) ? "is outdated" : "is up-to-date")); - System.out.println(" module " + mh.myName + " tests " + (mh.isOutdated(true) ? "are outdated" : "are up-to-date")); + for (ModuleWrapper m : myModules.values()) { + System.out.println(" module " + m.getName() + " " + (m.isOutdated(false) ? "is outdated" : "is up-to-date")); + System.out.println(" module " + m.getName() + " tests " + (m.isOutdated(true) ? "are outdated" : "are up-to-date")); } } } @@ -169,7 +894,7 @@ public void make(final boolean force, final boolean tests) { final List<Module> modules = new ArrayList<Module>(); - for (Map.Entry<String, ModuleStatus> entry : myPresent.myModuleHistories.entrySet()) { + for (Map.Entry<String, ModuleWrapper> entry : myModules.entrySet()) { if (entry.getValue().isOutdated(tests)) modules.add(myProject.getModules().get(entry.getKey())); } @@ -189,7 +914,7 @@ public void make(final boolean force, final boolean tests) { private void makeModules(final List<Module> initial, final boolean tests) { final Set<Module> modules = new HashSet<Module>(); - final Map<Module, Set<Module>> reversedDependencies = new HashMap<Module, Set<Module>> (); + final Map<Module, Set<Module>> reversedDependencies = new HashMap<Module, Set<Module>>(); for (Module m : myProject.getModules().values()) { for (Module.ModuleDependency mdep : m.getDependencies()) { @@ -199,7 +924,7 @@ private void makeModules(final List<Module> initial, final boolean tests) { Set<Module> sm = reversedDependencies.get(cpi); if (sm == null) { - sm = new HashSet<Module> (); + sm = new HashSet<Module>(); reversedDependencies.put((Module) cpi, sm); } @@ -244,7 +969,7 @@ public void makeModule(final String modName, final boolean force, final boolean return; } - final ModuleStatus h = myPresent.myModuleHistories.get(modName); + final ModuleWrapper h = getModule(modName); if (h != null && !h.isOutdated(tests) && !force) { System.out.println("Module \"" + modName + "\" in project \"" + myRoot + "\" is up-to-date."); return; diff --git a/jps/src/org/jetbrains/ether/StatusCollector.java b/jps/src/org/jetbrains/ether/StatusCollector.java deleted file mode 100644 index 9d231313ba539..0000000000000 --- a/jps/src/org/jetbrains/ether/StatusCollector.java +++ /dev/null @@ -1,186 +0,0 @@ -package org.jetbrains.ether; - -import com.sun.tools.javac.util.Pair; -import org.jetbrains.jps.*; -import org.jetbrains.jps.resolvers.PathEntry; - -import java.util.*; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 18.11.10 - * Time: 19:57 - * To change this template use File | Settings | File Templates. - */ -public class StatusCollector { - private static Pair<Long, Long> myDefaultPair = new Pair<Long, Long> (Long.MAX_VALUE, 0l); - - private static Pair<Long, Long> join (final Pair<Long, Long> a, final Pair<Long, Long> b) { - if (a == null) - return b; - - if (b == null) - return a; - - return new Pair<Long, Long> (Math.min(a.fst, b.fst), Math.max(a.snd, b.snd)); - } - - private static Comparator<Library> myLibraryComparator = new Comparator<Library>() { - public int compare (Library a, Library b) { - return a.getName().compareTo(b.getName()); - } - }; - - private static Comparator<Module> myModuleComparator = new Comparator<Module>() { - public int compare (Module a, Module b) { - return a.getName().compareTo(b.getName()); - } - }; - - private static <T> List<T> prepare (final Collection<T> coll, final Comparator<T> comp) { - List<T> list = new ArrayList<T> (); - - for (T elem : coll) { - if (elem != null) { - list.add(elem); - } - } - - Collections.sort(list, comp); - - return list; - } - - private static <T extends Comparable<? super T>> List<T> prepare (final Collection<T> coll) { - return prepare(coll, new Comparator<T> () { - public int compare (T a, T b) { - return a.compareTo(b); - } - }); - } - - private static void listToBuffer (StringBuffer buf, final List list) { - for (Object o : prepare (list)) { - if (o instanceof String) { - buf.append(o + "\n"); - } - else { - buf.append("*** <" + o.getClass().getName() + "> is not String ***\n"); - } - } - } - - private static void namedListToBuffer (StringBuffer buf, final String name, final List list) { - buf.append(name + ":\n"); - listToBuffer(buf, list); - } - - private static Pair<Long, Long> directoryToBuffer (StringBuffer buf, final String dir, final List<String> excludes) { - if (dir != null) { - final DirectoryScanner.Result result = DirectoryScanner.getFiles(dir, excludes); - - for (String name : prepare (result.myFiles)) { - buf.append(name + "\n"); - } - - return new Pair<Long, Long> (result.myEarliest, result.myLatest); - } - - return myDefaultPair; - } - - private static Pair<Long, Long> sourceRootToBuffer (StringBuffer buf, final String name, final List<String> dir, final List<String> excludes) { - Pair<Long, Long> result = myDefaultPair; - - buf.append(name + ":\n"); - - for (String d : prepare (dir)) { - if (dir != null) { - buf.append(d + ":\n"); - result = join (result, directoryToBuffer(buf, d, excludes)); - } - } - - return result; - } - - private static void classPathItemToBuffer (StringBuffer buf, final ClasspathItem cpi, boolean all) { - final ClasspathKind[] allKinds = {ClasspathKind.PRODUCTION_COMPILE, ClasspathKind.PRODUCTION_RUNTIME, ClasspathKind.TEST_COMPILE, ClasspathKind.TEST_RUNTIME}; - final ClasspathKind[] oneKind = {ClasspathKind.PRODUCTION_COMPILE}; - final ClasspathKind[] kinds = all ? allKinds : oneKind; - - for (int i=0; i<kinds.length; i++) { - final ClasspathKind kind = kinds[i]; - final String name = kind.name(); - - namedListToBuffer(buf, "classpath" + (all ? " (" + name + ")" : ""), cpi.getClasspathRoots(kind)); - } - } - - public static void libraryToBuffer (StringBuffer buf, final Library library) { - library.forceInit(); - buf.append ("Library: " + library.getName() + "\n"); - classPathItemToBuffer(buf, library, false); - } - - public static ModuleStatus moduleToBuffer (StringBuffer buf, final Module module) { - buf.append("Module: " + module.getName() + "\n"); - - classPathItemToBuffer(buf, module, true); - namedListToBuffer(buf, "Excludes", module.getExcludes()); - - buf.append("Libraries:\n"); - for (Library lib : prepare (module.getLibraries().values(), myLibraryComparator)) { - libraryToBuffer(buf, lib); - } - - long ss = sourceRootToBuffer(buf, "SourceRoots", module.getSourceRoots(), module.getExcludes()).snd; - buf.append("OutputPath: " + module.getOutputPath() + "\n"); - long os = directoryToBuffer(buf, module.getOutputPath(), null).fst; - - long tss = sourceRootToBuffer(buf, "TestRoots", module.getTestRoots(), module.getExcludes()).snd; - buf.append("TestOutputPath: " + module.getTestOutputPath() + "\n"); - long tos = directoryToBuffer(buf, module.getTestOutputPath(), null).fst; - - buf.append("Dependencies:\n"); - for (Module.ModuleDependency dep : module.getDependencies()){ - final ClasspathItem item = dep.getItem(); - if (item instanceof Module) { - buf.append("module " + ((Module) item).getName() + "\n"); - } - else if (item instanceof Library) { - buf.append("library " + ((Library) item).getName() + "\n"); - } - else if (item instanceof JavaSdk) { - buf.append("javaSdk " + ((JavaSdk) item).getName() + "\n"); - } - else if (item instanceof Sdk) { - buf.append("Sdk " + ((Sdk) item).getName() + "\n"); - } - else if (item instanceof PathEntry) { - buf.append("pathEntry " + ((PathEntry) item).getPath() + "\n"); - } - else { - buf.append("unknown ClasspathItem implementation in dependencies: <" + item.getClass().getName() + ">\n"); - } - } - - return new ModuleStatus(module.getName(), ss, os, tss, tos); - } - - public static ProjectSnapshot collectHistory (final Project prj) { - StringBuffer buf = new StringBuffer(); - Map<String, ModuleStatus> moduleHistories = new HashMap<String, ModuleStatus> (); - - for (Library lib : prepare (prj.getLibraries().values(), myLibraryComparator)) { - libraryToBuffer(buf, lib); - } - - for (Module mod : prepare (prj.getModules().values(), myModuleComparator)) { - moduleHistories.put(mod.getName(), moduleToBuffer(buf, mod)); - } - - return new ProjectSnapshot(buf.toString(), moduleHistories); - } -}
11ceaccc20c2e820e4891c5264947a01ca040bf4
elasticsearch
Randomize node level setting per node not per- cluster--
p
https://github.com/elastic/elasticsearch
diff --git a/src/test/java/org/elasticsearch/gateway/fs/IndexGatewayTests.java b/src/test/java/org/elasticsearch/gateway/fs/IndexGatewayTests.java index ed6ebe32d605c..0ca78e105693f 100644 --- a/src/test/java/org/elasticsearch/gateway/fs/IndexGatewayTests.java +++ b/src/test/java/org/elasticsearch/gateway/fs/IndexGatewayTests.java @@ -70,7 +70,6 @@ protected Settings nodeSettings(int nodeOrdinal) { if (between(0, 5) == 0) { builder.put("gateway.fs.chunk_size", between(1, 100) + "kb"); } - builder.put("index.number_of_replicas", "1"); builder.put("index.number_of_shards", rarely() ? Integer.toString(between(2, 6)) : "1"); storeType = rarely() ? "ram" : "fs"; diff --git a/src/test/java/org/elasticsearch/test/TestCluster.java b/src/test/java/org/elasticsearch/test/TestCluster.java index 6509ba74fcbfe..598c2b5ad01ab 100644 --- a/src/test/java/org/elasticsearch/test/TestCluster.java +++ b/src/test/java/org/elasticsearch/test/TestCluster.java @@ -150,21 +150,8 @@ public TestCluster(long clusterSeed, int numNodes, String clusterName) { sharedNodesSeeds[i] = random.nextLong(); } logger.info("Setup TestCluster [{}] with seed [{}] using [{}] nodes", clusterName, SeedUtils.formatSeed(clusterSeed), numSharedNodes); - Builder builder = ImmutableSettings.settingsBuilder() - /* use RAM directories in 10% of the runs */ -// .put("index.store.type", random.nextInt(10) == 0 ? MockRamIndexStoreModule.class.getName() : MockFSIndexStoreModule.class.getName()) - .put("index.store.type", MockFSIndexStoreModule.class.getName()) // no RAM dir for now! - .put(IndexEngineModule.EngineSettings.ENGINE_TYPE, MockEngineModule.class.getName()) - .put("cluster.name", clusterName) - // decrease the routing schedule so new nodes will be added quickly - some random value between 30 and 80 ms - .put("cluster.routing.schedule", (30 + random.nextInt(50)) + "ms") - // default to non gateway - .put("gateway.type", "none"); - if (isLocalTransportConfigured()) { - builder.put(TransportModule.TRANSPORT_TYPE_KEY, AssertingLocalTransportModule.class.getName()); - } else { - builder.put(Transport.TransportSettings.TRANSPORT_TCP_COMPRESS, random.nextInt(10) == 0); - } + this.nodeSettingsSource = nodeSettingsSource; + Builder builder = ImmutableSettings.settingsBuilder(); // randomize (multi/single) data path, special case for 0, don't set it at all... int numOfDataPaths = random.nextInt(5); if (numOfDataPaths > 0) { @@ -174,10 +161,8 @@ public TestCluster(long clusterSeed, int numNodes, String clusterName) { } builder.put("path.data", dataPath.toString()); } - builder.put("type", CacheRecycler.Type.values()[random.nextInt(CacheRecycler.Type.values().length)]); + defaultSettings = builder.build(); - this.defaultSettings = builder.build(); - this.nodeSettingsSource = nodeSettingsSource; } private static boolean isLocalTransportConfigured() { @@ -187,8 +172,9 @@ private static boolean isLocalTransportConfigured() { return Boolean.parseBoolean(System.getProperty("es.node.local", "false")); } - private Settings getSettings(int nodeOrdinal, Settings others) { - Builder builder = ImmutableSettings.settingsBuilder().put(defaultSettings); + private Settings getSettings(int nodeOrdinal, long nodeSeed, Settings others) { + Builder builder = ImmutableSettings.settingsBuilder().put(defaultSettings) + .put(getRandomNodeSettings(nodeSeed, clusterName)); Settings settings = nodeSettingsSource.settings(nodeOrdinal); if (settings != null) { builder.put(settings); @@ -199,6 +185,27 @@ private Settings getSettings(int nodeOrdinal, Settings others) { return builder.build(); } + private static Settings getRandomNodeSettings(long seed, String clusterName) { + Random random = new Random(seed); + Builder builder = ImmutableSettings.settingsBuilder() + /* use RAM directories in 10% of the runs */ + //.put("index.store.type", random.nextInt(10) == 0 ? MockRamIndexStoreModule.class.getName() : MockFSIndexStoreModule.class.getName()) + .put("index.store.type", MockFSIndexStoreModule.class.getName()) // no RAM dir for now! + .put(IndexEngineModule.EngineSettings.ENGINE_TYPE, MockEngineModule.class.getName()) + .put("cluster.name", clusterName) + // decrease the routing schedule so new nodes will be added quickly - some random value between 30 and 80 ms + .put("cluster.routing.schedule", (30 + random.nextInt(50)) + "ms") + // default to non gateway + .put("gateway.type", "none"); + if (isLocalTransportConfigured()) { + builder.put(TransportModule.TRANSPORT_TYPE_KEY, AssertingLocalTransportModule.class.getName()); + } else { + builder.put(Transport.TransportSettings.TRANSPORT_TCP_COMPRESS, random.nextInt(10) == 0); + } + builder.put("type", CacheRecycler.Type.values()[random.nextInt(CacheRecycler.Type.values().length)]); + return builder.build(); + } + public static String clusterName(String prefix, String childVMId, long clusterSeed) { StringBuilder builder = new StringBuilder(prefix); builder.append('-').append(NetworkUtils.getLocalAddress().getHostName()); @@ -298,7 +305,7 @@ private NodeAndClient buildNode() { private NodeAndClient buildNode(int nodeId, long seed, Settings settings) { ensureOpen(); - settings = getSettings(nodeId, settings); + settings = getSettings(nodeId, seed, settings); String name = buildNodeName(nodeId); assert !nodes.containsKey(name); Settings finalSettings = settingsBuilder() @@ -616,7 +623,7 @@ private synchronized void reset(Random random, boolean wipeData, double transpor NodeAndClient nodeAndClient = nodes.get(buildNodeName); if (nodeAndClient == null) { changed = true; - nodeAndClient = buildNode(i, sharedNodesSeeds[i], defaultSettings); + nodeAndClient = buildNode(i, sharedNodesSeeds[i], null); nodeAndClient.node.start(); logger.info("Start Shared Node [{}] not shared", nodeAndClient.name); }
4c0368c587a32fe1e828793e66e41b017fe41605
orientdb
Fixed issue about out*() functions--
c
https://github.com/orientechnologies/orientdb
diff --git a/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionLabel.java b/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionLabel.java index 183ec25efe2..046cb49742f 100644 --- a/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionLabel.java +++ b/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionLabel.java @@ -44,13 +44,13 @@ public Object execute(final OIdentifiable iCurrentRecord, final Object iCurrentR OCommandContext iContext) { final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); - if (iCurrentRecord == null) { + if (iParameters != null && iParameters.length > 0 && iParameters[0] != null) { return OSQLEngine.foreachRecord(new OCallable<Object, OIdentifiable>() { @Override public Object call(final OIdentifiable iArgument) { return getLabel(graph, iArgument); } - }, iCurrentRecord, iContext); + }, iParameters[0], iContext); } else return getLabel(graph, iCurrentRecord); } diff --git a/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionMove.java b/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionMove.java index a1f3ee7452c..c900c4f6077 100644 --- a/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionMove.java +++ b/graphdb/src/main/java/com/orientechnologies/orient/graph/sql/functions/OSQLFunctionMove.java @@ -69,13 +69,13 @@ public Object call(final Object iArgument) { else labels = null; - if (iCurrentResult != null) + if (iParameters != null && iParameters.length > 0 && iParameters[0] != null) return OSQLEngine.foreachRecord(new OCallable<Object, OIdentifiable>() { @Override public Object call(final OIdentifiable iArgument) { return move(graph, iArgument, labels); } - }, iCurrentRecord, iContext); + }, iParameters[0], iContext); else return move(graph, iCurrentRecord.getRecord(), labels); }
406bbcc65dbfe7f43f20f9ed86fa4f09535f331d
drools
BZ-1006481 - UI support for 'extends' rule keyword- broken--
c
https://github.com/kiegroup/drools
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java index 4421e9d5b2a..c1f16e93153 100644 --- a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java +++ b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java @@ -16,6 +16,7 @@ package org.drools.workbench.models.commons.shared.oracle; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; @@ -32,8 +33,12 @@ public interface ProjectDataModelOracle { //Fact and Field related methods String[] getFactTypes(); + Map<String,Collection<String>> getRuleNamesMap(); + List<String> getRuleNames(); + Collection<String> getRuleNamesForPackage(String packageName); + String getFactNameFromType( final String classType ); boolean isFactTypeRecognized( final String factType ); diff --git a/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java b/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java index dde4f87be37..dbf1abeb0e6 100644 --- a/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java +++ b/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; @@ -59,7 +60,7 @@ public class ProjectDataModelOracleImpl implements ProjectDataModelOracle { protected Map<String, Boolean> projectCollectionTypes = new HashMap<String, Boolean>(); // List of available rule names - private List<String> ruleNames = new ArrayList<String>(); + private Map<String, Collection<String>> ruleNames = new HashMap<String, Collection<String>>(); // List of available package names private List<String> packageNames = new ArrayList<String>(); @@ -775,15 +776,29 @@ public Map<String, Boolean> getProjectCollectionTypes() { return this.projectCollectionTypes; } - public void addRuleNames(List<String> ruleNames) { - this.ruleNames.addAll(ruleNames); + public void addRuleNames(String packageName, Collection<String> ruleNames) { + this.ruleNames.put(packageName, ruleNames); } @Override - public List<String> getRuleNames() { + public Map<String, Collection<String>> getRuleNamesMap() { return ruleNames; } + @Override + public List<String> getRuleNames() { + List<String> allTheRuleNames = new ArrayList<String>(); + for (String packageName : ruleNames.keySet()) { + allTheRuleNames.addAll(ruleNames.get(packageName)); + } + return allTheRuleNames; + } + + @Override + public Collection<String> getRuleNamesForPackage(String packageName) { + return ruleNames.get(packageName); + } + public void addPackageNames(List<String> packageNames) { this.packageNames.addAll(packageNames); }
9bac807cedbcff34e1a144fb475eff267e5ed86d
hadoop
MAPREDUCE-2187. Reporter sends progress during- sort/merge. Contributed by Anupam Seth.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1152964 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/mapreduce/CHANGES.txt b/mapreduce/CHANGES.txt index aee8b0a8cedc4..a95155a931d7b 100644 --- a/mapreduce/CHANGES.txt +++ b/mapreduce/CHANGES.txt @@ -40,6 +40,9 @@ Trunk (unreleased changes) IMPROVEMENTS + MAPREDUCE-2187. Reporter sends progress during sort/merge. (Anupam Seth via + acmurthy) + MAPREDUCE-2365. Add counters to track bytes (read,written) via File(Input,Output)Format. (Siddharth Seth via acmurthy) diff --git a/mapreduce/src/java/mapred-default.xml b/mapreduce/src/java/mapred-default.xml index 0b74e9778cb6a..db2d79a35dfd0 100644 --- a/mapreduce/src/java/mapred-default.xml +++ b/mapreduce/src/java/mapred-default.xml @@ -1041,6 +1041,14 @@ </property> <!-- End of TaskTracker DistributedCache configuration --> +<property> + <name>mapreduce.task.combine.progress.records</name> + <value>10000</value> + <description> The number of records to process during combine output collection + before sending a progress notification to the TaskTracker. + </description> +</property> + <property> <name>mapreduce.task.merge.progress.records</name> <value>10000</value> diff --git a/mapreduce/src/java/org/apache/hadoop/mapred/MapTask.java b/mapreduce/src/java/org/apache/hadoop/mapred/MapTask.java index 44ba9a7e68a03..951b45ae70fa4 100644 --- a/mapreduce/src/java/org/apache/hadoop/mapred/MapTask.java +++ b/mapreduce/src/java/org/apache/hadoop/mapred/MapTask.java @@ -946,7 +946,7 @@ public MapOutputBuffer(TaskUmbilicalProtocol umbilical, JobConf job, if (combinerRunner != null) { final Counters.Counter combineOutputCounter = reporter.getCounter(TaskCounter.COMBINE_OUTPUT_RECORDS); - combineCollector= new CombineOutputCollector<K,V>(combineOutputCounter); + combineCollector= new CombineOutputCollector<K,V>(combineOutputCounter, reporter, conf); } else { combineCollector = null; } diff --git a/mapreduce/src/java/org/apache/hadoop/mapred/ReduceTask.java b/mapreduce/src/java/org/apache/hadoop/mapred/ReduceTask.java index 0225982139b8b..6256c662730e8 100644 --- a/mapreduce/src/java/org/apache/hadoop/mapred/ReduceTask.java +++ b/mapreduce/src/java/org/apache/hadoop/mapred/ReduceTask.java @@ -352,7 +352,7 @@ public void run(JobConf job, final TaskUmbilicalProtocol umbilical) Class combinerClass = conf.getCombinerClass(); CombineOutputCollector combineCollector = (null != combinerClass) ? - new CombineOutputCollector(reduceCombineOutputCounter) : null; + new CombineOutputCollector(reduceCombineOutputCounter, reporter, conf) : null; Shuffle shuffle = new Shuffle(getTaskID(), job, FileSystem.getLocal(job), umbilical, diff --git a/mapreduce/src/java/org/apache/hadoop/mapred/Task.java b/mapreduce/src/java/org/apache/hadoop/mapred/Task.java index f5abb3022a56f..8ad56a7d05137 100644 --- a/mapreduce/src/java/org/apache/hadoop/mapred/Task.java +++ b/mapreduce/src/java/org/apache/hadoop/mapred/Task.java @@ -58,6 +58,7 @@ import org.apache.hadoop.mapreduce.TaskCounter; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.MRConfig; +import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.lib.reduce.WrappedReducer; import org.apache.hadoop.mapreduce.task.ReduceContextImpl; import org.apache.hadoop.mapreduce.util.ResourceCalculatorPlugin; @@ -79,6 +80,7 @@ abstract public class Task implements Writable, Configurable { LogFactory.getLog(Task.class); public static String MERGED_OUTPUT_PREFIX = ".merged"; + public static final long DEFAULT_COMBINE_RECORDS_BEFORE_PROGRESS = 10000; /** * Counters to measure the usage of the different file systems. @@ -1176,16 +1178,26 @@ public static class CombineOutputCollector<K extends Object, V extends Object> implements OutputCollector<K, V> { private Writer<K, V> writer; private Counters.Counter outCounter; - public CombineOutputCollector(Counters.Counter outCounter) { + private Progressable progressable; + private long progressBar; + + public CombineOutputCollector(Counters.Counter outCounter, Progressable progressable, Configuration conf) { this.outCounter = outCounter; + this.progressable=progressable; + progressBar = conf.getLong(MRJobConfig.COMBINE_RECORDS_BEFORE_PROGRESS, DEFAULT_COMBINE_RECORDS_BEFORE_PROGRESS); } + public synchronized void setWriter(Writer<K, V> writer) { this.writer = writer; } + public synchronized void collect(K key, V value) throws IOException { outCounter.increment(1); writer.append(key, value); + if ((outCounter.getValue() % progressBar) == 0) { + progressable.progress(); + } } } diff --git a/mapreduce/src/java/org/apache/hadoop/mapreduce/MRJobConfig.java b/mapreduce/src/java/org/apache/hadoop/mapreduce/MRJobConfig.java index bcaeaf147af0e..0054646caf185 100644 --- a/mapreduce/src/java/org/apache/hadoop/mapreduce/MRJobConfig.java +++ b/mapreduce/src/java/org/apache/hadoop/mapreduce/MRJobConfig.java @@ -260,6 +260,8 @@ public interface MRJobConfig { public static final String REDUCE_MEMTOMEM_ENABLED = "mapreduce.reduce.merge.memtomem.enabled"; + public static final String COMBINE_RECORDS_BEFORE_PROGRESS = "mapreduce.task.combine.progress.records"; + public static final String JOB_NAMENODES = "mapreduce.job.hdfs-servers"; public static final String JOB_JOBTRACKER_ID = "mapreduce.job.kerberos.jtprinicipal";
146eb941d0babe160c0ee0e5f09600ce3d2f9145
kotlin
Config refactoring.--
p
https://github.com/JetBrains/kotlin
diff --git a/js/js.tests/test/org/jetbrains/k2js/test/TestConfig.java b/js/js.tests/test/org/jetbrains/k2js/config/TestConfig.java similarity index 74% rename from js/js.tests/test/org/jetbrains/k2js/test/TestConfig.java rename to js/js.tests/test/org/jetbrains/k2js/config/TestConfig.java index 189e4b8b049e8..c918ad287895b 100644 --- a/js/js.tests/test/org/jetbrains/k2js/test/TestConfig.java +++ b/js/js.tests/test/org/jetbrains/k2js/config/TestConfig.java @@ -14,14 +14,13 @@ * limitations under the License. */ -package org.jetbrains.k2js.test; +package org.jetbrains.k2js.config; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.k2js.config.Config; import org.jetbrains.k2js.utils.JetFileUtils; import java.io.FileInputStream; @@ -29,7 +28,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -38,38 +36,12 @@ //TODO: review/refactor public final class TestConfig extends Config { - @NotNull - private static final List<String> LIB_FILE_NAMES = Arrays.asList( - "/core/annotations.kt", - "/jquery/common.kt", - "/jquery/ui.kt", - "/core/javautil.kt", - "/core/javalang.kt", - "/core/core.kt", - "/core/math.kt", - "/core/json.kt", - "/raphael/raphael.kt", - "/html5/canvas.kt", - "/html5/files.kt", - "/html5/image.kt" - ); - - private static final String LIBRARIES_LOCATION = "js.libraries/src"; @Nullable private /*var*/ List<JetFile> jsLibFiles = null; - @NotNull - private final Project project; - public TestConfig(@NotNull Project project) { - this.project = project; - } - - @NotNull - @Override - public Project getProject() { - return project; + super(project); } @NotNull diff --git a/js/js.translator/src/org/jetbrains/k2js/config/Config.java b/js/js.translator/src/org/jetbrains/k2js/config/Config.java index 9bef13e122061..269ac50498f7b 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/Config.java +++ b/js/js.translator/src/org/jetbrains/k2js/config/Config.java @@ -20,6 +20,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.psi.JetFile; +import java.util.Arrays; import java.util.List; /** @@ -30,9 +31,35 @@ public abstract class Config { @NotNull - public abstract Project getProject(); + protected static final List<String> LIB_FILE_NAMES = Arrays.asList( + "/core/annotations.kt", + "/jquery/common.kt", + "/jquery/ui.kt", + "/core/javautil.kt", + "/core/javalang.kt", + "/core/core.kt", + "/core/math.kt", + "/core/json.kt", + "/raphael/raphael.kt", + "/html5/canvas.kt", + "/html5/files.kt", + "/html5/image.kt" + ); + + protected static final String LIBRARIES_LOCATION = "js.libraries/src"; @NotNull - public abstract List<JetFile> getLibFiles(); + private final Project project; + public Config(@NotNull Project project) { + this.project = project; + } + + @NotNull + public Project getProject() { + return project; + } + + @NotNull + public abstract List<JetFile> getLibFiles(); } diff --git a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java b/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java index b421601c2740e..6788dec178c73 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java +++ b/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java @@ -28,17 +28,8 @@ */ public final class IDEAConfig extends Config { - @NotNull - private final Project project; - public IDEAConfig(@NotNull Project project) { - this.project = project; - } - - @NotNull - @Override - public Project getProject() { - return project; + super(project); } @NotNull
4cc5dbc23d2cf51d2b80bb0712149c00bab82ef8
aeshell$aesh
basic history search support
a
https://github.com/aeshell/aesh
diff --git a/src/main/java/org/jboss/jreadline/console/Console.java b/src/main/java/org/jboss/jreadline/console/Console.java index 7bba53682..673a9e1fb 100644 --- a/src/main/java/org/jboss/jreadline/console/Console.java +++ b/src/main/java/org/jboss/jreadline/console/Console.java @@ -108,11 +108,12 @@ public String read(String prompt) throws IOException { buffer.reset(prompt); outStream.write(buffer.getPrompt()); flushOut(); + StringBuilder searchTerm = null; + StringBuilder result = null; while(true) { int c = terminal.read(inStream); - //int c = reader.read(); //System.out.println("got int:"+c); if (c == -1) { return null; @@ -120,94 +121,95 @@ public String read(String prompt) throws IOException { Operation operation = editMode.parseInput(c); Action action = operation.getAction(); - //System.out.println("new action:"+action); if (action == Action.EDIT) { - /* - if (c != 0) { // ignore null chars - ActionListener tAction = triggeredActions.get(c); - if (tAction != null) { - tAction.actionPerformed(null); - } - else { - if(!undoManager.isEmpty()) { - addActionToUndoStack(); - } - putChar(c, true); - } - } - */ writeChar(c); } // For search movement is used a bit differently. // It only triggers what kind of search action thats performed else if(action == Action.SEARCH) { - /* + switch (operation.getMovement()) { //init a previous search case PREV: - searchTerm = new StringBuffer(buf.getBuffer()); + searchTerm = new StringBuilder(buffer.getLine()); if (searchTerm.length() > 0) { - searchIndex = history.searchBackwards(searchTerm.toString()); - if (searchIndex == -1) { - beep(); - } - printSearchStatus(searchTerm.toString(), - searchIndex > -1 ? history.getHistory(searchIndex) : ""); - } else { - searchIndex = -1; - printSearchStatus("", ""); + result = history.searchPrevious(searchTerm.toString()); } break; case PREV_WORD: - if (searchIndex == -1) { - searchIndex = history.searchBackwards(searchTerm.toString()); - } else { - searchIndex = history.searchBackwards(searchTerm.toString(), searchIndex); - } + result = history.searchPrevious(searchTerm.toString()); + break; case PREV_BIG_WORD: + if (searchTerm.length() > 0) { searchTerm.deleteCharAt(searchTerm.length() - 1); - searchIndex = history.searchBackwards(searchTerm.toString()); } + break; // new search input, append to search case ALL: searchTerm.appendCodePoint(c); - searchIndex = history.searchBackwards(searchTerm.toString()); + //check if the new searchTerm will find anything + StringBuilder tmpResult = history.searchPrevious(searchTerm.toString()); + // + if(tmpResult == null) { + searchTerm.deleteCharAt(searchTerm.length()-1); + } + else { + result = new StringBuilder(tmpResult.toString()); + } + //result = history.searchPrevious(searchTerm.toString()); break; // pressed enter, ending the search case END: - // Set buffer and cursor position to the found string. - if (searchIndex != -1) { - history.setCurrentIndex(searchIndex); - setBuffer(history.current()); - buf.setCursor(history.current().indexOf(searchTerm.toString())); + // Set buffer to the found string. + if (result != null) { + buffer.setLine(new StringBuilder(result)); + result = null; + redrawLine(); + printNewline(); + return buffer.getLine().toString(); + } + redrawLine(); + break; + + case NEXT_BIG_WORD: + if(result != null) { + buffer.setLine(new StringBuilder(result)); + result = null; } + //redrawLine(); break; } // if we're still in search mode, print the search status if (editMode.getCurrentAction() == Action.SEARCH) { if (searchTerm.length() == 0) { - printSearchStatus("", ""); + if(result != null) + printSearch("", result.toString()); + else + printSearch("", ""); } else { - if (searchIndex == -1) { - beep(); + if (result == null) { + //beep(); + //System.out.println("result"); } else { - printSearchStatus(searchTerm.toString(), history.getHistory(searchIndex)); + printSearch(searchTerm.toString(), result.toString()); } } } // otherwise, restore the line else { - restoreLine(); + redrawLine(); + outStream.write(Buffer.printAnsi((buffer.getPrompt().length()+1)+"G")); + flushOut(); } - */ + } @@ -415,21 +417,36 @@ private void redrawLineFromCursor() throws IOException { } private void redrawLine() throws IOException { + drawLine(buffer.getPrompt()+buffer.getLine().toString()); + } + private void drawLine(String line) throws IOException { outStream.write(Buffer.printAnsi("s")); //save cursor //move cursor to 0. - need to do this to clear the entire line outStream.write(Buffer.printAnsi("0G")); outStream.write(Buffer.printAnsi("2K")); // clear line flushOut(); - outStream.write(buffer.getPrompt()); - outStream.write(buffer.getLineFrom(0)); + outStream.write(line); // move cursor to saved pos outStream.write(Buffer.printAnsi("u")); flushOut(); } + private void printSearch(String searchTerm, String result) throws IOException { + //cursor should be placed at the index of searchTerm + int cursor = result.indexOf(searchTerm); + + StringBuilder out = new StringBuilder("(reverse-i-search) `"); + out.append(searchTerm).append("': "); + cursor += out.length(); + out.append(result); //.append("\u001b[K"); + drawLine(out.toString()); + outStream.write(Buffer.printAnsi((cursor+1) + "G")); + flushOut(); + } + /** * Insert a newline * diff --git a/src/main/java/org/jboss/jreadline/history/History.java b/src/main/java/org/jboss/jreadline/history/History.java index 5821794f5..b3eaf9bc7 100644 --- a/src/main/java/org/jboss/jreadline/history/History.java +++ b/src/main/java/org/jboss/jreadline/history/History.java @@ -34,6 +34,10 @@ public interface History { StringBuilder getPreviousFetch(); + StringBuilder searchNext(String search); + + StringBuilder searchPrevious(String search); + void setCurrent(StringBuilder line); StringBuilder getCurrent(); diff --git a/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java b/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java index a621b1edd..5b67831c4 100644 --- a/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java +++ b/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java @@ -28,12 +28,14 @@ public class InMemoryHistory implements History { private List<StringBuilder> historyList = new LinkedList<StringBuilder>(); private int lastFetchedId = -1; + private int lastSearchedId = 0; private StringBuilder current; @Override public void push(StringBuilder entry) { historyList.add(0, entry); lastFetchedId = -1; + lastSearchedId = 0; } @Override @@ -70,6 +72,29 @@ public StringBuilder getPreviousFetch() { } } + @Override + public StringBuilder searchNext(String search) { + for(; lastSearchedId < size(); lastSearchedId++) { + if(historyList.get(lastSearchedId).indexOf(search) != -1) + return get(lastSearchedId); + + } + + return null; + } + + @Override + public StringBuilder searchPrevious(String search) { + if(lastSearchedId < 1) + lastSearchedId = size()-1; + + for(; lastSearchedId >= 0; lastSearchedId-- ) { + if(historyList.get(lastSearchedId).indexOf(search) != -1) + return get(lastSearchedId); + } + return null; + } + @Override public void setCurrent(StringBuilder line) { this.current = line;
87a3c302325e42b2ec6c08b893e3aff50e0f4bd0
restlet-framework-java
Fixed NPE in the dataservices extension due to bad- parsing of referential constraints.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java b/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java index 67e89be7b7..20d190d4e8 100755 --- a/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java +++ b/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java @@ -143,13 +143,7 @@ public Set<EntityType> getImportedEntityTypes() { Set<EntityType> result = new TreeSet<EntityType>(); for (NavigationProperty property : getAssociations()) { - try { - System.err.println(property.getToRole().getType()); - result.add(property.getToRole().getType()); - } catch (Throwable e) { - e.printStackTrace(); - System.out.println(e.getMessage()); - } + result.add(property.getToRole().getType()); } return result; }
0bf9e191fdd374ddc4484ffdf0294e2fd9b79877
tapiji
Separates core and ui concerns for the java extension plug-in.
p
https://github.com/tapiji/tapiji
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 index d348d874..98da3a4e 100644 --- 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 @@ -81,7 +81,7 @@ &lt;pre&gt; &lt;extension point=&quot;org.eclipselabs.tapiji.tools.core.builderExtension&quot;&gt; &lt;i18nResourceAuditor - class=&quot;auditor.JavaResourceAuditor&quot;&gt; + class=&quot;ui.JavaResourceAuditor&quot;&gt; &lt;/i18nResourceAuditor&gt; &lt;/extension&gt; &lt;/pre&gt; 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 index 86f633db..a3e6a516 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF @@ -5,12 +5,12 @@ 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.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.eclipse.babel.tapiji.tools.core;bundle-version="0.0.2", - org.eclipse.babel.tapiji.tools.core.ui;bundle-version="0.0.2" + 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;bundle-version="3.7.3" Import-Package: org.eclipse.babel.tapiji.translator.rbe.babel.bundle, org.eclipse.babel.tapiji.translator.rbe.ui.wizards, org.eclipse.core.filebuffers, diff --git a/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml index 3b3bdf61..4e8e6b97 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml +++ b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml @@ -4,7 +4,7 @@ <extension point="org.eclipse.babel.tapiji.tools.core.builderExtension"> <i18nResourceAuditor - class="org.eclipse.babel.tapiji.tools.java.auditor.JavaResourceAuditor"> + class="org.eclipse.babel.tapiji.tools.java.ui.JavaResourceAuditor"> </i18nResourceAuditor> </extension> <extension diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java deleted file mode 100644 index 6e4336f0..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java +++ /dev/null @@ -1,162 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.auditor; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import org.eclipse.babel.tapiji.tools.core.builder.quickfix.CreateResourceBundle; -import org.eclipse.babel.tapiji.tools.core.builder.quickfix.IncludeResource; -import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor; -import org.eclipse.babel.tapiji.tools.core.extensions.ILocation; -import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants; -import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager; -import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry; -import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation; -import org.eclipse.babel.tapiji.tools.java.quickfix.ExcludeResourceFromInternationalization; -import org.eclipse.babel.tapiji.tools.java.quickfix.ExportToResourceBundleResolution; -import org.eclipse.babel.tapiji.tools.java.quickfix.IgnoreStringFromInternationalization; -import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleDefReference; -import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleReference; -import org.eclipse.babel.tapiji.tools.java.util.ASTutils; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.ui.IMarkerResolution; - - -public class JavaResourceAuditor extends I18nResourceAuditor { - - protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>(); - protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>(); - protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>(); - - @Override - public String[] getFileEndings() { - return new String[] { "java" }; - } - - @Override - public void audit(IResource resource) { - - ResourceAuditVisitor csav = new ResourceAuditVisitor(resource - .getProject().getFile(resource.getProjectRelativePath()), - resource.getProject().getName()); - - // get a reference to the shared AST of the loaded CompilationUnit - CompilationUnit cu = ASTutils.getCompilationUnit(resource); - if (cu == null) { - System.out.println("Cannot audit resource: " - + resource.getFullPath()); - return; - } - cu.accept(csav); - - // Report all constant string literals - constantLiterals = csav.getConstantStringLiterals(); - - // Report all broken Resource-Bundle references - brokenResourceReferences = csav.getBrokenResourceReferences(); - - // Report all broken definitions to Resource-Bundle references - brokenBundleReferences = csav.getBrokenRBReferences(); - } - - @Override - public List<ILocation> getConstantStringLiterals() { - return new ArrayList<ILocation>(constantLiterals); - } - - @Override - public List<ILocation> getBrokenResourceReferences() { - return new ArrayList<ILocation>(brokenResourceReferences); - } - - @Override - public List<ILocation> getBrokenBundleReferences() { - return new ArrayList<ILocation>(brokenBundleReferences); - } - - @Override - public String getContextId() { - return "java"; - } - - @Override - public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { - List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); - int cause = marker.getAttribute("cause", -1); - - switch (marker.getAttribute("cause", -1)) { - case IMarkerConstants.CAUSE_CONSTANT_LITERAL: - resolutions.add(new IgnoreStringFromInternationalization()); - resolutions.add(new ExcludeResourceFromInternationalization()); - resolutions.add(new ExportToResourceBundleResolution()); - break; - case IMarkerConstants.CAUSE_BROKEN_REFERENCE: - String dataName = marker.getAttribute("bundleName", ""); - int dataStart = marker.getAttribute("bundleStart", 0); - int dataEnd = marker.getAttribute("bundleEnd", 0); - - IProject project = marker.getResource().getProject(); - ResourceBundleManager manager = ResourceBundleManager - .getManager(project); - - if (manager.getResourceBundle(dataName) != null) { - String key = marker.getAttribute("key", ""); - - resolutions.add(new CreateResourceBundleEntry(key, - dataName)); - resolutions.add(new ReplaceResourceBundleReference(key, - dataName)); - resolutions.add(new ReplaceResourceBundleDefReference(dataName, - dataStart, dataEnd)); - } else { - String bname = dataName; - - Set<IResource> bundleResources = ResourceBundleManager - .getManager(marker.getResource().getProject()) - .getAllResourceBundleResources(bname); - - if (bundleResources != null && bundleResources.size() > 0) - resolutions - .add(new IncludeResource(bname, bundleResources)); - else - resolutions.add(new CreateResourceBundle(bname, marker - .getResource(), dataStart, dataEnd)); - resolutions.add(new ReplaceResourceBundleDefReference(bname, - dataStart, dataEnd)); - } - - break; - case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE: - String bname = marker.getAttribute("key", ""); - - Set<IResource> bundleResources = ResourceBundleManager.getManager( - marker.getResource().getProject()) - .getAllResourceBundleResources(bname); - - if (bundleResources != null && bundleResources.size() > 0) - resolutions.add(new IncludeResource(bname, bundleResources)); - else - resolutions.add(new CreateResourceBundle(marker.getAttribute( - "key", ""), marker.getResource(), marker.getAttribute( - IMarker.CHAR_START, 0), marker.getAttribute( - IMarker.CHAR_END, 0))); - resolutions.add(new ReplaceResourceBundleDefReference(marker - .getAttribute("key", ""), marker.getAttribute( - IMarker.CHAR_START, 0), marker.getAttribute( - IMarker.CHAR_END, 0))); - } - - return resolutions; - } - -} diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java index 367a27db..6efa3fff 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java @@ -18,7 +18,8 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.IProgressService; -public class ExcludeResourceFromInternationalization implements IMarkerResolution2 { +public class ExcludeResourceFromInternationalization implements + IMarkerResolution2 { @Override public String getLabel() { @@ -28,24 +29,28 @@ public String getLabel() { @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()); + 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) {} + } catch (Exception e) { + } } @Override diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java index d2dc9a36..716fb5bb 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java @@ -24,11 +24,11 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IMarkerResolution2; - public class ExportToResourceBundleResolution implements IMarkerResolution2 { - public ExportToResourceBundleResolution () {} - + public ExportToResourceBundleResolution() { + } + @Override public String getDescription() { return "Export constant string literal to a resource bundle."; @@ -50,36 +50,35 @@ public void run(IMarker marker) { int startPos = marker.getAttribute(IMarker.CHAR_START, 0); int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; IResource resource = marker.getResource(); - - ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); - IPath path = resource.getRawLocation(); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); try { - bufferManager.connect(path, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); - + bufferManager.connect(path, LocationKind.NORMALIZE, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( + path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); - + 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.setPreselectedBundle((startPos + 1 < document.getLength() && endPos > 1) ? document + .get(startPos + 1, endPos - 2) : ""); config.setPreselectedLocale(""); config.setProjectName(resource.getProject().getName()); - + dialog.setDialogConfiguration(config); - + if (dialog.open() != InputDialog.OK) return; - - ASTutils.insertNewBundleRef(document, - resource, - startPos, - endPos, - dialog.getSelectedResourceBundle(), - dialog.getSelectedKey()); - + + ASTutils.insertNewBundleRef(document, resource, startPos, endPos, + dialog.getSelectedResourceBundle(), dialog.getSelectedKey()); + textFileBuffer.commit(null, false); } catch (Exception e) { e.printStackTrace(); @@ -88,9 +87,8 @@ public void run(IMarker marker) { 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/quickfix/IgnoreStringFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java index 3343d261..ac1efba5 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java @@ -23,7 +23,6 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.ui.IMarkerResolution2; - public class IgnoreStringFromInternationalization implements IMarkerResolution2 { @Override @@ -34,30 +33,31 @@ public String getLabel() { @Override public void run(IMarker marker) { IResource resource = marker.getResource(); - + CompilationUnit cu = ASTutils.getCompilationUnit(resource); - - ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - - + + 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(); - + 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); + + ASTutils.createReplaceNonInternationalisationComment(cu, document, + position); textFileBuffer.commit(null, false); - + } catch (JavaModelException e) { Logger.logError(e); } catch (CoreException e) { Logger.logError(e); } - - + } @Override diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java index 606ac47e..c01fbe58 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java @@ -22,13 +22,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; @@ -37,9 +36,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 @@ -56,28 +54,31 @@ 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, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); - - ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(), - resource.getProject()); - + 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; - + key = iSep != -1 ? key.substring(iSep + 1) : key; + 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, 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/quickfix/ReplaceResourceBundleReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java index ca351e26..d592f909 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java @@ -24,12 +24,11 @@ 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; @@ -38,8 +37,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 @@ -57,28 +56,30 @@ public void run(IMarker marker) { int startPos = marker.getAttribute(IMarker.CHAR_START, 0); int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; IResource resource = marker.getResource(); - - ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); - IPath path = resource.getRawLocation(); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); try { - bufferManager.connect(path, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); - + bufferManager.connect(path, LocationKind.NORMALIZE, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( + path, LocationKind.NORMALIZE); + 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; - + String key = dialog.getSelectedResource(); Locale locale = dialog.getSelectedLocale(); - + document.replace(startPos, endPos, "\"" + key + "\""); - + textFileBuffer.commit(null, false); } catch (Exception e) { e.printStackTrace(); @@ -87,7 +88,7 @@ public void run(IMarker marker) { 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/ConstantStringHover.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java index 0cfbe071..899bac40 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java @@ -8,8 +8,8 @@ package org.eclipse.babel.tapiji.tools.java.ui; import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager; -import org.eclipse.babel.tapiji.tools.java.auditor.ResourceAuditVisitor; import org.eclipse.babel.tapiji.tools.java.util.ASTutils; +import org.eclipse.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; @@ -18,7 +18,6 @@ import org.eclipse.jface.text.ITextViewer; import org.eclipse.ui.IEditorPart; - public class ConstantStringHover implements IJavaEditorTextHover { IEditorPart editor = null; @@ -30,26 +29,27 @@ public void setEditor(IEditorPart editor) { this.editor = editor; initConstantStringAuditor(); } - - protected void 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()); + .getEditorInput()); - if (typeRoot == null) + if (typeRoot == null) { return; - + } + CompilationUnit cu = ASTutils.getCompilationUnit(typeRoot); - if (cu == null) + if (cu == null) { return; + } + + manager = ResourceBundleManager.getManager(cu.getJavaElement() + .getResource().getProject()); - manager = ResourceBundleManager.getManager( - cu.getJavaElement().getResource().getProject() - ); - // determine the element at the position of the cursur csf = new ResourceAuditVisitor(null, manager.getProject().getName()); cu.accept(csf); @@ -58,32 +58,37 @@ protected void initConstantStringAuditor () { @Override public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { initConstantStringAuditor(); - if (hoverRegion == null) + if (hoverRegion == null) { return null; + } // get region for string literals hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset()); - - if (hoverRegion == null) + + 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("")) + if (hoverText == null || hoverText.equals("")) { return null; - else + } else { return hoverText; + } } @Override public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - if (editor == null) + if (editor == null) { return null; + } - // Retrieve the property key at this position. Otherwise, null is returned. - return csf.getKeyAt(Long.valueOf(offset)); + // 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..3efe5dd6 --- /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.builder.quickfix.CreateResourceBundle; +import org.eclipse.babel.tapiji.tools.core.builder.quickfix.IncludeResource; +import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor; +import org.eclipse.babel.tapiji.tools.core.extensions.ILocation; +import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants; +import org.eclipse.babel.tapiji.tools.core.model.SLLocation; +import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry; +import org.eclipse.babel.tapiji.tools.java.quickfix.ExcludeResourceFromInternationalization; +import org.eclipse.babel.tapiji.tools.java.quickfix.ExportToResourceBundleResolution; +import org.eclipse.babel.tapiji.tools.java.quickfix.IgnoreStringFromInternationalization; +import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleDefReference; +import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleReference; +import org.eclipse.babel.tapiji.tools.java.util.ASTutils; +import org.eclipse.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 = ASTutils.getCompilationUnit(resource); + if (cu == null) { + System.out.println("Cannot audit resource: " + + resource.getFullPath()); + return; + } + cu.accept(csav); + + // Report all constant string literals + constantLiterals = csav.getConstantStringLiterals(); + + // Report all broken Resource-Bundle references + brokenResourceReferences = csav.getBrokenResourceReferences(); + + // Report all broken definitions to Resource-Bundle references + brokenBundleReferences = csav.getBrokenRBReferences(); + } + + @Override + public List<ILocation> getConstantStringLiterals() { + return new ArrayList<ILocation>(constantLiterals); + } + + @Override + public List<ILocation> getBrokenResourceReferences() { + return new ArrayList<ILocation>(brokenResourceReferences); + } + + @Override + public List<ILocation> getBrokenBundleReferences() { + return new ArrayList<ILocation>(brokenBundleReferences); + } + + @Override + public String getContextId() { + return "java"; + } + + @Override + public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { + List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); + + 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 index 571b1060..5cee9c16 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java @@ -14,13 +14,13 @@ import org.eclipse.babel.tapiji.tools.core.Logger; import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature; import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager; -import org.eclipse.babel.tapiji.tools.java.auditor.ResourceAuditVisitor; import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.CreateResourceBundleProposal; import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.InsertResourceBundleReferenceProposal; import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.MessageCompletionProposal; import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NewResourceBundleEntryProposal; import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NoActionProposal; import org.eclipse.babel.tapiji.tools.java.util.ASTutils; +import org.eclipse.babel.tapiji.tools.java.visitor.ResourceAuditVisitor; import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IProgressMonitor; @@ -31,213 +31,225 @@ 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 { + IJavaCompletionProposalComputer { - private ResourceAuditVisitor csav; - private IResource resource; - private CompilationUnit cu; - private ResourceBundleManager manager; + private ResourceAuditVisitor csav; + private IResource resource; + private CompilationUnit cu; + private ResourceBundleManager manager; - public MessageCompletionProposalComputer() { + public MessageCompletionProposalComputer() { - } - - @Override - public List<ICompletionProposal> computeCompletionProposals( - ContentAssistInvocationContext context, IProgressMonitor monitor) { - - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + } - if (!InternationalizationNature - .hasNature(((JavaContentAssistInvocationContext) context) - .getCompilationUnit().getResource().getProject())) - return completions; + @Override + public List<ICompletionProposal> computeCompletionProposals( + ContentAssistInvocationContext context, IProgressMonitor monitor) { - try { - JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context); - CompletionContext coreContext = javaContext.getCoreContext(); + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - int tokenStart = coreContext.getTokenStart(); - int tokenEnd = coreContext.getTokenEnd(); - int tokenOffset = coreContext.getOffset(); - boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL; + if (!InternationalizationNature + .hasNature(((JavaContentAssistInvocationContext) context) + .getCompilationUnit().getResource().getProject())) { + return completions; + } - if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME - && (tokenEnd + 1) - tokenStart > 0) + try { + JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context); + CompletionContext coreContext = javaContext.getCoreContext(); + + int tokenStart = coreContext.getTokenStart(); + int tokenEnd = coreContext.getTokenEnd(); + int tokenOffset = coreContext.getOffset(); + boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL; + + if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME + && (tokenEnd + 1) - tokenStart > 0) { + return completions; + } + + if (isStringLiteral) { + tokenStart++; + } + + if (tokenStart < 0) { + tokenStart = tokenOffset; + tokenEnd = tokenOffset; + } + + tokenEnd = Math.max(tokenEnd, tokenStart); + + String fullToken = ""; + + if (tokenStart < tokenEnd) { + fullToken = context.getDocument().get(tokenStart, + tokenEnd - tokenStart); + } + + // Check if the string literal is up to be written within the + // context of a resource-bundle accessor method + + if (cu == null) { + manager = ResourceBundleManager.getManager(javaContext + .getCompilationUnit().getResource().getProject()); + + resource = javaContext.getCompilationUnit().getResource(); + + csav = new ResourceAuditVisitor(null, manager.getProject() + .getName()); + + cu = ASTutils.getCompilationUnit(resource); + + cu.accept(csav); + } + + if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) { + completions.addAll(getResourceBundleCompletionProposals( + tokenStart, tokenEnd, tokenOffset, isStringLiteral, + fullToken, manager, csav, resource)); + } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null + && isStringLiteral) { + completions.addAll(getRBReferenceCompletionProposals( + tokenStart, tokenEnd, fullToken, isStringLiteral, + manager, resource)); + } else { + completions.addAll(getBasicJavaCompletionProposals(tokenStart, + tokenEnd, tokenOffset, fullToken, isStringLiteral, + manager, csav, resource)); + } + if (completions.size() == 1) { + completions.add(new NoActionProposal()); + } + + } catch (Exception e) { + Logger.logError(e); + } return completions; + } - if (isStringLiteral) - tokenStart++; - - if (tokenStart < 0) { - tokenStart = tokenOffset; - tokenEnd = tokenOffset; - } - - tokenEnd = Math.max(tokenEnd, tokenStart); - - String fullToken = ""; - - if (tokenStart < tokenEnd) - fullToken = context.getDocument().get(tokenStart, - tokenEnd - tokenStart); - - // Check if the string literal is up to be written within the - // context of a resource-bundle accessor method - - if (cu == null) { - manager = ResourceBundleManager.getManager(javaContext - .getCompilationUnit().getResource().getProject()); + 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)); + } + } + } - resource = javaContext.getCompilationUnit().getResource(); + if (!hit && fullToken.trim().length() > 0) { + completions.add(new CreateResourceBundleProposal(fullToken, + resource, tokenStart, tokenEnd)); + } - csav = new ResourceAuditVisitor(null, manager.getProject().getName()); + return completions; + } - cu = ASTutils.getCompilationUnit(resource); + 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; + } - cu.accept(csav); - } + 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)); - 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()); + } + return completions; + } - } catch (Exception e) { - Logger.logError(e); + @Override + public String getErrorMessage() { + // TODO Auto-generated method stub + return ""; } - 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)); - } + + @Override + public void sessionEnded() { + cu = null; + csav = null; + resource = null; + manager = null; } - 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)); + @Override + public void sessionStarted() { + } - return completions; - } - - protected List<ICompletionProposal> getResourceBundleCompletionProposals( - int tokenStart, int tokenEnd, int tokenOffset, - boolean isStringLiteral, String fullToken, - ResourceBundleManager manager, ResourceAuditVisitor csav, - IResource resource) { - - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - IRegion region = csav.getKeyAt(new Long(tokenOffset)); - String bundleName = csav.getBundleReference(region); - IMessagesBundleGroup bundleGroup = manager - .getResourceBundle(bundleName); - - if (fullToken.length() > 0) { - boolean hit = false; - // If a part of a String has already been entered - for (String key : bundleGroup.getMessageKeys()) { - if (key.toLowerCase().startsWith(fullToken)) { - if (!key.equals(fullToken)) - completions.add(new MessageCompletionProposal( - tokenStart, tokenEnd - tokenStart, key, false)); - else - hit = true; - } - } - if (!hit) { - completions.add(new NewResourceBundleEntryProposal(resource, - tokenStart, tokenEnd, fullToken, isStringLiteral, true, - manager.getProject().getName(), bundleName)); - - // TODO: reference to existing resource - } - } else { - for (String key : bundleGroup.getMessageKeys()) { - completions.add(new MessageCompletionProposal(tokenStart, - tokenEnd - tokenStart, key, false)); - } - completions.add(new NewResourceBundleEntryProposal(resource, - tokenStart, tokenEnd, fullToken, isStringLiteral, true, - manager.getProject().getName(), bundleName)); + @Override + public List<IContextInformation> computeContextInformation( + ContentAssistInvocationContext arg0, IProgressMonitor arg1) { + // TODO Auto-generated method stub + return null; } - return completions; - } - - @Override - public List computeContextInformation( - ContentAssistInvocationContext context, IProgressMonitor monitor) { - return null; - } - - @Override - public String getErrorMessage() { - // TODO Auto-generated method stub - return ""; - } - - @Override - public void sessionEnded() { - cu = null; - csav = null; - resource = null; - manager = null; - } - - @Override - public void sessionStarted() { - - } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java index e5d169a0..7f39b6b7 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java @@ -36,183 +36,187 @@ public class CreateResourceBundleProposal implements IJavaCompletionProposal { - private IResource resource; - private int start; - private int end; - private String key; - private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard"; - - public CreateResourceBundleProposal(String key, IResource resource, - int start, int end) { - this.key = ResourceUtils.deriveNonExistingRBName(key, - ResourceBundleManager.getManager(resource.getProject())); - this.resource = resource; - this.start = start; - this.end = end; - } - - public String getDescription() { - return "Creates a new Resource-Bundle with the id '" + key + "'"; - } - - public String getLabel() { - return "Create Resource-Bundle '" + key + "'"; - } - - protected void runAction() { - // First see if this is a "new wizard". - IWizardDescriptor descriptor = PlatformUI.getWorkbench() - .getNewWizardRegistry().findWizard(newBunldeWizard); - // If not check if it is an "import wizard". - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() - .findWizard(newBunldeWizard); + 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; } - // Or maybe an export wizard - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() - .findWizard(newBunldeWizard); + + public String getDescription() { + return "Creates a new Resource-Bundle with the id '" + key + "'"; } - 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 = ""; - } - } + 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 { - 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; - } + // Then if we have a wizard, open it. + if (descriptor != null) { + IWizard wizard = descriptor.createWizard(); + + if (!(wizard instanceof IResourceBundleWizard)) { + return; + } + + IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; + String[] keySilbings = key.split("\\."); + String rbName = keySilbings[keySilbings.length - 1]; + String packageName = ""; + + rbw.setBundleId(rbName); + + // Set the default path according to the specified package name + String pathName = ""; + if (keySilbings.length > 1) { + try { + IJavaProject jp = JavaCore + .create(resource.getProject()); + packageName = key.substring(0, key.lastIndexOf(".")); + + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + IPackageFragment pf = fr + .getPackageFragment(packageName); + if (pf.exists()) { + pathName = pf.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } + } + } catch (Exception e) { + pathName = ""; + } + } + + try { + IJavaProject jp = JavaCore.create(resource.getProject()); + if (pathName.trim().equals("")) { + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + if (!fr.isReadOnly()) { + pathName = fr.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } + } + } + } catch (Exception e) { + pathName = ""; + } + + rbw.setDefaultPath(pathName); + + WizardDialog wd = new WizardDialog(Display.getDefault() + .getActiveShell(), wizard); + + wd.setTitle(wizard.getWindowTitle()); + if (wd.open() == WizardDialog.OK) { + (new I18nBuilder()).buildProject(null, + resource.getProject()); + (new I18nBuilder()).buildResource(resource, null); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, LocationKind.NORMALIZE, + null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); + + if (document.get().charAt(start - 1) == '"' + && document.get().charAt(start) != '"') { + start--; + end++; + } + if (document.get().charAt(end + 1) == '"' + && document.get().charAt(end) != '"') { + end++; + } + + document.replace(start, end - start, "\"" + + (packageName.equals("") ? "" : packageName + + ".") + rbName + "\""); + + textFileBuffer.commit(null, false); + } catch (Exception e) { + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + } + } + } } - } - } catch (Exception e) { - pathName = ""; + } catch (CoreException e) { } + } - rbw.setDefaultPath(pathName); - - WizardDialog wd = new WizardDialog(Display.getDefault() - .getActiveShell(), wizard); - - wd.setTitle(wizard.getWindowTitle()); - if (wd.open() == WizardDialog.OK) { - (new I18nBuilder()).buildProject(null, - resource.getProject()); - (new I18nBuilder()).buildResource(resource, null); - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, LocationKind.NORMALIZE, - null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); - - if (document.get().charAt(start - 1) == '"' - && document.get().charAt(start) != '"') { - start--; - end++; - } - if (document.get().charAt(end + 1) == '"' - && document.get().charAt(end) != '"') - end++; - - document.replace(start, end - start, "\"" - + (packageName.equals("") ? "" : packageName - + ".") + rbName + "\""); - - textFileBuffer.commit(null, false); - } catch (Exception e) { - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - } - } + @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; } - } - } catch (CoreException e) { } - } - - @Override - public void apply(IDocument document) { - this.runAction(); - } - - @Override - public String getAdditionalProposalInfo() { - return getDescription(); - } - - @Override - public IContextInformation getContextInformation() { - return null; - } - - @Override - public String getDisplayString() { - return getLabel(); - } - - @Override - public Point getSelection(IDocument document) { - return null; - } - - @Override - public Image getImage() { - return PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); - } - - @Override - public int getRelevance() { - // TODO Auto-generated method stub - if (end - start == 0) - return 99; - else - return 1099; - } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java index 9d1b942a..e6c03ff4 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java @@ -24,7 +24,7 @@ import org.eclipse.ui.PlatformUI; public class InsertResourceBundleReferenceProposal implements - IJavaCompletionProposal { + IJavaCompletionProposal { private int offset = 0; private int length = 0; @@ -33,7 +33,8 @@ public class InsertResourceBundleReferenceProposal implements private String projectName; public InsertResourceBundleReferenceProposal(int offset, int length, - String projectName, IResource resource, Collection<String> availableBundles) { + String projectName, IResource resource, + Collection<String> availableBundles) { this.offset = offset; this.length = length; this.resource = resource; @@ -43,18 +44,19 @@ public InsertResourceBundleReferenceProposal(int offset, int length, @Override public void apply(IDocument document) { ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( - Display.getDefault().getActiveShell()); + Display.getDefault().getActiveShell()); dialog.setProjectName(projectName); - if (dialog.open() != InputDialog.OK) + 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); + offset, length, resourceBundleId, key, locale); } @Override @@ -76,7 +78,7 @@ public String getDisplayString() { @Override public Image getImage() { return PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); } @Override @@ -89,10 +91,11 @@ public Point getSelection(IDocument document) { @Override public int getRelevance() { // TODO Auto-generated method stub - if (this.length == 0) + if (this.length == 0) { return 97; - else + } else { return 1097; + } } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java index 434a22a6..a622e8e3 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java @@ -17,58 +17,58 @@ public class MessageCompletionProposal implements IJavaCompletionProposal { - private int offset = 0; - private int length = 0; - private String content = ""; - private boolean messageAccessor = false; + private int offset = 0; + private int length = 0; + private String content = ""; + private boolean messageAccessor = false; - public MessageCompletionProposal(int offset, int length, String content, - boolean messageAccessor) { - this.offset = offset; - this.length = length; - this.content = content; - this.messageAccessor = messageAccessor; - } + public MessageCompletionProposal(int offset, int length, String content, + boolean messageAccessor) { + this.offset = offset; + this.length = length; + this.content = content; + this.messageAccessor = messageAccessor; + } - @Override - public void apply(IDocument document) { - try { - document.replace(offset, length, content); - } catch (Exception e) { - Logger.logError(e); + @Override + public void apply(IDocument document) { + try { + document.replace(offset, length, content); + } catch (Exception e) { + Logger.logError(e); + } } - } - @Override - public String getAdditionalProposalInfo() { - return "Inserts the resource key '" + this.content + "'"; - } + @Override + public String getAdditionalProposalInfo() { + return "Inserts the resource key '" + this.content + "'"; + } - @Override - public IContextInformation getContextInformation() { - return null; - } + @Override + public IContextInformation getContextInformation() { + return null; + } - @Override - public String getDisplayString() { - return content; - } + @Override + public String getDisplayString() { + return content; + } - @Override - public Image getImage() { - if (messageAccessor) - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE); - } + @Override + public Image getImage() { + if (messageAccessor) + return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); + return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE); + } - @Override - public Point getSelection(IDocument document) { - return new Point(offset + content.length() + 1, 0); - } + @Override + public Point getSelection(IDocument document) { + return new Point(offset + content.length() + 1, 0); + } - @Override - public int getRelevance() { - return 99; - } + @Override + public int getRelevance() { + return 99; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java index cc1fdb07..160b5c78 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 @@ -24,110 +24,109 @@ public class NewResourceBundleEntryProposal implements IJavaCompletionProposal { - private int startPos; - private int endPos; - private String value; - private boolean bundleContext; - private String projectName; - private IResource resource; - private String bundleName; - private String reference; - - public NewResourceBundleEntryProposal(IResource resource, int startPos, - int endPos, String value, boolean isStringLiteral, - boolean bundleContext, String projectName, - String bundleName) { - - this.startPos = startPos; - this.endPos = endPos; - this.value = value; - this.bundleContext = bundleContext; - this.projectName = projectName; - this.resource = resource; - this.bundleName = bundleName; - } - - @Override - public void apply(IDocument document) { - - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); - - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(bundleContext ? value : ""); - config.setPreselectedMessage(value); - config.setPreselectedBundle(bundleName == null ? "" : bundleName); - config.setPreselectedLocale(""); - config.setProjectName(projectName); - - dialog.setDialogConfiguration(config); - - if (dialog.open() != InputDialog.OK) - return; - - String resourceBundleId = dialog.getSelectedResourceBundle(); - String key = dialog.getSelectedKey(); - - try { - if (!bundleContext) - reference = ASTutils.insertNewBundleRef(document, resource, - startPos, endPos - startPos, resourceBundleId, key); - else { - document.replace(startPos, endPos - startPos, key); - reference = key + "\""; - } - ResourceBundleManager.refreshResource(resource); - } catch (Exception e) { - e.printStackTrace(); + private int startPos; + private int endPos; + private String value; + private boolean bundleContext; + private String projectName; + private IResource resource; + private String bundleName; + private String reference; + + public NewResourceBundleEntryProposal(IResource resource, int startPos, + int endPos, String value, boolean isStringLiteral, + boolean bundleContext, String projectName, String bundleName) { + + this.startPos = startPos; + this.endPos = endPos; + this.value = value; + this.bundleContext = bundleContext; + this.projectName = projectName; + this.resource = resource; + this.bundleName = bundleName; + } + + @Override + public void apply(IDocument document) { + + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); + + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(bundleContext ? value : ""); + config.setPreselectedMessage(value); + config.setPreselectedBundle(bundleName == null ? "" : bundleName); + config.setPreselectedLocale(""); + config.setProjectName(projectName); + + dialog.setDialogConfiguration(config); + + if (dialog.open() != InputDialog.OK) + return; + + String resourceBundleId = dialog.getSelectedResourceBundle(); + String key = dialog.getSelectedKey(); + + try { + if (!bundleContext) + reference = ASTutils.insertNewBundleRef(document, resource, + startPos, endPos - startPos, resourceBundleId, key); + else { + document.replace(startPos, endPos - startPos, key); + reference = key + "\""; + } + ResourceBundleManager.refreshResource(resource); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public String getAdditionalProposalInfo() { + if (value != null && value.length() > 0) { + return "Exports the focused string literal into a Java Resource-Bundle. This action results " + + "in a Resource-Bundle reference!"; + } else + return ""; + } + + @Override + public IContextInformation getContextInformation() { + return null; + } + + @Override + public String getDisplayString() { + String displayStr = ""; + if (bundleContext) + displayStr = "Create a new resource-bundle-entry"; + else + displayStr = "Create a new localized string literal"; + + if (value != null && value.length() > 0) + displayStr += " for '" + value + "'"; + + return displayStr; + } + + @Override + public Image getImage() { + return PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); + } + + @Override + public Point getSelection(IDocument document) { + int refLength = reference == null ? 0 : reference.length() - 1; + return new Point(startPos + refLength, 0); + } + + @Override + public int getRelevance() { + if (this.value.trim().length() == 0) + return 96; + else + return 1096; } - } - - @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 index c2bcffc5..f16c4cd6 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java @@ -13,16 +13,16 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; -public class NoActionProposal implements IJavaCompletionProposal { +public class NoActionProposal implements IJavaCompletionProposal { - public NoActionProposal () { + public NoActionProposal() { super(); } - + @Override public void apply(IDocument document) { // TODO Auto-generated method stub - + } @Override diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java index 7774650a..2961808c 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java @@ -13,35 +13,32 @@ public class Sorter extends AbstractProposalSorter { - private boolean loaded = false; - - public Sorter() { - // i18n - loaded = true; - } - - @Override - public void beginSorting(ContentAssistInvocationContext context) { - // TODO Auto-generated method stub - super.beginSorting(context); - } - - @Override - public int compare(ICompletionProposal prop1, ICompletionProposal prop2) { - return getIndex(prop1) - getIndex(prop2); - } - - protected int getIndex(ICompletionProposal prop) { - if (prop instanceof NoActionProposal) - return 1; - else if (prop instanceof MessageCompletionProposal) - return 2; - else if (prop instanceof InsertResourceBundleReferenceProposal) - return 3; - else if (prop instanceof NewResourceBundleEntryProposal) - return 4; - else - return 0; - } + 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/auditor/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java similarity index 88% rename from org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/model/SLLocation.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java index 809b3b9e..3fb44e82 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/model/SLLocation.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java @@ -5,23 +5,22 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.auditor.model; +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; @@ -29,32 +28,46 @@ public SLLocation(IFile file, int startPos, int endPos, String literal) { 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; } - public Serializable getData () { + + @Override + 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.java.ui/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java deleted file mode 100644 index 478a94ed..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java +++ /dev/null @@ -1,1042 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.eclipse.babel.tapiji.tools.core.Logger; -import org.eclipse.babel.tapiji.tools.java.auditor.MethodParameterDescriptor; -import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.ITypeRoot; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTParser; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.IVariableBinding; -import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; -import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; -import org.eclipse.jdt.core.dom.rewrite.ListRewrite; -import org.eclipse.jdt.ui.SharedASTProvider; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.text.edits.TextEdit; - -public class ASTutils { - - private static MethodParameterDescriptor rbDefinition; - private static MethodParameterDescriptor rbAccessor; - - public static MethodParameterDescriptor getRBDefinitionDesc() { - if (rbDefinition == null) { - // Init descriptor for Resource-Bundle-Definition - List<String> definition = new ArrayList<String>(); - definition.add("getBundle"); - rbDefinition = new MethodParameterDescriptor(definition, - "java.util.ResourceBundle", true, 0); - } - - return rbDefinition; - } - - public static MethodParameterDescriptor getRBAccessorDesc() { - if (rbAccessor == null) { - // Init descriptor for Resource-Bundle-Accessors - List<String> accessors = new ArrayList<String>(); - accessors.add("getString"); - accessors.add("getStringArray"); - rbAccessor = new MethodParameterDescriptor(accessors, - "java.util.ResourceBundle", true, 0); - } - - return rbAccessor; - } - - public static CompilationUnit getCompilationUnit(IResource resource) { - IJavaElement je = JavaCore.create(resource, - JavaCore.create(resource.getProject())); - // get the type of the currently loaded resource - ITypeRoot typeRoot = ((ICompilationUnit) je); - - if (typeRoot == null) - return null; - - return getCompilationUnit(typeRoot); - } - - public static CompilationUnit getCompilationUnit(ITypeRoot typeRoot) { - // get a reference to the shared AST of the loaded CompilationUnit - CompilationUnit cu = SharedASTProvider.getAST(typeRoot, - // do not wait for AST creation - SharedASTProvider.WAIT_YES, null); - - return cu; - } - - public static String insertExistingBundleRef(IDocument document, - IResource resource, int offset, int length, - String resourceBundleId, String key, Locale locale) { - String reference = ""; - String newName = null; - - CompilationUnit cu = getCompilationUnit(resource); - - String variableName = ASTutils.resolveRBReferenceVar(document, - resource, offset, resourceBundleId, cu); - if (variableName == null) - newName = ASTutils.getNonExistingRBRefName(resourceBundleId, - document, cu); - - try { - reference = ASTutils.createResourceReference(resourceBundleId, key, - locale, resource, offset, variableName == null ? newName - : variableName, document, cu); - - document.replace(offset, length, reference); - - // create non-internationalisation-comment - createReplaceNonInternationalisationComment(cu, document, offset); - } catch (BadLocationException e) { - e.printStackTrace(); - } - - // TODO retrieve cu in the same way as in createResourceReference - // the current version does not parse method bodies - - if (variableName == null) { - ASTutils.createResourceBundleReference(resource, offset, document, - resourceBundleId, locale, true, newName, cu); - // createReplaceNonInternationalisationComment(cu, document, pos); - } - return reference; - } - - public static String insertNewBundleRef(IDocument document, - IResource resource, int startPos, int endPos, - String resourceBundleId, String key) { - String newName = null; - String reference = ""; - - CompilationUnit cu = getCompilationUnit(resource); - - if (cu == null) - return null; - - String variableName = ASTutils.resolveRBReferenceVar(document, - resource, startPos, resourceBundleId, cu); - if (variableName == null) - newName = ASTutils.getNonExistingRBRefName(resourceBundleId, - document, cu); - - try { - reference = ASTutils.createResourceReference(resourceBundleId, key, - null, resource, startPos, variableName == null ? newName - : variableName, document, cu); - - if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') { - startPos--; - endPos++; - } - - if ((startPos + endPos) < document.getLength() - && document.get().charAt(startPos + endPos) == '\"') - endPos++; - - if ((startPos + endPos) < document.getLength() - && document.get().charAt(startPos + endPos - 1) == ';') - endPos--; - - document.replace(startPos, endPos, reference); - - // create non-internationalisation-comment - createReplaceNonInternationalisationComment(cu, document, startPos); - } catch (BadLocationException e) { - e.printStackTrace(); - } - - if (variableName == null) { - // refresh reference to the shared AST of the loaded CompilationUnit - cu = getCompilationUnit(resource); - - ASTutils.createResourceBundleReference(resource, startPos, - document, resourceBundleId, null, true, newName, cu); - // createReplaceNonInternationalisationComment(cu, document, pos); - } - - return reference; - } - - public static String resolveRBReferenceVar(IDocument document, - IResource resource, int pos, final String bundleId, - CompilationUnit cu) { - String bundleVar; - - PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); - cu.accept(typeFinder); - AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType(); - TypeDeclaration td = typeFinder.getEnclosingType(); - MethodDeclaration meth = typeFinder.getEnclosingMethod(); - - if (atd == null) { - BundleDeclarationFinder bdf = new BundleDeclarationFinder( - bundleId, - td, - meth != null - && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); - td.accept(bdf); - - bundleVar = bdf.getVariableName(); - } else { - BundleDeclarationFinder bdf = new BundleDeclarationFinder( - bundleId, - atd, - meth != null - && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); - atd.accept(bdf); - - bundleVar = bdf.getVariableName(); - } - - // Check also method body - if (meth != null) { - try { - InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder( - bundleId, pos); - typeFinder.getEnclosingMethod().accept(imbdf); - bundleVar = imbdf.getVariableName() != null ? imbdf - .getVariableName() : bundleVar; - } catch (Exception e) { - // ignore - } - } - - return bundleVar; - } - - public static String getNonExistingRBRefName(String bundleId, - IDocument document, CompilationUnit cu) { - String referenceName = null; - int i = 0; - - while (referenceName == null) { - String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1) - + "Ref" + (i == 0 ? "" : i); - actRef = actRef.toLowerCase(); - - VariableFinder vf = new VariableFinder(actRef); - cu.accept(vf); - - if (!vf.isVariableFound()) { - referenceName = actRef; - break; - } - - i++; - } - - return referenceName; - } - - @Deprecated - public static String resolveResourceBundle( - MethodInvocation methodInvocation, - MethodParameterDescriptor rbDefinition, - Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { - String bundleName = null; - - if (methodInvocation.getExpression() instanceof SimpleName) { - SimpleName vName = (SimpleName) methodInvocation.getExpression(); - IVariableBinding vBinding = (IVariableBinding) vName - .resolveBinding(); - VariableDeclarationFragment dec = variableBindingManagers - .get(vBinding); - - if (dec.getInitializer() instanceof MethodInvocation) { - MethodInvocation init = (MethodInvocation) dec.getInitializer(); - - // Check declaring class - boolean isValidClass = false; - ITypeBinding type = init.resolveMethodBinding() - .getDeclaringClass(); - while (type != null) { - if (type.getQualifiedName().equals( - rbDefinition.getDeclaringClass())) { - isValidClass = true; - break; - } else { - if (rbDefinition.isConsiderSuperclass()) - type = type.getSuperclass(); - else - type = null; - } - - } - if (!isValidClass) - return null; - - boolean isValidMethod = false; - for (String mn : rbDefinition.getMethodName()) { - if (init.getName().getFullyQualifiedName().equals(mn)) { - isValidMethod = true; - break; - } - } - if (!isValidMethod) - return null; - - // retrieve bundlename - if (init.arguments().size() < rbDefinition.getPosition() + 1) - return null; - - bundleName = ((StringLiteral) init.arguments().get( - rbDefinition.getPosition())).getLiteralValue(); - } - } - - return bundleName; - } - - public static SLLocation resolveResourceBundleLocation( - MethodInvocation methodInvocation, - MethodParameterDescriptor rbDefinition, - Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { - SLLocation bundleDesc = null; - - if (methodInvocation.getExpression() instanceof SimpleName) { - SimpleName vName = (SimpleName) methodInvocation.getExpression(); - IVariableBinding vBinding = (IVariableBinding) vName - .resolveBinding(); - VariableDeclarationFragment dec = variableBindingManagers - .get(vBinding); - - if (dec.getInitializer() instanceof MethodInvocation) { - MethodInvocation init = (MethodInvocation) dec.getInitializer(); - - // Check declaring class - boolean isValidClass = false; - ITypeBinding type = init.resolveMethodBinding() - .getDeclaringClass(); - while (type != null) { - if (type.getQualifiedName().equals( - rbDefinition.getDeclaringClass())) { - isValidClass = true; - break; - } else { - if (rbDefinition.isConsiderSuperclass()) - type = type.getSuperclass(); - else - type = null; - } - - } - if (!isValidClass) - return null; - - boolean isValidMethod = false; - for (String mn : rbDefinition.getMethodName()) { - if (init.getName().getFullyQualifiedName().equals(mn)) { - isValidMethod = true; - break; - } - } - if (!isValidMethod) - return null; - - // retrieve bundlename - if (init.arguments().size() < rbDefinition.getPosition() + 1) - return null; - - StringLiteral bundleLiteral = ((StringLiteral) init.arguments() - .get(rbDefinition.getPosition())); - bundleDesc = new SLLocation(null, - bundleLiteral.getStartPosition(), - bundleLiteral.getLength() - + bundleLiteral.getStartPosition(), - bundleLiteral.getLiteralValue()); - } - } - - return bundleDesc; - } - - private static boolean isMatchingMethodDescriptor( - MethodInvocation methodInvocation, MethodParameterDescriptor desc) { - boolean result = false; - - if (methodInvocation.resolveMethodBinding() == null) - return false; - - String methodName = methodInvocation.resolveMethodBinding().getName(); - - // Check declaring class - ITypeBinding type = methodInvocation.resolveMethodBinding() - .getDeclaringClass(); - while (type != null) { - if (type.getQualifiedName().equals(desc.getDeclaringClass())) { - result = true; - break; - } else { - if (desc.isConsiderSuperclass()) - type = type.getSuperclass(); - else - type = null; - } - - } - - if (!result) - return false; - - result = !result; - - // Check method name - for (String method : desc.getMethodName()) { - if (method.equals(methodName)) { - result = true; - break; - } - } - - return result; - } - - public static boolean isMatchingMethodParamDesc( - MethodInvocation methodInvocation, String literal, - MethodParameterDescriptor desc) { - boolean result = isMatchingMethodDescriptor(methodInvocation, desc); - - if (!result) - return false; - else - result = false; - - if (methodInvocation.arguments().size() > desc.getPosition()) { - if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) { - StringLiteral sl = (StringLiteral) methodInvocation.arguments() - .get(desc.getPosition()); - if (sl.getLiteralValue().trim().toLowerCase() - .equals(literal.toLowerCase())) - result = true; - } - } - - return result; - } - - public static boolean isMatchingMethodParamDesc( - MethodInvocation methodInvocation, StringLiteral literal, - MethodParameterDescriptor desc) { - int keyParameter = desc.getPosition(); - boolean result = isMatchingMethodDescriptor(methodInvocation, desc); - - if (!result) - return false; - - // Check position within method call - StructuralPropertyDescriptor spd = literal.getLocationInParent(); - if (spd.isChildListProperty()) { - List<ASTNode> arguments = (List<ASTNode>) methodInvocation - .getStructuralProperty(spd); - result = (arguments.size() > keyParameter && arguments - .get(keyParameter) == literal); - } - - return result; - } - - public static ICompilationUnit createCompilationUnit(IResource resource) { - // Instantiate a new AST parser - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setResolveBindings(true); - - ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource - .getProject().getFile(resource.getRawLocation())); - - return cu; - } - - public static CompilationUnit createCompilationUnit(IDocument document) { - // Instantiate a new AST parser - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setResolveBindings(true); - - parser.setSource(document.get().toCharArray()); - return (CompilationUnit) parser.createAST(null); - } - - public static void createImport(IDocument doc, IResource resource, - CompilationUnit cu, AST ast, ASTRewrite rewriter, - String qualifiedClassName) throws CoreException, - BadLocationException { - - ImportFinder impFinder = new ImportFinder(qualifiedClassName); - - cu.accept(impFinder); - - if (!impFinder.isImportFound()) { - // ITextFileBufferManager bufferManager = - // FileBuffers.getTextFileBufferManager(); - // IPath path = resource.getFullPath(); - // - // bufferManager.connect(path, LocationKind.IFILE, null); - // ITextFileBuffer textFileBuffer = - // bufferManager.getTextFileBuffer(doc); - - // TODO create new import - ImportDeclaration id = ast.newImportDeclaration(); - id.setName(ast.newName(qualifiedClassName.split("\\."))); - id.setStatic(false); - - ListRewrite lrw = rewriter.getListRewrite(cu, cu.IMPORTS_PROPERTY); - lrw.insertFirst(id, null); - - // TextEdit te = rewriter.rewriteAST(doc, null); - // te.apply(doc); - // - // if (textFileBuffer != null) - // textFileBuffer.commit(null, false); - // else - // FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()), - // doc.get()); - // bufferManager.disconnect(path, LocationKind.IFILE, null); - } - - } - - // TODO export initializer specification into a methodinvocationdefinition - public static void createResourceBundleReference(IResource resource, - int typePos, IDocument doc, String bundleId, Locale locale, - boolean globalReference, String variableName, CompilationUnit cu) { - - try { - - if (globalReference) { - - // retrieve compilation unit from document - PositionalTypeFinder typeFinder = new PositionalTypeFinder( - typePos); - cu.accept(typeFinder); - ASTNode node = typeFinder.getEnclosingType(); - ASTNode anonymNode = typeFinder.getEnclosingAnonymType(); - if (anonymNode != null) - node = anonymNode; - - MethodDeclaration meth = typeFinder.getEnclosingMethod(); - AST ast = node.getAST(); - - VariableDeclarationFragment vdf = ast - .newVariableDeclarationFragment(); - vdf.setName(ast.newSimpleName(variableName)); - - // set initializer - vdf.setInitializer(createResourceBundleGetter(ast, bundleId, - locale)); - - FieldDeclaration fd = ast.newFieldDeclaration(vdf); - fd.setType(ast.newSimpleType(ast - .newName(new String[] { "ResourceBundle" }))); - - if (meth != null - && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC) - fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC)); - - // rewrite AST - ASTRewrite rewriter = ASTRewrite.create(ast); - ListRewrite lrw = rewriter - .getListRewrite( - node, - node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY - : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY); - lrw.insertAt(fd, /* - * findIndexOfLastField(node.bodyDeclarations()) - * +1 - */ - 0, null); - - // create import if required - createImport(doc, resource, cu, ast, rewriter, - getRBDefinitionDesc().getDeclaringClass()); - - TextEdit te = rewriter.rewriteAST(doc, null); - te.apply(doc); - } else { - - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private static int findIndexOfLastField(List bodyDeclarations) { - for (int i = bodyDeclarations.size() - 1; i >= 0; i--) { - BodyDeclaration each = (BodyDeclaration) bodyDeclarations.get(i); - if (each instanceof FieldDeclaration) - return i; - } - return -1; - } - - protected static MethodInvocation createResourceBundleGetter(AST ast, - String bundleId, Locale locale) { - MethodInvocation mi = ast.newMethodInvocation(); - - mi.setName(ast.newSimpleName("getBundle")); - mi.setExpression(ast.newName(new String[] { "ResourceBundle" })); - - // Add bundle argument - StringLiteral sl = ast.newStringLiteral(); - sl.setLiteralValue(bundleId); - mi.arguments().add(sl); - - // TODO Add Locale argument - - return mi; - } - - public static ASTNode getEnclosingType(CompilationUnit cu, int pos) { - PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); - cu.accept(typeFinder); - return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder - .getEnclosingAnonymType() : typeFinder.getEnclosingType(); - } - - public static ASTNode getEnclosingType(ASTNode cu, int pos) { - PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); - cu.accept(typeFinder); - return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder - .getEnclosingAnonymType() : typeFinder.getEnclosingType(); - } - - protected static MethodInvocation referenceResource(AST ast, - String accessorName, String key, Locale locale) { - MethodParameterDescriptor accessorDesc = getRBAccessorDesc(); - MethodInvocation mi = ast.newMethodInvocation(); - - mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0))); - - // Declare expression - StringLiteral sl = ast.newStringLiteral(); - sl.setLiteralValue(key); - - // TODO define locale expression - if (mi.arguments().size() == accessorDesc.getPosition()) - mi.arguments().add(sl); - - SimpleName name = ast.newSimpleName(accessorName); - mi.setExpression(name); - - return mi; - } - - public static String createResourceReference(String bundleId, String key, - Locale locale, IResource resource, int typePos, - String accessorName, IDocument doc, CompilationUnit cu) { - - PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos); - cu.accept(typeFinder); - AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType(); - TypeDeclaration td = typeFinder.getEnclosingType(); - - // retrieve compilation unit from document - ASTNode node = atd == null ? td : atd; - AST ast = node.getAST(); - - ExpressionStatement expressionStatement = ast - .newExpressionStatement(referenceResource(ast, accessorName, - key, locale)); - - String exp = expressionStatement.toString(); - - // remove semicolon and line break at the end of this expression - // statement - if (exp.endsWith(";\n")) - exp = exp.substring(0, exp.length() - 2); - - return exp; - } - - private static int findNonInternationalisationPosition(CompilationUnit cu, - IDocument doc, int offset) { - LinePreStringsFinder lsfinder = null; - try { - lsfinder = new LinePreStringsFinder(offset, doc); - cu.accept(lsfinder); - } catch (BadLocationException e) { - Logger.logError(e); - } - if (lsfinder == null) - return 1; - - List<StringLiteral> strings = lsfinder.getStrings(); - - return strings.size() + 1; - } - - public static void createReplaceNonInternationalisationComment( - CompilationUnit cu, IDocument doc, int position) { - int i = findNonInternationalisationPosition(cu, doc, position); - - IRegion reg; - try { - reg = doc.getLineInformationOfOffset(position); - doc.replace(reg.getOffset() + reg.getLength(), 0, " //$NON-NLS-" - + i + "$"); - } catch (BadLocationException e) { - Logger.logError(e); - } - } - - private static void createASTNonInternationalisationComment( - CompilationUnit cu, IDocument doc, ASTNode parent, ASTNode fd, - ASTRewrite rewriter, ListRewrite lrw) { - int i = 1; - - // ListRewrite lrw2 = rewriter.getListRewrite(node, - // Block.STATEMENTS_PROPERTY); - ASTNode placeHolder = rewriter.createStringPlaceholder("//$NON-NLS-" - + i + "$", ASTNode.LINE_COMMENT); - lrw.insertAfter(placeHolder, fd, null); - } - - public static boolean existsNonInternationalisationComment( - StringLiteral literal) throws BadLocationException { - CompilationUnit cu = (CompilationUnit) literal.getRoot(); - ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); - - IDocument doc = null; - try { - doc = new Document(icu.getSource()); - } catch (JavaModelException e) { - Logger.logError(e); - } - - // get whole line in which string literal - int lineNo = doc.getLineOfOffset(literal.getStartPosition()); - int lineOffset = doc.getLineOffset(lineNo); - int lineLength = doc.getLineLength(lineNo); - String lineOfString = doc.get(lineOffset, lineLength); - - // search for a line comment in this line - int indexComment = lineOfString.indexOf("//"); - - if (indexComment == -1) - return false; - - String comment = lineOfString.substring(indexComment); - - // remove first "//" of line comment - comment = comment.substring(2).toLowerCase(); - - // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3 - String[] comments = comment.split("//"); - - for (String commentFrag : comments) { - commentFrag = commentFrag.trim(); - - // if comment match format: "$non-nls$" then ignore whole line - if (commentFrag.matches("^\\$non-nls\\$$")) { - return true; - - // if comment match format: "$non-nls-{number}$" then only - // ignore string which is on given position - } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) { - int iString = findNonInternationalisationPosition(cu, doc, - literal.getStartPosition()); - int iComment = new Integer(commentFrag.substring(9, 10)); - if (iString == iComment) - return true; - } - } - return false; - } - - public static StringLiteral getStringAtPos(CompilationUnit cu, int position) { - StringFinder strFinder = new StringFinder(position); - cu.accept(strFinder); - return strFinder.getString(); - } - - static class PositionalTypeFinder extends ASTVisitor { - - private int position; - private TypeDeclaration enclosingType; - private AnonymousClassDeclaration enclosingAnonymType; - private MethodDeclaration enclosingMethod; - - public PositionalTypeFinder(int pos) { - position = pos; - } - - public TypeDeclaration getEnclosingType() { - return enclosingType; - } - - public AnonymousClassDeclaration getEnclosingAnonymType() { - return enclosingAnonymType; - } - - public MethodDeclaration getEnclosingMethod() { - return enclosingMethod; - } - - @Override - public boolean visit(MethodDeclaration node) { - if (position >= node.getStartPosition() - && position <= (node.getStartPosition() + node.getLength())) { - enclosingMethod = node; - return true; - } else - return false; - } - - @Override - public boolean visit(TypeDeclaration node) { - if (position >= node.getStartPosition() - && position <= (node.getStartPosition() + node.getLength())) { - enclosingType = node; - return true; - } else - return false; - } - - @Override - public boolean visit(AnonymousClassDeclaration node) { - if (position >= node.getStartPosition() - && position <= (node.getStartPosition() + node.getLength())) { - enclosingAnonymType = node; - return true; - } else - return false; - } - } - - static class ImportFinder extends ASTVisitor { - - String qName; - boolean importFound = false; - - public ImportFinder(String qName) { - this.qName = qName; - } - - public boolean isImportFound() { - return importFound; - } - - @Override - public boolean visit(ImportDeclaration id) { - if (id.getName().getFullyQualifiedName().equals(qName)) - importFound = true; - - return true; - } - } - - static class VariableFinder extends ASTVisitor { - - boolean found = false; - String variableName; - - public boolean isVariableFound() { - return found; - } - - public VariableFinder(String variableName) { - this.variableName = variableName; - } - - @Override - public boolean visit(VariableDeclarationFragment vdf) { - if (vdf.getName().getFullyQualifiedName().equals(variableName)) { - found = true; - return false; - } - - return true; - } - } - - static class InMethodBundleDeclFinder extends ASTVisitor { - String varName; - String bundleId; - int pos; - - public InMethodBundleDeclFinder(String bundleId, int pos) { - this.bundleId = bundleId; - this.pos = pos; - } - - public String getVariableName() { - return varName; - } - - @Override - public boolean visit(VariableDeclarationFragment fdvd) { - if (fdvd.getStartPosition() > pos) - return false; - - // boolean bStatic = (fdvd.resolveBinding().getModifiers() & - // Modifier.STATIC) == Modifier.STATIC; - // if (!bStatic && isStatic) - // return true; - - String tmpVarName = fdvd.getName().getFullyQualifiedName(); - - if (fdvd.getInitializer() instanceof MethodInvocation) { - MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer(); - if (isMatchingMethodParamDesc(fdi, bundleId, - getRBDefinitionDesc())) - varName = tmpVarName; - } - return true; - } - } - - static class BundleDeclarationFinder extends ASTVisitor { - - String varName; - String bundleId; - ASTNode typeDef; - boolean isStatic; - - public BundleDeclarationFinder(String bundleId, ASTNode td, - boolean isStatic) { - this.bundleId = bundleId; - this.typeDef = td; - this.isStatic = isStatic; - } - - public String getVariableName() { - return varName; - } - - @Override - public boolean visit(MethodDeclaration md) { - return true; - } - - @Override - public boolean visit(FieldDeclaration fd) { - if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef) - return false; - - boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC; - if (!bStatic && isStatic) - return true; - - if (fd.getType() instanceof SimpleType) { - SimpleType fdType = (SimpleType) fd.getType(); - String typeName = fdType.getName().getFullyQualifiedName(); - String referenceName = getRBDefinitionDesc() - .getDeclaringClass(); - if (typeName.equals(referenceName) - || (referenceName.lastIndexOf(".") >= 0 && typeName - .equals(referenceName.substring(referenceName - .lastIndexOf(".") + 1)))) { - // Check VariableDeclarationFragment - if (fd.fragments().size() == 1) { - if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { - VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd - .fragments().get(0); - String tmpVarName = fdvd.getName() - .getFullyQualifiedName(); - - if (fdvd.getInitializer() instanceof MethodInvocation) { - MethodInvocation fdi = (MethodInvocation) fdvd - .getInitializer(); - if (isMatchingMethodParamDesc(fdi, bundleId, - getRBDefinitionDesc())) - varName = tmpVarName; - } - } - } - } - } - return false; - } - - } - - static class LinePreStringsFinder extends ASTVisitor { - private int position; - private int line; - private List<StringLiteral> strings; - private IDocument document; - - public LinePreStringsFinder(int position, IDocument document) - throws BadLocationException { - this.document = document; - this.position = position; - line = document.getLineOfOffset(position); - strings = new ArrayList<StringLiteral>(); - } - - public List<StringLiteral> getStrings() { - return strings; - } - - @Override - public boolean visit(StringLiteral node) { - try { - if (line == document.getLineOfOffset(node.getStartPosition()) - && node.getStartPosition() < position) { - strings.add(node); - return true; - } - } catch (BadLocationException e) { - } - return true; - } - } - - static class StringFinder extends ASTVisitor { - private int position; - private StringLiteral string; - - public StringFinder(int position) { - this.position = position; - } - - public StringLiteral getString() { - return string; - } - - @Override - public boolean visit(StringLiteral node) { - if (position > node.getStartPosition() - && position < (node.getStartPosition() + node.getLength())) - string = node; - return true; - } - } -} diff --git a/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF index 1e66b103..a83aa3e1 100644 --- a/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF @@ -5,3 +5,17 @@ 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;bundle-version="3.7.101", + org.eclipse.jdt.core;bundle-version="3.7.3", + org.eclipse.core.runtime;bundle-version="3.7.0", + org.eclipse.jface;bundle-version="3.7.0", + org.eclipse.babel.tapiji.tools.core;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 index 34d2e4d2..e9863e28 100644 --- a/org.eclipse.babel.tapiji.tools.java/build.properties +++ b/org.eclipse.babel.tapiji.tools.java/build.properties @@ -1,4 +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..44784264 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java @@ -0,0 +1,1062 @@ +/******************************************************************************* + * Copyright (c) 2012 TapiJI. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + ******************************************************************************/ +package org.eclipse.babel.tapiji.tools.java.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.eclipse.babel.tapiji.tools.core.Logger; +import org.eclipse.babel.tapiji.tools.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.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.CompilationUnit; +import org.eclipse.jdt.core.dom.ExpressionStatement; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.IVariableBinding; +import org.eclipse.jdt.core.dom.ImportDeclaration; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.SimpleType; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; +import org.eclipse.jdt.ui.SharedASTProvider; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.text.edits.TextEdit; + +public class ASTutils { + + private static MethodParameterDescriptor rbDefinition; + private static MethodParameterDescriptor rbAccessor; + + public static MethodParameterDescriptor getRBDefinitionDesc() { + if (rbDefinition == null) { + // Init descriptor for Resource-Bundle-Definition + List<String> definition = new ArrayList<String>(); + definition.add("getBundle"); + rbDefinition = new MethodParameterDescriptor(definition, + "java.util.ResourceBundle", true, 0); + } + + return rbDefinition; + } + + public static MethodParameterDescriptor getRBAccessorDesc() { + if (rbAccessor == null) { + // Init descriptor for Resource-Bundle-Accessors + List<String> accessors = new ArrayList<String>(); + accessors.add("getString"); + accessors.add("getStringArray"); + rbAccessor = new MethodParameterDescriptor(accessors, + "java.util.ResourceBundle", true, 0); + } + + return rbAccessor; + } + + public static CompilationUnit getCompilationUnit(IResource resource) { + IJavaElement je = JavaCore.create(resource, + JavaCore.create(resource.getProject())); + // get the type of the currently loaded resource + ITypeRoot typeRoot = ((ICompilationUnit) je); + + if (typeRoot == null) { + return null; + } + + return getCompilationUnit(typeRoot); + } + + public static CompilationUnit getCompilationUnit(ITypeRoot typeRoot) { + // get a reference to the shared AST of the loaded CompilationUnit + CompilationUnit cu = SharedASTProvider.getAST(typeRoot, + // do not wait for AST creation + SharedASTProvider.WAIT_YES, null); + + return cu; + } + + public static String insertExistingBundleRef(IDocument document, + IResource resource, int offset, int length, + String resourceBundleId, String key, Locale locale) { + String reference = ""; + String newName = null; + + CompilationUnit cu = getCompilationUnit(resource); + + String variableName = ASTutils.resolveRBReferenceVar(document, + resource, offset, resourceBundleId, cu); + if (variableName == null) { + newName = ASTutils.getNonExistingRBRefName(resourceBundleId, + document, cu); + } + + try { + reference = ASTutils.createResourceReference(resourceBundleId, key, + locale, resource, offset, variableName == null ? newName + : variableName, document, cu); + + document.replace(offset, length, reference); + + // create non-internationalisation-comment + createReplaceNonInternationalisationComment(cu, document, offset); + } catch (BadLocationException e) { + e.printStackTrace(); + } + + // TODO retrieve cu in the same way as in createResourceReference + // the current version does not parse method bodies + + if (variableName == null) { + ASTutils.createResourceBundleReference(resource, offset, document, + resourceBundleId, locale, true, newName, cu); + // createReplaceNonInternationalisationComment(cu, document, pos); + } + return reference; + } + + public static String insertNewBundleRef(IDocument document, + IResource resource, int startPos, int endPos, + String resourceBundleId, String key) { + String newName = null; + String reference = ""; + + CompilationUnit cu = getCompilationUnit(resource); + + if (cu == null) { + return null; + } + + String variableName = ASTutils.resolveRBReferenceVar(document, + resource, startPos, resourceBundleId, cu); + if (variableName == null) { + newName = ASTutils.getNonExistingRBRefName(resourceBundleId, + document, cu); + } + + try { + reference = ASTutils.createResourceReference(resourceBundleId, key, + null, resource, startPos, variableName == null ? newName + : variableName, document, cu); + + if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') { + startPos--; + endPos++; + } + + if ((startPos + endPos) < document.getLength() + && document.get().charAt(startPos + endPos) == '\"') { + endPos++; + } + + if ((startPos + endPos) < document.getLength() + && document.get().charAt(startPos + endPos - 1) == ';') { + endPos--; + } + + document.replace(startPos, endPos, reference); + + // create non-internationalisation-comment + createReplaceNonInternationalisationComment(cu, document, startPos); + } catch (BadLocationException e) { + e.printStackTrace(); + } + + if (variableName == null) { + // refresh reference to the shared AST of the loaded CompilationUnit + cu = getCompilationUnit(resource); + + ASTutils.createResourceBundleReference(resource, startPos, + document, resourceBundleId, null, true, newName, cu); + // createReplaceNonInternationalisationComment(cu, document, pos); + } + + return reference; + } + + public static String resolveRBReferenceVar(IDocument document, + IResource resource, int pos, final String bundleId, + CompilationUnit cu) { + String bundleVar; + + PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); + cu.accept(typeFinder); + AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType(); + TypeDeclaration td = typeFinder.getEnclosingType(); + MethodDeclaration meth = typeFinder.getEnclosingMethod(); + + if (atd == null) { + BundleDeclarationFinder bdf = new BundleDeclarationFinder( + bundleId, + td, + meth != null + && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); + td.accept(bdf); + + bundleVar = bdf.getVariableName(); + } else { + BundleDeclarationFinder bdf = new BundleDeclarationFinder( + bundleId, + atd, + meth != null + && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); + atd.accept(bdf); + + bundleVar = bdf.getVariableName(); + } + + // Check also method body + if (meth != null) { + try { + InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder( + bundleId, pos); + typeFinder.getEnclosingMethod().accept(imbdf); + bundleVar = imbdf.getVariableName() != null ? imbdf + .getVariableName() : bundleVar; + } catch (Exception e) { + // ignore + } + } + + return bundleVar; + } + + public static String getNonExistingRBRefName(String bundleId, + IDocument document, CompilationUnit cu) { + String referenceName = null; + int i = 0; + + while (referenceName == null) { + String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1) + + "Ref" + (i == 0 ? "" : i); + actRef = actRef.toLowerCase(); + + VariableFinder vf = new VariableFinder(actRef); + cu.accept(vf); + + if (!vf.isVariableFound()) { + referenceName = actRef; + break; + } + + i++; + } + + return referenceName; + } + + @Deprecated + public static String resolveResourceBundle( + MethodInvocation methodInvocation, + MethodParameterDescriptor rbDefinition, + Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { + String bundleName = null; + + if (methodInvocation.getExpression() instanceof SimpleName) { + SimpleName vName = (SimpleName) methodInvocation.getExpression(); + IVariableBinding vBinding = (IVariableBinding) vName + .resolveBinding(); + VariableDeclarationFragment dec = variableBindingManagers + .get(vBinding); + + if (dec.getInitializer() instanceof MethodInvocation) { + MethodInvocation init = (MethodInvocation) dec.getInitializer(); + + // Check declaring class + boolean isValidClass = false; + ITypeBinding type = init.resolveMethodBinding() + .getDeclaringClass(); + while (type != null) { + if (type.getQualifiedName().equals( + rbDefinition.getDeclaringClass())) { + isValidClass = true; + break; + } else { + if (rbDefinition.isConsiderSuperclass()) { + type = type.getSuperclass(); + } else { + type = null; + } + } + + } + if (!isValidClass) { + return null; + } + + boolean isValidMethod = false; + for (String mn : rbDefinition.getMethodName()) { + if (init.getName().getFullyQualifiedName().equals(mn)) { + isValidMethod = true; + break; + } + } + if (!isValidMethod) { + return null; + } + + // retrieve bundlename + if (init.arguments().size() < rbDefinition.getPosition() + 1) { + return null; + } + + bundleName = ((StringLiteral) init.arguments().get( + rbDefinition.getPosition())).getLiteralValue(); + } + } + + return bundleName; + } + + public static SLLocation resolveResourceBundleLocation( + MethodInvocation methodInvocation, + MethodParameterDescriptor rbDefinition, + Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { + SLLocation bundleDesc = null; + + if (methodInvocation.getExpression() instanceof SimpleName) { + SimpleName vName = (SimpleName) methodInvocation.getExpression(); + IVariableBinding vBinding = (IVariableBinding) vName + .resolveBinding(); + VariableDeclarationFragment dec = variableBindingManagers + .get(vBinding); + + if (dec.getInitializer() instanceof MethodInvocation) { + MethodInvocation init = (MethodInvocation) dec.getInitializer(); + + // Check declaring class + boolean isValidClass = false; + ITypeBinding type = init.resolveMethodBinding() + .getDeclaringClass(); + while (type != null) { + if (type.getQualifiedName().equals( + rbDefinition.getDeclaringClass())) { + isValidClass = true; + break; + } else { + if (rbDefinition.isConsiderSuperclass()) { + type = type.getSuperclass(); + } else { + type = null; + } + } + + } + if (!isValidClass) { + return null; + } + + boolean isValidMethod = false; + for (String mn : rbDefinition.getMethodName()) { + if (init.getName().getFullyQualifiedName().equals(mn)) { + isValidMethod = true; + break; + } + } + if (!isValidMethod) { + return null; + } + + // retrieve bundlename + if (init.arguments().size() < rbDefinition.getPosition() + 1) { + return null; + } + + StringLiteral bundleLiteral = ((StringLiteral) init.arguments() + .get(rbDefinition.getPosition())); + bundleDesc = new SLLocation(null, + bundleLiteral.getStartPosition(), + bundleLiteral.getLength() + + bundleLiteral.getStartPosition(), + bundleLiteral.getLiteralValue()); + } + } + + return bundleDesc; + } + + private static boolean isMatchingMethodDescriptor( + MethodInvocation methodInvocation, MethodParameterDescriptor desc) { + boolean result = false; + + if (methodInvocation.resolveMethodBinding() == null) { + return false; + } + + String methodName = methodInvocation.resolveMethodBinding().getName(); + + // Check declaring class + ITypeBinding type = methodInvocation.resolveMethodBinding() + .getDeclaringClass(); + while (type != null) { + if (type.getQualifiedName().equals(desc.getDeclaringClass())) { + result = true; + break; + } else { + if (desc.isConsiderSuperclass()) { + type = type.getSuperclass(); + } else { + type = null; + } + } + + } + + if (!result) { + return false; + } + + result = !result; + + // Check method name + for (String method : desc.getMethodName()) { + if (method.equals(methodName)) { + result = true; + break; + } + } + + return result; + } + + public static boolean isMatchingMethodParamDesc( + MethodInvocation methodInvocation, String literal, + MethodParameterDescriptor desc) { + boolean result = isMatchingMethodDescriptor(methodInvocation, desc); + + if (!result) { + return false; + } else { + result = false; + } + + if (methodInvocation.arguments().size() > desc.getPosition()) { + if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) { + StringLiteral sl = (StringLiteral) methodInvocation.arguments() + .get(desc.getPosition()); + if (sl.getLiteralValue().trim().toLowerCase() + .equals(literal.toLowerCase())) { + result = true; + } + } + } + + return result; + } + + public static boolean isMatchingMethodParamDesc( + MethodInvocation methodInvocation, StringLiteral literal, + MethodParameterDescriptor desc) { + int keyParameter = desc.getPosition(); + boolean result = isMatchingMethodDescriptor(methodInvocation, desc); + + if (!result) { + return false; + } + + // Check position within method call + StructuralPropertyDescriptor spd = literal.getLocationInParent(); + if (spd.isChildListProperty()) { + @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); + } + + } + + // 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 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); + } + } + + public static boolean existsNonInternationalisationComment( + StringLiteral literal) throws BadLocationException { + CompilationUnit cu = (CompilationUnit) literal.getRoot(); + ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); + + IDocument doc = null; + try { + doc = new Document(icu.getSource()); + } catch (JavaModelException e) { + Logger.logError(e); + } + + // get whole line in which string literal + int lineNo = doc.getLineOfOffset(literal.getStartPosition()); + int lineOffset = doc.getLineOffset(lineNo); + int lineLength = doc.getLineLength(lineNo); + String lineOfString = doc.get(lineOffset, lineLength); + + // search for a line comment in this line + int indexComment = lineOfString.indexOf("//"); + + if (indexComment == -1) { + return false; + } + + String comment = lineOfString.substring(indexComment); + + // remove first "//" of line comment + comment = comment.substring(2).toLowerCase(); + + // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3 + String[] comments = comment.split("//"); + + for (String commentFrag : comments) { + commentFrag = commentFrag.trim(); + + // if comment match format: "$non-nls$" then ignore whole line + if (commentFrag.matches("^\\$non-nls\\$$")) { + return true; + + // if comment match format: "$non-nls-{number}$" then only + // ignore string which is on given position + } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) { + int iString = findNonInternationalisationPosition(cu, doc, + literal.getStartPosition()); + int iComment = new Integer(commentFrag.substring(9, 10)); + if (iString == iComment) { + return true; + } + } + } + return false; + } + + public static StringLiteral getStringAtPos(CompilationUnit cu, int position) { + StringFinder strFinder = new StringFinder(position); + cu.accept(strFinder); + return strFinder.getString(); + } + + static class PositionalTypeFinder extends ASTVisitor { + + private int position; + private TypeDeclaration enclosingType; + private AnonymousClassDeclaration enclosingAnonymType; + private MethodDeclaration enclosingMethod; + + public PositionalTypeFinder(int pos) { + position = pos; + } + + public TypeDeclaration getEnclosingType() { + return enclosingType; + } + + public AnonymousClassDeclaration getEnclosingAnonymType() { + return enclosingAnonymType; + } + + public MethodDeclaration getEnclosingMethod() { + return enclosingMethod; + } + + @Override + public boolean visit(MethodDeclaration node) { + if (position >= node.getStartPosition() + && position <= (node.getStartPosition() + node.getLength())) { + enclosingMethod = node; + return true; + } else { + return false; + } + } + + @Override + public boolean visit(TypeDeclaration node) { + if (position >= node.getStartPosition() + && position <= (node.getStartPosition() + node.getLength())) { + enclosingType = node; + return true; + } else { + return false; + } + } + + @Override + public boolean visit(AnonymousClassDeclaration node) { + if (position >= node.getStartPosition() + && position <= (node.getStartPosition() + node.getLength())) { + enclosingAnonymType = node; + return true; + } else { + return false; + } + } + } + + static class ImportFinder extends ASTVisitor { + + String qName; + boolean importFound = false; + + public ImportFinder(String qName) { + this.qName = qName; + } + + public boolean isImportFound() { + return importFound; + } + + @Override + public boolean visit(ImportDeclaration id) { + if (id.getName().getFullyQualifiedName().equals(qName)) { + importFound = true; + } + + return true; + } + } + + static class VariableFinder extends ASTVisitor { + + boolean found = false; + String variableName; + + public boolean isVariableFound() { + return found; + } + + public VariableFinder(String variableName) { + this.variableName = variableName; + } + + @Override + public boolean visit(VariableDeclarationFragment vdf) { + if (vdf.getName().getFullyQualifiedName().equals(variableName)) { + found = true; + return false; + } + + return true; + } + } + + static class InMethodBundleDeclFinder extends ASTVisitor { + String varName; + String bundleId; + int pos; + + public InMethodBundleDeclFinder(String bundleId, int pos) { + this.bundleId = bundleId; + this.pos = pos; + } + + public String getVariableName() { + return varName; + } + + @Override + public boolean visit(VariableDeclarationFragment fdvd) { + if (fdvd.getStartPosition() > pos) { + return false; + } + + // boolean bStatic = (fdvd.resolveBinding().getModifiers() & + // Modifier.STATIC) == Modifier.STATIC; + // if (!bStatic && isStatic) + // return true; + + String tmpVarName = fdvd.getName().getFullyQualifiedName(); + + if (fdvd.getInitializer() instanceof MethodInvocation) { + MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer(); + if (isMatchingMethodParamDesc(fdi, bundleId, + getRBDefinitionDesc())) { + varName = tmpVarName; + } + } + return true; + } + } + + static class BundleDeclarationFinder extends ASTVisitor { + + String varName; + String bundleId; + ASTNode typeDef; + boolean isStatic; + + public BundleDeclarationFinder(String bundleId, ASTNode td, + boolean isStatic) { + this.bundleId = bundleId; + this.typeDef = td; + this.isStatic = isStatic; + } + + public String getVariableName() { + return varName; + } + + @Override + public boolean visit(MethodDeclaration md) { + return true; + } + + @Override + public boolean visit(FieldDeclaration fd) { + if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef) { + return false; + } + + boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC; + if (!bStatic && isStatic) { + return true; + } + + if (fd.getType() instanceof SimpleType) { + SimpleType fdType = (SimpleType) fd.getType(); + String typeName = fdType.getName().getFullyQualifiedName(); + String referenceName = getRBDefinitionDesc() + .getDeclaringClass(); + if (typeName.equals(referenceName) + || (referenceName.lastIndexOf(".") >= 0 && typeName + .equals(referenceName.substring(referenceName + .lastIndexOf(".") + 1)))) { + // Check VariableDeclarationFragment + if (fd.fragments().size() == 1) { + if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { + VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd + .fragments().get(0); + String tmpVarName = fdvd.getName() + .getFullyQualifiedName(); + + if (fdvd.getInitializer() instanceof MethodInvocation) { + MethodInvocation fdi = (MethodInvocation) fdvd + .getInitializer(); + if (isMatchingMethodParamDesc(fdi, bundleId, + getRBDefinitionDesc())) { + varName = tmpVarName; + } + } + } + } + } + } + return false; + } + + } + + static class LinePreStringsFinder extends ASTVisitor { + private int position; + private int line; + private List<StringLiteral> strings; + private IDocument document; + + public LinePreStringsFinder(int position, IDocument document) + throws BadLocationException { + this.document = document; + this.position = position; + line = document.getLineOfOffset(position); + strings = new ArrayList<StringLiteral>(); + } + + public List<StringLiteral> getStrings() { + return strings; + } + + @Override + public boolean visit(StringLiteral node) { + try { + if (line == document.getLineOfOffset(node.getStartPosition()) + && node.getStartPosition() < position) { + strings.add(node); + return true; + } + } catch (BadLocationException e) { + } + return true; + } + } + + static class StringFinder extends ASTVisitor { + private int position; + private StringLiteral string; + + public StringFinder(int position) { + this.position = position; + } + + public StringLiteral getString() { + return string; + } + + @Override + public boolean visit(StringLiteral node) { + if (position > node.getStartPosition() + && position < (node.getStartPosition() + node.getLength())) { + string = node; + } + return true; + } + } +} diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java similarity index 87% rename from org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java rename to org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java index d0694fa5..d342601b 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java @@ -5,7 +5,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.auditor; +package org.eclipse.babel.tapiji.tools.java.visitor; import java.util.List; @@ -15,31 +15,36 @@ public class MethodParameterDescriptor { private String declaringClass; private boolean considerSuperclass; private int position; - - public MethodParameterDescriptor(List<String> methodName, String declaringClass, - boolean considerSuperclass, 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; } @@ -51,7 +56,5 @@ public void setMethodName(List<String> methodName) { public List<String> getMethodName() { return methodName; } - - - + } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java similarity index 76% rename from org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java rename to org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java index 43659d4b..604cab2e 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java @@ -5,7 +5,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.auditor; +package org.eclipse.babel.tapiji.tools.java.visitor; import java.util.ArrayList; import java.util.Collection; @@ -17,8 +17,8 @@ import java.util.SortedMap; import java.util.TreeMap; +import org.eclipse.babel.tapiji.tools.core.model.SLLocation; import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager; -import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation; import org.eclipse.babel.tapiji.tools.java.util.ASTutils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; @@ -40,7 +40,7 @@ * */ public class ResourceAuditVisitor extends ASTVisitor implements - IResourceVisitor { + IResourceVisitor { private List<SLLocation> constants; private List<SLLocation> brokenStrings; @@ -52,8 +52,7 @@ public class ResourceAuditVisitor extends ASTVisitor implements 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>(); @@ -62,20 +61,22 @@ public ResourceAuditVisitor(IFile file, String projectName) { this.projectName = projectName; } + @SuppressWarnings("unchecked") @Override public boolean visit(VariableDeclarationStatement varDeclaration) { for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration - .fragments().iterator(); itFrag.hasNext();) { + .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();) { + .fragments().iterator(); itFrag.hasNext();) { VariableDeclarationFragment fragment = itFrag.next(); parseVariableDeclarationFragment(fragment); } @@ -83,7 +84,7 @@ public boolean visit(FieldDeclaration fieldDeclaration) { } protected void parseVariableDeclarationFragment( - VariableDeclarationFragment fragment) { + VariableDeclarationFragment fragment) { IVariableBinding vBinding = fragment.resolveBinding(); this.variableBindingManagers.put(vBinding, fragment); } @@ -92,60 +93,61 @@ protected void parseVariableDeclarationFragment( public boolean visit(StringLiteral stringLiteral) { try { ASTNode parent = stringLiteral.getParent(); - ResourceBundleManager manager = ResourceBundleManager.getManager(projectName); + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); if (parent instanceof MethodInvocation) { MethodInvocation methodInvocation = (MethodInvocation) parent; IRegion region = new Region(stringLiteral.getStartPosition(), - stringLiteral.getLength()); + stringLiteral.getLength()); // Check if this method invokes the getString-Method on a // ResourceBundle Implementation if (ASTutils.isMatchingMethodParamDesc(methodInvocation, - stringLiteral, ASTutils.getRBAccessorDesc())) { + stringLiteral, ASTutils.getRBAccessorDesc())) { // Check if the given Resource-Bundle reference is broken SLLocation rbName = ASTutils.resolveResourceBundleLocation( - methodInvocation, ASTutils.getRBDefinitionDesc(), - variableBindingManagers); + methodInvocation, ASTutils.getRBDefinitionDesc(), + variableBindingManagers); if (rbName == null - || manager.isKeyBroken(rbName.getLiteral(), - stringLiteral.getLiteralValue())) { + || manager.isKeyBroken(rbName.getLiteral(), + stringLiteral.getLiteralValue())) { // report new problem SLLocation desc = new SLLocation(file, - stringLiteral.getStartPosition(), - stringLiteral.getStartPosition() - + stringLiteral.getLength(), - stringLiteral.getLiteralValue()); + 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); + 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())) { + stringLiteral, ASTutils.getRBDefinitionDesc())) { rbDefReferences.put( - Long.valueOf(stringLiteral.getStartPosition()), - region); + Long.valueOf(stringLiteral.getStartPosition()), + region); boolean referenceBroken = true; for (String bundle : manager.getResourceBundleIdentifiers()) { if (bundle.trim().equals( - stringLiteral.getLiteralValue())) { + stringLiteral.getLiteralValue())) { referenceBroken = false; } } if (referenceBroken) { this.brokenRBReferences.add(new SLLocation(file, - stringLiteral.getStartPosition(), stringLiteral - .getStartPosition() - + stringLiteral.getLength(), - stringLiteral.getLiteralValue())); + stringLiteral.getStartPosition(), stringLiteral + .getStartPosition() + + stringLiteral.getLength(), + stringLiteral.getLiteralValue())); } return false; @@ -159,9 +161,9 @@ public boolean visit(StringLiteral stringLiteral) { // constant string literal found constants.add(new SLLocation(file, - stringLiteral.getStartPosition(), stringLiteral - .getStartPosition() + stringLiteral.getLength(), - stringLiteral.getLiteralValue())); + stringLiteral.getStartPosition(), stringLiteral + .getStartPosition() + stringLiteral.getLength(), + stringLiteral.getLiteralValue())); } catch (Exception e) { e.printStackTrace(); } @@ -186,12 +188,13 @@ public IRegion getKeyAt(Long position) { Iterator<Long> keys = keyPositions.keySet().iterator(); while (keys.hasNext()) { Long startPos = keys.next(); - if (startPos > position) + if (startPos > position) { break; + } IRegion region = keyPositions.get(startPos); if (region.getOffset() <= position - && (region.getOffset() + region.getLength()) >= position) { + && (region.getOffset() + region.getLength()) >= position) { reg = region; break; } @@ -201,10 +204,11 @@ public IRegion getKeyAt(Long position) { } public String getKeyAt(IRegion region) { - if (bundleKeys.containsKey(region)) + if (bundleKeys.containsKey(region)) { return bundleKeys.get(region); - else + } else { return ""; + } } public String getBundleReference(IRegion region) { @@ -220,8 +224,9 @@ public boolean visit(IResource resource) throws CoreException { public Collection<String> getDefinedResourceBundles(int offset) { Collection<String> result = new HashSet<String>(); for (String s : bundleReferences.values()) { - if (s != null) + if (s != null) { result.add(s); + } } return result; } @@ -232,12 +237,13 @@ public IRegion getRBReferenceAt(Long offset) { Iterator<Long> keys = rbDefReferences.keySet().iterator(); while (keys.hasNext()) { Long startPos = keys.next(); - if (startPos > offset) + if (startPos > offset) { break; + } IRegion region = rbDefReferences.get(startPos); if (region != null && region.getOffset() <= offset - && (region.getOffset() + region.getLength()) >= offset) { + && (region.getOffset() + region.getLength()) >= offset) { reg = region; break; }
ffdde40b9f189cb30dee4c5187d63b61809f2d62
hadoop
HADOOP-6583. Captures authentication and- authorization metrics. Contributed by Devaraj Das.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@915095 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index bf071d24a12aa..4a58a1d1a3b68 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -156,6 +156,8 @@ Trunk (unreleased changes) meaningful exceptions when there are failures instead of returning false. (omalley) + HADOOP-6583. Captures authentication and authorization metrics. (ddas) + OPTIMIZATIONS BUG FIXES diff --git a/src/java/org/apache/hadoop/ipc/Server.java b/src/java/org/apache/hadoop/ipc/Server.java index 6297ec7a947d2..efb25a70e8018 100644 --- a/src/java/org/apache/hadoop/ipc/Server.java +++ b/src/java/org/apache/hadoop/ipc/Server.java @@ -220,6 +220,11 @@ public static void bind(ServerSocket socket, InetSocketAddress address, } } } + + /*Returns a handle to the rpcMetrics (required in tests)*/ + public RpcMetrics getRpcMetrics() { + return rpcMetrics; + } /** A call queued for handling. */ private static class Call { @@ -877,7 +882,13 @@ public Object run() throws IOException { if (LOG.isDebugEnabled()) LOG.debug("Have read input token of size " + saslToken.length + " for processing by saslServer.evaluateResponse()"); - byte[] replyToken = saslServer.evaluateResponse(saslToken); + byte[] replyToken; + try { + replyToken = saslServer.evaluateResponse(saslToken); + } catch (SaslException se) { + rpcMetrics.authenticationFailures.inc(); + throw se; + } if (replyToken != null) { if (LOG.isDebugEnabled()) LOG.debug("Will send token of size " + replyToken.length @@ -1078,6 +1089,7 @@ private void processUnwrappedData(byte[] inBuf) throws IOException, private void processOneRpc(byte[] buf) throws IOException, InterruptedException { + rpcMetrics.authenticationSuccesses.inc(); if (headerRead) { processData(buf); } else { @@ -1121,7 +1133,9 @@ private boolean authorizeConnection() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Successfully authorized " + header); } + rpcMetrics.authorizationSuccesses.inc(); } catch (AuthorizationException ae) { + rpcMetrics.authorizationFailures.inc(); authFailedCall.connection = this; setupResponse(authFailedResponse, authFailedCall, Status.FATAL, null, ae.getClass().getName(), ae.getMessage()); diff --git a/src/java/org/apache/hadoop/ipc/metrics/RpcMetrics.java b/src/java/org/apache/hadoop/ipc/metrics/RpcMetrics.java index a1fbccd06d45b..dd5d2af5c725a 100644 --- a/src/java/org/apache/hadoop/ipc/metrics/RpcMetrics.java +++ b/src/java/org/apache/hadoop/ipc/metrics/RpcMetrics.java @@ -27,6 +27,7 @@ import org.apache.hadoop.metrics.util.MetricsBase; import org.apache.hadoop.metrics.util.MetricsIntValue; import org.apache.hadoop.metrics.util.MetricsRegistry; +import org.apache.hadoop.metrics.util.MetricsTimeVaryingInt; import org.apache.hadoop.metrics.util.MetricsTimeVaryingRate; /** @@ -79,7 +80,14 @@ public RpcMetrics(String hostName, String port, Server server) { new MetricsIntValue("NumOpenConnections", registry); public MetricsIntValue callQueueLen = new MetricsIntValue("callQueueLen", registry); - + public MetricsTimeVaryingInt authenticationFailures = + new MetricsTimeVaryingInt("rpcAuthenticationFailures", registry); + public MetricsTimeVaryingInt authenticationSuccesses = + new MetricsTimeVaryingInt("rpcAuthenticationSuccesses", registry); + public MetricsTimeVaryingInt authorizationFailures = + new MetricsTimeVaryingInt("rpcAuthorizationFailures", registry); + public MetricsTimeVaryingInt authorizationSuccesses = + new MetricsTimeVaryingInt("rpcAuthorizationSuccesses", registry); /** * Push the metrics to the monitoring subsystem on doUpdate() call. */ diff --git a/src/test/core/org/apache/hadoop/ipc/TestRPC.java b/src/test/core/org/apache/hadoop/ipc/TestRPC.java index 0bb3f8dc5c0b3..b94c88b4d19e7 100644 --- a/src/test/core/org/apache/hadoop/ipc/TestRPC.java +++ b/src/test/core/org/apache/hadoop/ipc/TestRPC.java @@ -368,6 +368,31 @@ private void doRPCs(Configuration conf, boolean expectFailure) throws Exception if (proxy != null) { RPC.stopProxy(proxy); } + if (expectFailure) { + assertTrue("Expected 1 but got " + + server.getRpcMetrics().authorizationFailures + .getCurrentIntervalValue(), + server.getRpcMetrics().authorizationFailures + .getCurrentIntervalValue() == 1); + } else { + assertTrue("Expected 1 but got " + + server.getRpcMetrics().authorizationSuccesses + .getCurrentIntervalValue(), + server.getRpcMetrics().authorizationSuccesses + .getCurrentIntervalValue() == 1); + } + //since we don't have authentication turned ON, we should see + // >0 for the authentication successes and 0 for failure + assertTrue("Expected 0 but got " + + server.getRpcMetrics().authenticationFailures + .getCurrentIntervalValue(), + server.getRpcMetrics().authenticationFailures + .getCurrentIntervalValue() == 0); + assertTrue("Expected greater than 0 but got " + + server.getRpcMetrics().authenticationSuccesses + .getCurrentIntervalValue(), + server.getRpcMetrics().authenticationSuccesses + .getCurrentIntervalValue() > 0); } }
4024e350d765be2eb312369b2c68cf16c1739151
tapiji
Disables tapiji auto-complete, when the user types non-string-literals. Fixes Issue 63
a
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java index 7e78e630..9b481e7c 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java @@ -47,11 +47,16 @@ public List<ICompletionProposal> computeCompletionProposals( try { JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context); CompletionContext coreContext = javaContext.getCoreContext(); + int tokenStart = coreContext.getTokenStart(); int tokenEnd = coreContext.getTokenEnd(); int tokenOffset = coreContext.getOffset(); boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL; + if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME + && (tokenEnd + 1) - tokenStart > 0) + return completions; + if (isStringLiteral) tokenStart++; @@ -69,8 +74,7 @@ public List<ICompletionProposal> computeCompletionProposals( tokenEnd - tokenStart); // Check if the string literal is up to be written within the - // context - // of a resource-bundle accessor method + // context of a resource-bundle accessor method ResourceBundleManager manager = ResourceBundleManager .getManager(javaContext.getCompilationUnit().getResource() .getProject());
6d69f7beadc0f23c9cedbc56332cd9712664c99b
drools
-update unit tests for LeftInputAdapterNode--git-svn-id: https://svn.jboss.org/repos/labs/trunk/labs/jbossrules@2283 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
p
https://github.com/kiegroup/drools
diff --git a/drools-core/src/test/java/org/drools/reteoo/LeftInputAdapterNodeTest.java b/drools-core/src/test/java/org/drools/reteoo/LeftInputAdapterNodeTest.java index e4b89ea06d9..1f843d7f608 100644 --- a/drools-core/src/test/java/org/drools/reteoo/LeftInputAdapterNodeTest.java +++ b/drools-core/src/test/java/org/drools/reteoo/LeftInputAdapterNodeTest.java @@ -1,17 +1,19 @@ package org.drools.reteoo; import java.util.List; +import java.util.Map; import org.drools.DroolsTestCase; import org.drools.rule.Rule; import org.drools.spi.PropagationContext; +import org.drools.util.LinkedList; +import org.drools.util.LinkedListNodeWrapper; public class LeftInputAdapterNodeTest extends DroolsTestCase { public void testLeftInputAdapterNode() { MockObjectSource source = new MockObjectSource( 15 ); LeftInputAdapterNode liaNode = new LeftInputAdapterNode( 23, - 0, source ); assertEquals( 23, liaNode.getId() ); @@ -31,7 +33,6 @@ public void testAttach() throws Exception { MockObjectSource source = new MockObjectSource( 15 ); LeftInputAdapterNode liaNode = new LeftInputAdapterNode( 1, - 0, source ); assertEquals( 1, @@ -62,34 +63,49 @@ public void testAssertObject() throws Exception { WorkingMemoryImpl workingMemory = new WorkingMemoryImpl( new RuleBaseImpl() ); - MockObjectSource source = new MockObjectSource( 15 ); - LeftInputAdapterNode liaNode = new LeftInputAdapterNode( 1, - 0, - source ); + new MockObjectSource( 15 ) ); MockTupleSink sink = new MockTupleSink(); liaNode.addTupleSink( sink ); Object string1 = "cheese"; - FactHandleImpl handle1 = new FactHandleImpl( 1 ); - - workingMemory.putObject( handle1, - string1 ); - - /* assert object */ - liaNode.assertObject( handle1, + + // assert object + FactHandleImpl f0 = (FactHandleImpl) workingMemory.assertObject( string1 ); + liaNode.assertObject( f0, context, workingMemory ); List asserted = sink.getAsserted(); assertLength( 1, asserted ); - - /* check tuple comes out */ - ReteTuple tuple = (ReteTuple) ((Object[]) asserted.get( 0 ))[0]; + ReteTuple tuple0 = (ReteTuple) ((Object[]) asserted.get( 0 ))[0]; assertSame( string1, - workingMemory.getObject( tuple.get( 0 ) ) ); + workingMemory.getObject( tuple0.get( 0 ) ) ); + + // check node memory + Map map = (Map) workingMemory.getNodeMemory( liaNode ); + LinkedList list0 = (LinkedList) (LinkedList)map.get( f0 ); + assertEquals( 1, list0.size() ); + assertSame( tuple0, ((LinkedListNodeWrapper)list0.getFirst()).getNode() ); + + // check memory stacks correctly + FactHandleImpl f1 = (FactHandleImpl) workingMemory.assertObject( "test1" ); + liaNode.assertObject( f1, + context, + workingMemory ); + + assertLength( 2, + asserted ); + ReteTuple tuple1 = (ReteTuple) ((Object[]) asserted.get( 1 ))[0]; + + LinkedList list1 = (LinkedList) (LinkedList)map.get( f1 ); + assertEquals( 1, list1.size() ); + assertSame( tuple1, ((LinkedListNodeWrapper)list1.getFirst()).getNode() ); + + assertNotSame( tuple0, tuple1 ); + } /** @@ -109,39 +125,26 @@ public void testRetractObject() throws Exception { MockObjectSource source = new MockObjectSource( 15 ); LeftInputAdapterNode liaNode = new LeftInputAdapterNode( 1, - 0, source ); MockTupleSink sink = new MockTupleSink(); liaNode.addTupleSink( sink ); - Object string1 = "cheese"; - - FactHandleImpl handle1 = new FactHandleImpl( 1 ); - - workingMemory.putObject( handle1, - string1 ); + FactHandleImpl f0 = (FactHandleImpl) workingMemory.assertObject( "f1" ); /* assert object */ - liaNode.assertObject( handle1, + liaNode.assertObject( f0, context, workingMemory ); ReteTuple tuple = (ReteTuple) ((Object[]) sink.getAsserted().get( 0 ))[0]; + + liaNode.retractObject( f0, context, workingMemory ); + + Map map = (Map) workingMemory.getNodeMemory( liaNode ); + assertNull( map.get( f0 ) ); - ReteTuple previous = new ReteTuple(0, handle1, workingMemory); - ReteTuple next = new ReteTuple(0, handle1, workingMemory); - - tuple.setPrevious( previous ); - tuple.setNext( next ); - - tuple.remove( context, workingMemory ); - - assertSame(previous.getNext(), next); - assertSame(next.getPrevious(), previous); + assertSame( tuple, (ReteTuple) ((Object[]) sink.getRetracted().get( 0 ))[0] ); - assertNull(tuple.getPrevious()); - assertNull(tuple.getNext()); - } }
d6fd1637307f6b088eb226c3f979085725530f32
jhy$jsoup
Performance improvment for Element.text
p
https://github.com/jhy/jsoup
diff --git a/src/main/java/org/jsoup/helper/StringUtil.java b/src/main/java/org/jsoup/helper/StringUtil.java index ad0679e5ad..3ee5953959 100644 --- a/src/main/java/org/jsoup/helper/StringUtil.java +++ b/src/main/java/org/jsoup/helper/StringUtil.java @@ -103,32 +103,45 @@ public static boolean isWhitespace(int c){ return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r'; } + /** + * Normalise the whitespace within this string; multiple spaces collapse to a single, and all whitespace characters + * (e.g. newline, tab) convert to a simple space + * @param string content to normalise + * @return normalised string + */ public static String normaliseWhitespace(String string) { StringBuilder sb = new StringBuilder(string.length()); + appendNormalisedWhitespace(sb, string, false); + return sb.toString(); + } + /** + * After normalizing the whitespace within a string, appends it to a string builder. + * @param accum builder to append to + * @param string string to normalize whitespace within + * @param stripLeading set to true if you wish to remove any leading whitespace + * @return + */ + public static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { boolean lastWasWhite = false; - boolean modified = false; + boolean reachedNonWhite = false; - int l = string.length(); + int len = string.length(); int c; - for (int i = 0; i < l; i+= Character.charCount(c)) { + for (int i = 0; i < len; i+= Character.charCount(c)) { c = string.codePointAt(i); if (isWhitespace(c)) { - if (lastWasWhite) { - modified = true; + if ((stripLeading && !reachedNonWhite) || lastWasWhite) continue; - } - if (c != ' ') - modified = true; - sb.append(' '); + accum.append(' '); lastWasWhite = true; } else { - sb.appendCodePoint(c); + accum.appendCodePoint(c); lastWasWhite = false; + reachedNonWhite = true; } } - return modified ? sb.toString() : string; } public static boolean in(String needle, String... haystack) { diff --git a/src/main/java/org/jsoup/nodes/Element.java b/src/main/java/org/jsoup/nodes/Element.java index 41a5535ce1..2bd950461d 100644 --- a/src/main/java/org/jsoup/nodes/Element.java +++ b/src/main/java/org/jsoup/nodes/Element.java @@ -867,12 +867,10 @@ private void ownText(StringBuilder accum) { private static void appendNormalisedText(StringBuilder accum, TextNode textNode) { String text = textNode.getWholeText(); - if (!preserveWhitespace(textNode.parent())) { - text = TextNode.normaliseWhitespace(text); - if (TextNode.lastCharIsWhitespace(accum)) - text = TextNode.stripLeadingWhitespace(text); - } - accum.append(text); + if (preserveWhitespace(textNode.parentNode)) + accum.append(text); + else + StringUtil.appendNormalisedWhitespace(accum, text, TextNode.lastCharIsWhitespace(accum)); } private static void appendWhitespaceIfBr(Element element, StringBuilder accum) { diff --git a/src/main/java/org/jsoup/nodes/TextNode.java b/src/main/java/org/jsoup/nodes/TextNode.java index fde9ec7268..a0dfefe1a9 100644 --- a/src/main/java/org/jsoup/nodes/TextNode.java +++ b/src/main/java/org/jsoup/nodes/TextNode.java @@ -90,14 +90,14 @@ public TextNode splitText(int offset) { } void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) { - String html = Entities.escape(getWholeText(), out); - if (out.prettyPrint() && parent() instanceof Element && !Element.preserveWhitespace((Element) parent())) { - html = normaliseWhitespace(html); - } - if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock() && !isBlank()) || (out.outline() && siblingNodes().size()>0 && !isBlank()) )) indent(accum, depth, out); - accum.append(html); + + String html = Entities.escape(getWholeText(), out); + if (out.prettyPrint() && parent() instanceof Element && !Element.preserveWhitespace((Element) parent())) + StringUtil.appendNormalisedWhitespace(accum, html, false); + else + accum.append(html); } void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out) {} diff --git a/src/test/java/org/jsoup/helper/StringUtilTest.java b/src/test/java/org/jsoup/helper/StringUtilTest.java index 3e6282102f..9e7be4daba 100644 --- a/src/test/java/org/jsoup/helper/StringUtilTest.java +++ b/src/test/java/org/jsoup/helper/StringUtilTest.java @@ -64,17 +64,6 @@ public class StringUtilTest { assertEquals("hello there", StringUtil.normaliseWhitespace("hello\nthere")); } - @Test public void normaliseWhiteSpaceModified() { - String check1 = "Hello there"; - String check2 = "Hello\nthere"; - String check3 = "Hello there"; - - // does not create new string no mods done - assertTrue(check1 == StringUtil.normaliseWhitespace(check1)); - assertTrue(check2 != StringUtil.normaliseWhitespace(check2)); - assertTrue(check3 != StringUtil.normaliseWhitespace(check3)); - } - @Test public void normaliseWhiteSpaceHandlesHighSurrogates() { String test71540chars = "\ud869\udeb2\u304b\u309a 1"; String test71540charsExpectedSingleWhitespace = "\ud869\udeb2\u304b\u309a 1";
57ec7d083a68abb23f009f9fdffb80197c138afd
hbase
HBASE-6400 Add getMasterAdmin() and- getMasterMonitor() to HConnection (Enis)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1363009 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hbase
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java index 6161a643388a..b623bc260d39 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java @@ -33,11 +33,11 @@ import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.HServerAddress; import org.apache.hadoop.hbase.HTableDescriptor; +import org.apache.hadoop.hbase.MasterAdminProtocol; +import org.apache.hadoop.hbase.MasterMonitorProtocol; import org.apache.hadoop.hbase.MasterNotRunningException; import org.apache.hadoop.hbase.ZooKeeperConnectionException; import org.apache.hadoop.hbase.catalog.CatalogTracker; -import org.apache.hadoop.hbase.client.AdminProtocol; -import org.apache.hadoop.hbase.client.ClientProtocol; import org.apache.hadoop.hbase.client.coprocessor.Batch; import org.apache.hadoop.hbase.ipc.CoprocessorProtocol; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; @@ -184,6 +184,17 @@ public HRegionLocation locateRegion(final byte [] regionName) public List<HRegionLocation> locateRegions(byte[] tableName) throws IOException; + /** + * Returns a {@link MasterAdminProtocol} to the active master + */ + public MasterAdminProtocol getMasterAdmin() throws IOException; + + /** + * Returns an {@link MasterMonitorProtocol} to the active master + */ + public MasterMonitorProtocol getMasterMonitor() throws IOException; + + /** * Establishes a connection to the region server at the specified address. * @param hostname RegionServer hostname diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java index b4af521abc53..632586fb36ae 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java @@ -27,8 +27,18 @@ import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import java.net.InetSocketAddress; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; @@ -52,7 +62,10 @@ import org.apache.hadoop.hbase.HServerAddress; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; +import org.apache.hadoop.hbase.MasterAdminProtocol; +import org.apache.hadoop.hbase.MasterMonitorProtocol; import org.apache.hadoop.hbase.MasterNotRunningException; +import org.apache.hadoop.hbase.MasterProtocol; import org.apache.hadoop.hbase.RegionMovedException; import org.apache.hadoop.hbase.RemoteExceptionHandler; import org.apache.hadoop.hbase.ServerName; @@ -65,11 +78,6 @@ import org.apache.hadoop.hbase.ipc.CoprocessorProtocol; import org.apache.hadoop.hbase.ipc.ExecRPCInvoker; import org.apache.hadoop.hbase.ipc.HBaseRPC; -import org.apache.hadoop.hbase.MasterProtocol; -import org.apache.hadoop.hbase.MasterMonitorProtocol; -import org.apache.hadoop.hbase.MasterAdminProtocol; -import org.apache.hadoop.hbase.client.MasterAdminKeepAliveConnection; -import org.apache.hadoop.hbase.client.MasterMonitorKeepAliveConnection; import org.apache.hadoop.hbase.ipc.VersionedProtocol; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.RequestConverter; @@ -77,10 +85,15 @@ import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsRequest; import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsResponse; import org.apache.hadoop.hbase.security.User; -import org.apache.hadoop.hbase.util.*; -import org.apache.hadoop.hbase.zookeeper.ZKClusterId; +import org.apache.hadoop.hbase.util.Addressing; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.Pair; +import org.apache.hadoop.hbase.util.SoftValueSortedMap; +import org.apache.hadoop.hbase.util.Triple; +import org.apache.hadoop.hbase.util.Writables; import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker; import org.apache.hadoop.hbase.zookeeper.RootRegionTracker; +import org.apache.hadoop.hbase.zookeeper.ZKClusterId; import org.apache.hadoop.hbase.zookeeper.ZKTable; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; @@ -1615,6 +1628,16 @@ private Object getKeepAliveMasterProtocol( } } + @Override + public MasterAdminProtocol getMasterAdmin() throws MasterNotRunningException { + return getKeepAliveMasterAdmin(); + }; + + @Override + public MasterMonitorProtocol getMasterMonitor() throws MasterNotRunningException { + return getKeepAliveMasterMonitor(); + } + /** * This function allows HBaseAdmin and potentially others * to get a shared MasterAdminProtocol connection.
d104b26a38fc5379dd01a2a61d865c4dc871cb55
hbase
HBASE-7715 FSUtils-waitOnSafeMode can incorrectly- loop on standby NN (Ted Yu)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1440600 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/util/FSUtils.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/util/FSUtils.java index 74a568896ace..31b596d84594 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/util/FSUtils.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/util/FSUtils.java @@ -24,6 +24,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -238,6 +239,31 @@ public static void checkFileSystemAvailable(final FileSystem fs) throw io; } + /** + * We use reflection because {@link DistributedFileSystem#setSafeMode( + * FSConstants.SafeModeAction action, boolean isChecked)} is not in hadoop 1.1 + * + * @param dfs + * @return whether we're in safe mode + * @throws IOException + */ + private static boolean isInSafeMode(DistributedFileSystem dfs) throws IOException { + boolean inSafeMode = false; + try { + Method m = DistributedFileSystem.class.getMethod("setSafeMode", new Class<?> []{ + org.apache.hadoop.hdfs.protocol.FSConstants.SafeModeAction.class, boolean.class}); + inSafeMode = (Boolean) m.invoke(dfs, + org.apache.hadoop.hdfs.protocol.FSConstants.SafeModeAction.SAFEMODE_GET, true); + } catch (Exception e) { + if (e instanceof IOException) throw (IOException) e; + + // Check whether dfs is on safemode. + inSafeMode = dfs.setSafeMode( + org.apache.hadoop.hdfs.protocol.FSConstants.SafeModeAction.SAFEMODE_GET); + } + return inSafeMode; + } + /** * Check whether dfs is in safemode. * @param conf @@ -249,8 +275,7 @@ public static void checkDfsSafeMode(final Configuration conf) FileSystem fs = FileSystem.get(conf); if (fs instanceof DistributedFileSystem) { DistributedFileSystem dfs = (DistributedFileSystem)fs; - // Check whether dfs is on safemode. - isInSafeMode = dfs.setSafeMode(org.apache.hadoop.hdfs.protocol.FSConstants.SafeModeAction.SAFEMODE_GET); + isInSafeMode = isInSafeMode(dfs); } if (isInSafeMode) { throw new IOException("File system is in safemode, it can't be written now"); @@ -622,7 +647,7 @@ public static void waitOnSafeMode(final Configuration conf, if (!(fs instanceof DistributedFileSystem)) return; DistributedFileSystem dfs = (DistributedFileSystem)fs; // Make sure dfs is not in safe mode - while (dfs.setSafeMode(org.apache.hadoop.hdfs.protocol.FSConstants.SafeModeAction.SAFEMODE_GET)) { + while (isInSafeMode(dfs)) { LOG.info("Waiting for dfs to exit safe mode..."); try { Thread.sleep(wait);
dabca506b7b4a7aa200cf7a81dcb290aa6b5b5eb
Mylyn Reviews
Removed CDO from the UI project
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF b/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF index 9309a535..c9787808 100644 --- a/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF +++ b/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF @@ -12,7 +12,6 @@ Require-Bundle: org.eclipse.ui, org.eclipse.compare;bundle-version="3.5.0", org.eclipse.mylyn.reviews.core;bundle-version="0.0.1", org.eclipse.emf.ecore.change;bundle-version="2.5.0", - org.eclipse.emf.cdo;bundle-version="2.0.0", org.eclipse.mylyn.bugzilla.ui;bundle-version="3.4.0" Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-1.6
60dfbfe5d954228d404eebc435346172cfbadec1
aeshell$aesh
LineParser now supports curly brackets. It have also been refactored caused by increase of complexity
a
https://github.com/aeshell/aesh
diff --git a/src/main/java/org/aesh/command/impl/AeshCommandResolver.java b/src/main/java/org/aesh/command/impl/AeshCommandResolver.java index 8d4e5f5f4..db111abee 100644 --- a/src/main/java/org/aesh/command/impl/AeshCommandResolver.java +++ b/src/main/java/org/aesh/command/impl/AeshCommandResolver.java @@ -34,9 +34,11 @@ public class AeshCommandResolver<C extends Command> implements CommandResolver<C> { private CommandRegistry<C> registry; + private LineParser lineParser; public AeshCommandResolver(CommandRegistry<C> commandRegistry) { this.registry = commandRegistry; + lineParser = new LineParser(); } public CommandRegistry<C> getRegistry() { @@ -45,8 +47,7 @@ public CommandRegistry<C> getRegistry() { @Override public CommandContainer<C> resolveCommand(String line) throws CommandNotFoundException { - ParsedLine aeshLine = LineParser.parseLine(line); - return getCommand(aeshLine, line); + return getCommand(lineParser.parseLine(line), line); } /** diff --git a/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java b/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java index fcb85b7f7..8c0c4d7b3 100644 --- a/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java +++ b/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java @@ -77,6 +77,8 @@ public class AeshCommandRuntime<C extends Command, CI extends CommandInvocation> private final AeshContext ctx; private final CommandInvocationBuilder<CI> commandInvocationBuilder; + private final LineParser lineParser; + public AeshCommandRuntime(AeshContext ctx, CommandRegistry<C> registry, CommandInvocationProvider<CI> commandInvocationProvider, @@ -98,6 +100,7 @@ public AeshCommandRuntime(AeshContext ctx, validatorInvocationProvider, optionActivatorProvider, commandActivatorProvider); processAfterInit(); registry.addRegistrationListener(this); + lineParser = new LineParser(); } @Override @@ -126,7 +129,7 @@ public void executeCommand(String line) throws CommandNotFoundException, try (CommandContainer<? extends Command> container = commandResolver.resolveCommand(line)) { resultHandler = container.getParser().getProcessedCommand().resultHandler(); CommandContainerResult ccResult = container.executeCommand( - LineParser.parseLine(line), + lineParser.parseLine(line), invocationProviders, ctx, commandInvocationProvider.enhanceCommandInvocation( @@ -209,7 +212,7 @@ private ProcessedCommand<C> getPopulatedCommand(String commandLine) throws Comma return null; } - ParsedLine aeshLine = LineParser.parseLine(commandLine); + ParsedLine aeshLine = lineParser.parseLine(commandLine); if (aeshLine.words().isEmpty()) { return null; } diff --git a/src/main/java/org/aesh/command/impl/parser/AeshCommandLineCompletionParser.java b/src/main/java/org/aesh/command/impl/parser/AeshCommandLineCompletionParser.java index 1154dfde5..8852f3b58 100644 --- a/src/main/java/org/aesh/command/impl/parser/AeshCommandLineCompletionParser.java +++ b/src/main/java/org/aesh/command/impl/parser/AeshCommandLineCompletionParser.java @@ -44,9 +44,11 @@ public class AeshCommandLineCompletionParser<C extends Command> implements CommandLineCompletionParser { private final AeshCommandLineParser<C> parser; + private final LineParser lineParser; public AeshCommandLineCompletionParser(AeshCommandLineParser<C> parser) { this.parser = parser; + lineParser = new LineParser(); } @@ -220,7 +222,7 @@ public void injectValuesAndComplete(ParsedCompleteObject completeObject, //we have partial/full name if(completeObject.getName() != null && completeObject.getName().length() > 0) { String rest = completeOperation.getBuffer().substring(0, completeOperation.getBuffer().lastIndexOf( completeObject.getName())); - ParsedLine parsedLine = LineParser.parseLine(rest); + ParsedLine parsedLine = lineParser.parseLine(rest); try { //parser.parse(parsedLine.iterator(), true); parser.getCommandPopulator().populateObject(parser.getProcessedCommand(), invocationProviders, @@ -245,7 +247,7 @@ public void injectValuesAndComplete(ParsedCompleteObject completeObject, } else { try { - ParsedLine parsedLine = LineParser.parseLine(completeOperation.getBuffer()); + ParsedLine parsedLine = lineParser.parseLine(completeOperation.getBuffer()); if(parsedLine.words().get(parsedLine.words().size()-1).word().equals("--") || parsedLine.words().get(parsedLine.words().size()-1).word().equals("-")) parsedLine.words().remove(parsedLine.words().size()-1); @@ -355,7 +357,7 @@ else if(completeObject.isArgument()) { String lastWord = Parser.findEscapedSpaceWordCloseToEnd(completeOperation.getBuffer()); String rest = completeOperation.getBuffer().substring(0, completeOperation.getBuffer().length() - lastWord.length()); try { - ParsedLine parsedLine = LineParser.parseLine(rest); + ParsedLine parsedLine = lineParser.parseLine(rest); parser.parse(parsedLine.iterator(), CommandLineParser.Mode.NONE); parser.getCommandPopulator().populateObject(parser.getProcessedCommand(), invocationProviders, completeOperation.getContext(), CommandLineParser.Mode.NONE); diff --git a/src/main/java/org/aesh/command/impl/parser/AeshCommandLineParser.java b/src/main/java/org/aesh/command/impl/parser/AeshCommandLineParser.java index 6726bbacf..2ace203d1 100644 --- a/src/main/java/org/aesh/command/impl/parser/AeshCommandLineParser.java +++ b/src/main/java/org/aesh/command/impl/parser/AeshCommandLineParser.java @@ -52,9 +52,11 @@ public class AeshCommandLineParser<C extends Command> implements CommandLinePars private boolean isChild = false; private ProcessedOption lastParsedOption; private boolean parsedCommand = false; + private final LineParser lineParser; public AeshCommandLineParser(ProcessedCommand<C> processedCommand) { this.processedCommand = processedCommand; + lineParser = new LineParser(); } @Override @@ -301,7 +303,7 @@ public ProcessedOption lastParsedOption() { */ @Override public void parse(String line, Mode mode) { - parse(LineParser.parseLine(line).iterator(), mode); + parse(lineParser.parseLine(line).iterator(), mode); } @Override diff --git a/src/main/java/org/aesh/console/export/ExportCompletion.java b/src/main/java/org/aesh/console/export/ExportCompletion.java index b0730eaed..c17d38023 100644 --- a/src/main/java/org/aesh/console/export/ExportCompletion.java +++ b/src/main/java/org/aesh/console/export/ExportCompletion.java @@ -32,9 +32,11 @@ public class ExportCompletion implements Completion { private static final String EXPORT = "export"; private static final String EXPORT_SPACE = "export "; private final ExportManager exportManager; + private final LineParser lineParser; public ExportCompletion(ExportManager manager) { this.exportManager = manager; + lineParser = new LineParser(); } @Override @@ -51,7 +53,7 @@ else if(EXPORT_SPACE.equals(completeOperation.getBuffer()) || completeOperation.setOffset(completeOperation.getCursor()); } else if(completeOperation.getBuffer().startsWith(EXPORT_SPACE)) { - String word = LineParser.parseLine(completeOperation.getBuffer(), completeOperation.getCursor()).selectedWord().word(); + String word = lineParser.parseLine(completeOperation.getBuffer(), completeOperation.getCursor()).selectedWord().word(); if(word.length() > 0) { completeOperation.addCompletionCandidates( exportManager.findAllMatchingKeys(word)); if(Parser.containsNonEscapedDollar(word)) { @@ -63,7 +65,7 @@ else if(completeOperation.getBuffer().startsWith(EXPORT_SPACE)) { } } else if(Parser.containsNonEscapedDollar( completeOperation.getBuffer())) { - String word = LineParser.parseLine(completeOperation.getBuffer(), completeOperation.getCursor()).selectedWord().word(); + String word = lineParser.parseLine(completeOperation.getBuffer(), completeOperation.getCursor()).selectedWord().word(); if(Parser.containsNonEscapedDollar(word)) { completeOperation.addCompletionCandidates(exportManager.findAllMatchingKeys(word)); completeOperation.setOffset(completeOperation.getCursor()-word.length()); diff --git a/src/main/java/org/aesh/console/operator/RedirectionCompletion.java b/src/main/java/org/aesh/console/operator/RedirectionCompletion.java index 7ca1ad542..80499e594 100644 --- a/src/main/java/org/aesh/console/operator/RedirectionCompletion.java +++ b/src/main/java/org/aesh/console/operator/RedirectionCompletion.java @@ -39,7 +39,7 @@ public void complete(CompleteOperation completeOperation) { int redirectPos = ControlOperatorParser.findLastRedirectionPositionBeforeCursor( completeOperation.getBuffer(), completeOperation.getCursor()); - String word = LineParser.parseLine(completeOperation.getBuffer(), + String word = new LineParser().parseLine(completeOperation.getBuffer(), completeOperation.getCursor()).selectedWord().word(); completeOperation.setOffset(completeOperation.getCursor()); diff --git a/src/main/java/org/aesh/parser/LineParser.java b/src/main/java/org/aesh/parser/LineParser.java index a2dd32229..2fa7165e1 100644 --- a/src/main/java/org/aesh/parser/LineParser.java +++ b/src/main/java/org/aesh/parser/LineParser.java @@ -17,6 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.aesh.parser; import java.util.ArrayList; @@ -32,6 +33,22 @@ public class LineParser { private static final char BACK_SLASH = '\\'; private static final char SINGLE_QUOTE = '\''; private static final char DOUBLE_QUOTE = '\"'; + private static final char CURLY_START = '{'; + private static final char CURLY_END = '}'; + + private List<ParsedWord> textList = new ArrayList<>(); + private boolean haveEscape = false; + private boolean haveSingleQuote = false; + private boolean haveDoubleQuote = false; + private boolean ternaryQuote = false; + private boolean haveCurlyBracket = false; + private boolean haveSquareBracket = false; + private boolean haveBlock = false; + private StringBuilder builder = new StringBuilder(); + private char prev = NULL_CHAR; + private int index = 0; + private int cursorWord = -1; + private int wordCursor = -1; /** * Split up the text into words, escaped spaces and quotes are handled @@ -39,22 +56,17 @@ public class LineParser { * @param text test * @return aeshline with all the words */ - public static ParsedLine parseLine(String text) { + public ParsedLine parseLine(String text) { return parseLine(text, -1); } - public static ParsedLine parseLine(String text, int cursor) { - List<ParsedWord> textList = new ArrayList<>(); - boolean haveEscape = false; - boolean haveSingleQuote = false; - boolean haveDoubleQuote = false; - boolean ternaryQuote = false; - StringBuilder builder = new StringBuilder(); - char prev = NULL_CHAR; - int index = 0; - int cursorWord = -1; - int wordCursor = -1; + public ParsedLine parseLine(String text, int cursor) { + return parseLine(text, cursor, false); + } + public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets) { + //first reset all values + reset(); for (char c : text.toCharArray()) { //if the previous char was a space, there is no word "connected" to cursor if(cursor == index && (prev != SPACE_CHAR || haveEscape)) { @@ -62,17 +74,7 @@ public static ParsedLine parseLine(String text, int cursor) { wordCursor = builder.length(); } if (c == SPACE_CHAR) { - if (haveEscape) { - builder.append(c); - haveEscape = false; - } - else if (haveSingleQuote || haveDoubleQuote) { - builder.append(c); - } - else if (builder.length() > 0) { - textList.add(new ParsedWord(builder.toString(), index-builder.length())); - builder = new StringBuilder(); - } + handleSpace(c); } else if (c == BACK_SLASH) { if (haveEscape || ternaryQuote) { @@ -83,52 +85,17 @@ else if (c == BACK_SLASH) { haveEscape = true; } else if (c == SINGLE_QUOTE) { - if (haveEscape || ternaryQuote) { - builder.append(c); - haveEscape = false; - } - else if (haveSingleQuote) { - if (builder.length() > 0) { - textList.add(new ParsedWord(builder.toString(), index-builder.length())); - builder = new StringBuilder(); - } - haveSingleQuote = false; - } - else if(haveDoubleQuote) { - builder.append(c); - } - else - haveSingleQuote = true; + handleSingleQuote(c); } else if (c == DOUBLE_QUOTE) { - if (haveEscape || (ternaryQuote && prev != DOUBLE_QUOTE)) { - builder.append(c); - haveEscape = false; - } - else if (haveDoubleQuote) { - if (!ternaryQuote && prev == DOUBLE_QUOTE) - ternaryQuote = true; - else if (ternaryQuote && prev == DOUBLE_QUOTE) { - if (builder.length() > 0) { - builder.deleteCharAt(builder.length() - 1); - textList.add(new ParsedWord(builder.toString(), index-builder.length())); - builder = new StringBuilder(); - } - haveDoubleQuote = false; - ternaryQuote = false; - } - else { - if (builder.length() > 0) { - textList.add(new ParsedWord(builder.toString(), index-builder.length())); - builder = new StringBuilder(); - } - haveDoubleQuote = false; - } - } - else if(haveSingleQuote) - builder.append(c); - else - haveDoubleQuote = true; + handleDoubleQuote(c); + } + else if(parseCurlyAndSquareBrackets && c == CURLY_START) { + handleCurlyStart(c); + + } + else if(parseCurlyAndSquareBrackets && c == CURLY_END && haveCurlyBracket) { + handleCurlyEnd(c); } else if (haveEscape) { builder.append(BACK_SLASH); @@ -156,9 +123,108 @@ else if (haveEscape) { ParserStatus status = ParserStatus.OK; if (haveSingleQuote && haveDoubleQuote) status = ParserStatus.DOUBLE_UNCLOSED_QUOTE; - else if (haveSingleQuote || haveDoubleQuote) + else if (haveSingleQuote || haveDoubleQuote || haveCurlyBracket) status = ParserStatus.UNCLOSED_QUOTE; return new ParsedLine(text, textList, cursor, cursorWord, wordCursor, status, ""); } + + private void handleCurlyEnd(char c) { + if(haveEscape) + haveEscape = false; + else { + haveCurlyBracket = false; + } + builder.append(c); + } + + private void handleCurlyStart(char c) { + if(haveEscape) { + haveEscape = false; + } + else { + haveCurlyBracket = true; + } + builder.append(c); + } + + private void handleDoubleQuote(char c) { + if (haveEscape || (ternaryQuote && prev != DOUBLE_QUOTE)) { + builder.append(c); + haveEscape = false; + } + else if (haveDoubleQuote) { + if (!ternaryQuote && prev == DOUBLE_QUOTE) + ternaryQuote = true; + else if (ternaryQuote && prev == DOUBLE_QUOTE) { + if (builder.length() > 0) { + builder.deleteCharAt(builder.length() - 1); + textList.add(new ParsedWord(builder.toString(), index-builder.length())); + builder = new StringBuilder(); + } + haveDoubleQuote = false; + ternaryQuote = false; + } + else { + if (builder.length() > 0) { + textList.add(new ParsedWord(builder.toString(), index-builder.length())); + builder = new StringBuilder(); + } + haveDoubleQuote = false; + } + } + else if(haveSingleQuote) + builder.append(c); + else + haveDoubleQuote = true; + } + + private void handleSingleQuote(char c) { + if (haveEscape || ternaryQuote) { + builder.append(c); + haveEscape = false; + } + else if (haveSingleQuote) { + if (builder.length() > 0) { + textList.add(new ParsedWord(builder.toString(), index-builder.length())); + builder = new StringBuilder(); + } + haveSingleQuote = false; + } + else if(haveDoubleQuote) { + builder.append(c); + } + else + haveSingleQuote = true; + } + + private void handleSpace(char c) { + if (haveEscape) { + builder.append(c); + haveEscape = false; + } + else if (haveSingleQuote || haveDoubleQuote || haveCurlyBracket) { + builder.append(c); + } + else if (builder.length() > 0) { + textList.add(new ParsedWord(builder.toString(), index-builder.length())); + builder = new StringBuilder(); + } + } + + private void reset() { + textList = new ArrayList<>(); + haveEscape = false; + haveSingleQuote = false; + haveDoubleQuote = false; + ternaryQuote = false; + haveCurlyBracket = false; + haveSquareBracket = false; + haveBlock = false; + builder = new StringBuilder(); + prev = NULL_CHAR; + index = 0; + cursorWord = -1; + wordCursor = -1; + } } diff --git a/src/test/java/org/aesh/parser/LineParserTest.java b/src/test/java/org/aesh/parser/LineParserTest.java index 588e87689..c110d4949 100644 --- a/src/test/java/org/aesh/parser/LineParserTest.java +++ b/src/test/java/org/aesh/parser/LineParserTest.java @@ -17,6 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.aesh.parser; import org.junit.Test; @@ -31,112 +32,119 @@ */ public class LineParserTest { - @Test + @Test public void testfindCurrentWordFromCursor() { - assertEquals("", LineParser.parseLine(" ", 1).selectedWord().word()); - assertEquals("foo", LineParser.parseLine("foo bar", 3).selectedWord().word()); - assertEquals("bar", LineParser.parseLine("foo bar", 6).selectedWord().word()); - assertEquals("foobar", LineParser.parseLine("foobar", 6).selectedWord().word()); - assertEquals("fo", LineParser.parseLine("foobar", 2).selectedWordToCursor().word()); - assertEquals("", LineParser.parseLine("ls ", 3).selectedWord().word()); - assertEquals("foo", LineParser.parseLine("ls foo", 6).selectedWord().word()); - assertEquals("foo", LineParser.parseLine("ls foo bar", 6).selectedWord().word()); - assertEquals("bar", LineParser.parseLine("ls foo bar", 11).selectedWordToCursor().word()); - assertEquals("ba", LineParser.parseLine("ls foo bar", 10).selectedWordToCursor().word()); - assertEquals("b", LineParser.parseLine("ls foo bar", 9).selectedWordToCursor().word()); - assertEquals("foo", LineParser.parseLine("ls foo ", 6).selectedWordToCursor().word()); - assertEquals("o", LineParser.parseLine("ls o org/jboss/aeshell/Shell.class", 4).selectedWord().word()); - assertEquals("", LineParser.parseLine("ls org/jboss/aeshell/Shell.class", 3).selectedWord().word()); + LineParser lineParser = new LineParser(); + assertEquals("", lineParser.parseLine(" ", 1).selectedWord().word()); + assertEquals("foo", lineParser.parseLine("foo bar", 3).selectedWord().word()); + assertEquals("bar", lineParser.parseLine("foo bar", 6).selectedWord().word()); + assertEquals("foobar", lineParser.parseLine("foobar", 6).selectedWord().word()); + assertEquals("fo", lineParser.parseLine("foobar", 2).selectedWordToCursor().word()); + assertEquals("", lineParser.parseLine("ls ", 3).selectedWord().word()); + assertEquals("foo", lineParser.parseLine("ls foo", 6).selectedWord().word()); + assertEquals("foo", lineParser.parseLine("ls foo bar", 6).selectedWord().word()); + assertEquals("bar", lineParser.parseLine("ls foo bar", 11).selectedWordToCursor().word()); + assertEquals("ba", lineParser.parseLine("ls foo bar", 10).selectedWordToCursor().word()); + assertEquals("b", lineParser.parseLine("ls foo bar", 9).selectedWordToCursor().word()); + assertEquals("foo", lineParser.parseLine("ls foo ", 6).selectedWordToCursor().word()); + assertEquals("o", lineParser.parseLine("ls o org/jboss/aeshell/Shell.class", 4).selectedWord().word()); + assertEquals("", lineParser.parseLine("ls org/jboss/aeshell/Shell.class", 3).selectedWord().word()); } @Test public void testFindCurrentWordWithEscapedSpaceToCursor() { - assertEquals("foo bar", LineParser.parseLine("foo\\ bar", 8).selectedWordToCursor().word()); - assertEquals("foo ba", LineParser.parseLine("foo\\ bar", 7).selectedWordToCursor().word()); - assertEquals("foo bar", LineParser.parseLine("ls foo\\ bar", 12).selectedWordToCursor().word()); + LineParser lineParser = new LineParser(); + assertEquals("foo bar", lineParser.parseLine("foo\\ bar", 8).selectedWordToCursor().word()); + assertEquals("foo ba", lineParser.parseLine("foo\\ bar", 7).selectedWordToCursor().word()); + assertEquals("foo bar", lineParser.parseLine("ls foo\\ bar", 12).selectedWordToCursor().word()); } @Test public void testFindClosestWholeWordToCursor() { - assertEquals("foo", LineParser.parseLine("ls foo bar", 6).selectedWord().word()); + LineParser lineParser = new LineParser(); + assertEquals("foo", lineParser.parseLine("ls foo bar", 6).selectedWord().word()); - assertEquals("", LineParser.parseLine(" ", 1).selectedWord().word()); - assertEquals("foo", LineParser.parseLine("foo bar", 1).selectedWord().word()); - assertEquals("foo", LineParser.parseLine("foo bar", 3).selectedWord().word()); - assertEquals("foobar", LineParser.parseLine("foobar", 6).selectedWord().word()); - assertEquals("foobar", LineParser.parseLine("foobar", 2).selectedWord().word()); - assertEquals("", LineParser.parseLine("ls ", 3).selectedWord().word()); + assertEquals("", lineParser.parseLine(" ", 1).selectedWord().word()); + assertEquals("foo", lineParser.parseLine("foo bar", 1).selectedWord().word()); + assertEquals("foo", lineParser.parseLine("foo bar", 3).selectedWord().word()); + assertEquals("foobar", lineParser.parseLine("foobar", 6).selectedWord().word()); + assertEquals("foobar", lineParser.parseLine("foobar", 2).selectedWord().word()); + assertEquals("", lineParser.parseLine("ls ", 3).selectedWord().word()); - assertEquals("o", LineParser.parseLine("ls o org/jboss/aeshell/Shell.class", 4).selectedWord().word()); - assertEquals("", LineParser.parseLine("ls org/jboss/aeshell/Shell.class", 3).selectedWord().word()); + assertEquals("o", lineParser.parseLine("ls o org/jboss/aeshell/Shell.class", 4).selectedWord().word()); + assertEquals("", lineParser.parseLine("ls org/jboss/aeshell/Shell.class", 3).selectedWord().word()); - assertEquals("foo", LineParser.parseLine("foo bar foo", 3).selectedWord().word()); + assertEquals("foo", lineParser.parseLine("foo bar foo", 3).selectedWord().word()); } @Test public void testFindClosestWholeWordToCursorEscapedSpace() { - assertEquals("foo bar", LineParser.parseLine("foo\\ bar", 7).selectedWord().word()); - assertEquals("foo bar", LineParser.parseLine("ls foo\\ bar", 11).selectedWord().word()); + LineParser lineParser = new LineParser(); + assertEquals("foo bar", lineParser.parseLine("foo\\ bar", 7).selectedWord().word()); + assertEquals("foo bar", lineParser.parseLine("ls foo\\ bar", 11).selectedWord().word()); } @Test public void testOriginalInput() { + LineParser lineParser = new LineParser(); String input = "echo foo -i bar"; - ParsedLine line = LineParser.parseLine(input); + ParsedLine line = lineParser.parseLine(input); assertEquals(input, line.line()); } @Test public void testFindAllWords() { - ParsedLine line = LineParser.parseLine("", 0); + LineParser lineParser = new LineParser(); + ParsedLine line = lineParser.parseLine("", 0); assertEquals(-1, line.wordCursor()); assertEquals(0, line.cursor()); assertEquals("", line.selectedWord().word()); - line = LineParser.parseLine(" foo bar\\ baz 12345 ", 5); + line = lineParser.parseLine(" foo bar\\ baz 12345 ", 5); assertEquals("foo", line.words().get(0).word()); assertEquals("bar baz", line.words().get(1).word()); assertEquals("12345", line.words().get(2).word()); assertEquals("foo", line.selectedWord().word()); assertEquals(2, line.wordCursor()); - line = LineParser.parseLine("man < foo\\ bar ", 14); + line = lineParser.parseLine("man < foo\\ bar ", 14); assertEquals("man", line.words().get(0).word()); assertEquals("<", line.words().get(1).word()); assertEquals("foo bar", line.words().get(2).word()); assertEquals("foo bar", line.selectedWord().word()); assertEquals(7, line.wordCursor()); - line = LineParser.parseLine("cd A\\ Directory\\ With\\ Spaces", 2); + line = lineParser.parseLine("cd A\\ Directory\\ With\\ Spaces", 2); assertEquals("cd", line.words().get(0).word()); assertEquals("A Directory With Spaces", line.words().get(1).word()); assertEquals("cd", line.selectedWord().word()); assertEquals(2, line.wordCursor()); - line = LineParser.parseLine("cd A\\ ",5); + line = lineParser.parseLine("cd A\\ ",5); assertEquals("cd", line.words().get(0).word()); assertEquals("A ", line.words().get(1).word()); assertEquals("A ", line.selectedWord().word()); assertEquals(1, line.wordCursor()); - line = LineParser.parseLine("cd A\\", 4); + line = lineParser.parseLine("cd A\\", 4); assertEquals("cd", line.words().get(0).word()); assertEquals("A\\", line.words().get(1).word()); assertEquals("A\\", line.selectedWord().word()); assertEquals(1, line.wordCursor()); - line = LineParser.parseLine("ls --files /tmp/A\\ "); + line = lineParser.parseLine("ls --files /tmp/A\\ "); assertEquals("ls", line.words().get(0).word()); assertEquals("--files", line.words().get(1).word()); assertEquals("/tmp/A ", line.words().get(2).word()); - line = LineParser.parseLine("..\\..\\..\\..\\..\\..\\..\\temp\\foo.txt"); + line = lineParser.parseLine("..\\..\\..\\..\\..\\..\\..\\temp\\foo.txt"); assertEquals("..\\..\\..\\..\\..\\..\\..\\temp\\foo.txt", line.words().get(0).word()); } @Test public void testFindAllQuotedWords() { - ParsedLine line = LineParser.parseLine("foo bar \"baz 12345\" ", 19); + LineParser lineParser = new LineParser(); + ParsedLine line = lineParser.parseLine("foo bar \"baz 12345\" ", 19); assertEquals("foo", line.words().get(0).word()); assertEquals(0, line.words().get(0).lineIndex()); assertEquals("bar", line.words().get(1).word()); @@ -146,57 +154,59 @@ public void testFindAllQuotedWords() { assertEquals("", line.selectedWord().word()); assertEquals(0, line.wordCursor()); - line = LineParser.parseLine("java -cp \"foo/bar\" \"Example\""); + line = lineParser.parseLine("java -cp \"foo/bar\" \"Example\""); assertEquals("foo/bar", line.words().get(2).word()); assertEquals("Example", line.words().get(3).word()); - line = LineParser.parseLine("'foo/bar/' Example\\ 1"); + line = lineParser.parseLine("'foo/bar/' Example\\ 1"); assertEquals("foo/bar/", line.words().get(0).word()); assertEquals("Example 1", line.words().get(1).word()); - line = LineParser.parseLine("man -f='foo bar/' Example\\ 1 foo"); + line = lineParser.parseLine("man -f='foo bar/' Example\\ 1 foo"); assertEquals("man", line.words().get(0).word()); assertEquals("-f=foo bar/", line.words().get(1).word()); assertEquals("Example 1", line.words().get(2).word()); assertEquals("foo", line.words().get(3).word()); - line = LineParser.parseLine("man -f='foo/bar/ Example\\ 1"); + line = lineParser.parseLine("man -f='foo/bar/ Example\\ 1"); assertEquals(ParserStatus.UNCLOSED_QUOTE, line.status()); - line = LineParser.parseLine("man -f='foo/bar/' Example\\ 1\""); + line = lineParser.parseLine("man -f='foo/bar/' Example\\ 1\""); assertEquals(ParserStatus.UNCLOSED_QUOTE, line.status()); - line = LineParser.parseLine("-s \'redirectUris=[\"http://localhost:8080/blah/*\"]\'"); + line = lineParser.parseLine("-s \'redirectUris=[\"http://localhost:8080/blah/*\"]\'"); assertEquals("-s", line.words().get(0).word()); assertEquals("redirectUris=[\"http://localhost:8080/blah/*\"]", line.words().get(1).word()); } @Test public void testFindAllTernaryQuotedWords() { - ParsedLine line = LineParser.parseLine("\"\" \"\""); + LineParser lineParser = new LineParser(); + ParsedLine line = lineParser.parseLine("\"\" \"\""); assertEquals(" ", line.words().get(0).word()); - line = LineParser.parseLine("\"\" foo bar \"\""); + line = lineParser.parseLine("\"\" foo bar \"\""); assertEquals(" foo bar ", line.words().get(0).word()); - line = LineParser.parseLine("\"\" \"foo bar\" \"\""); + line = lineParser.parseLine("\"\" \"foo bar\" \"\""); assertEquals(" \"foo bar\" ", line.words().get(0).word()); - line = LineParser.parseLine("gah bah-bah \"\" \"foo bar\" \"\" boo"); + line = lineParser.parseLine("gah bah-bah \"\" \"foo bar\" \"\" boo"); assertEquals("gah", line.words().get(0).word()); assertEquals("bah-bah", line.words().get(1).word()); assertEquals(" \"foo bar\" ", line.words().get(2).word()); assertEquals("boo", line.words().get(3).word()); - line = LineParser.parseLine(" \"\"/s-ramp/wsdl/Operation[xp2:matches(@name, 'submit.*')]\"\""); + line = lineParser.parseLine(" \"\"/s-ramp/wsdl/Operation[xp2:matches(@name, 'submit.*')]\"\""); assertEquals("/s-ramp/wsdl/Operation[xp2:matches(@name, 'submit.*')]", line.words().get(0).word()); - line = LineParser.parseLine(" \"\"/s-ramp/ext/${type} \\ \"\""); + line = lineParser.parseLine(" \"\"/s-ramp/ext/${type} \\ \"\""); assertEquals("/s-ramp/ext/${type} \\ ", line.words().get(0).word()); } @Test public void testParsedLineIterator() { - ParsedLine line = LineParser.parseLine("foo bar"); + LineParser lineParser = new LineParser(); + ParsedLine line = lineParser.parseLine("foo bar"); ParsedLineIterator iterator = line.iterator(); int counter = 0; while(iterator.hasNextWord()) { @@ -208,12 +218,12 @@ else if(counter == 1) counter++; } - line = LineParser.parseLine(""); + line = lineParser.parseLine(""); iterator = line.iterator(); assertFalse(iterator.hasNextWord()); assertNull(iterator.pollWord()); - line = LineParser.parseLine("\\ foo ba bar"); + line = lineParser.parseLine("\\ foo ba bar"); iterator = line.iterator(); assertEquals(" foo", iterator.peekWord()); @@ -227,7 +237,7 @@ else if(counter == 1) assertEquals("bar", iterator.pollWord()); assertTrue(iterator.finished()); - line = LineParser.parseLine("\\ foo ba bar"); + line = lineParser.parseLine("\\ foo ba bar"); iterator = line.iterator(); assertEquals('\\', iterator.pollChar()); assertEquals(' ', iterator.pollChar()); @@ -239,7 +249,7 @@ else if(counter == 1) assertEquals('r', iterator.pollChar()); assertTrue(iterator.finished()); - line = LineParser.parseLine("\\ foo ba bar"); + line = lineParser.parseLine("\\ foo ba bar"); iterator = line.iterator(); assertEquals(" foo", iterator.pollWord()); @@ -247,7 +257,8 @@ else if(counter == 1) @Test public void testParsedLineIterator2() { - ParsedLine line = LineParser.parseLine("foo bar"); + LineParser lineParser = new LineParser(); + ParsedLine line = lineParser.parseLine("foo bar"); ParsedLineIterator iterator = line.iterator(); assertEquals("foo bar", iterator.stringFromCurrentPosition()); @@ -256,7 +267,7 @@ public void testParsedLineIterator2() { assertEquals("bar", iterator.stringFromCurrentPosition()); assertEquals("bar", iterator.pollWord()); - line = LineParser.parseLine("command --opt1={ myProp1=99, myProp2=100} --opt2"); + line = lineParser.parseLine("command --opt1={ myProp1=99, myProp2=100} --opt2"); iterator = line.iterator(); assertEquals("command", iterator.pollWord()); assertEquals('-', iterator.peekChar()); @@ -265,7 +276,7 @@ public void testParsedLineIterator2() { assertEquals("--opt2", iterator.peekWord()); assertEquals(' ', iterator.peekChar()); - line = LineParser.parseLine("--headers={t=x; t=y}"); + line = lineParser.parseLine("--headers={t=x; t=y}"); iterator = line.iterator(); assertEquals("--headers={t=x;", iterator.pollWord()); assertEquals('t', iterator.peekChar()); @@ -275,7 +286,7 @@ public void testParsedLineIterator2() { assertFalse(iterator.hasNextWord()); assertNull("", iterator.pollWord()); - line = LineParser.parseLine("--headers={t=x; t=y}"); + line = lineParser.parseLine("--headers={t=x; t=y}"); iterator = line.iterator(); iterator.pollParsedWord(); iterator.updateIteratorPosition(4); @@ -283,7 +294,7 @@ public void testParsedLineIterator2() { assertEquals('\u0000', iterator.pollChar()); assertNull("", iterator.pollWord()); - line = LineParser.parseLine("--headers={t=x; t=y}"); + line = lineParser.parseLine("--headers={t=x; t=y}"); iterator = line.iterator(); iterator.pollParsedWord(); iterator.updateIteratorPosition(40); @@ -291,10 +302,24 @@ public void testParsedLineIterator2() { assertEquals('\u0000', iterator.pollChar()); assertNull("", iterator.pollWord()); - line = LineParser.parseLine("--headers={t=x; t=y}"); + line = lineParser.parseLine("--headers={t=x; t=y}"); iterator = line.iterator(); iterator.updateIteratorPosition(20); assertNull(iterator.peekWord()); } + @Test + public void testCurlyBrackets() { + LineParser lineParser = new LineParser(); + ParsedLine line = lineParser.parseLine("foo bar {baz 12345} ", 19, true); + assertEquals("foo", line.words().get(0).word()); + assertEquals(0, line.words().get(0).lineIndex()); + assertEquals("bar", line.words().get(1).word()); + assertEquals(4, line.words().get(1).lineIndex()); + assertEquals("{baz 12345}", line.words().get(2).word()); + assertEquals(8, line.words().get(2).lineIndex()); + assertEquals("{baz 12345}", line.selectedWord().word()); + assertEquals(11, line.wordCursor()); + } + }
b58a646039f2b8830118be3bb6378bf534256291
hbase
HBASE-1816 Master rewrite; should have removed- safe-mode from regionserver-side too -- Needed to remove the wait up in top- of flush and compactions threads-- used to wait on safe mode... was stuck- there...--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@830844 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/CompactSplitThread.java b/src/java/org/apache/hadoop/hbase/regionserver/CompactSplitThread.java index 5e0890f1d368..96ec15cd35a8 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/CompactSplitThread.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/CompactSplitThread.java @@ -70,13 +70,6 @@ public CompactSplitThread(HRegionServer server) { @Override public void run() { - while (!this.server.isStopRequested()) { - try { - Thread.sleep(this.frequency); - } catch (InterruptedException ex) { - continue; - } - } int count = 0; while (!this.server.isStopRequested()) { HRegion r = null; diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java index 5f74b9c9dded..c5855ce46c48 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java @@ -202,9 +202,6 @@ public class HRegionServer implements HConstants, HRegionInterface, // eclipse warning when accessed by inner classes protected volatile HLog hlog; LogRoller hlogRoller; - - // limit compactions while starting up - CompactionLimitThread compactionLimitThread; // flag set after we're done setting up server threads (used for testing) protected volatile boolean isOnline; @@ -858,48 +855,6 @@ protected boolean checkFileSystem() { return this.fsOk; } - /** - * Thread that gradually ups compaction limit. - */ - private class CompactionLimitThread extends Thread { - protected CompactionLimitThread() {} - - @Override - public void run() { - // Slowly increase per-cycle compaction limit, finally setting it to - // unlimited (-1) - int compactionCheckInterval = - conf.getInt("hbase.regionserver.thread.splitcompactcheckfrequency", - 20 * 1000); - final int limitSteps[] = { - 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, - 3, 3, 3, 3, 3, 3, 3, 3, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - -1 - }; - for (int i = 0; i < limitSteps.length; i++) { - // Just log changes. - if (compactSplitThread.getLimit() != limitSteps[i] && - LOG.isDebugEnabled()) { - LOG.debug("setting compaction limit to " + limitSteps[i]); - } - compactSplitThread.setLimit(limitSteps[i]); - try { - Thread.sleep(compactionCheckInterval); - } catch (InterruptedException ex) { - // unlimit compactions before exiting - compactSplitThread.setLimit(-1); - if (LOG.isDebugEnabled()) { - LOG.debug(this.getName() + " exiting on interrupt"); - } - return; - } - } - LOG.info("compactions no longer limited"); - } - } - /* * Thread to shutdown the region server in an orderly manner. This thread * is registered as a shutdown hook in the HRegionServer constructor and is @@ -1130,10 +1085,6 @@ public void uncaughtException(Thread t, Throwable e) { } } - this.compactionLimitThread = new CompactionLimitThread(); - Threads.setDaemonThreadRunning(this.compactionLimitThread, n + - ".compactionLimitThread", handler); - // Start Server. This service is like leases in that it internally runs // a thread. this.server.start(); @@ -2083,7 +2034,7 @@ public InfoServer getInfoServer() { * @return true if a stop has been requested. */ public boolean isStopRequested() { - return stopRequested.get(); + return this.stopRequested.get(); } /** diff --git a/src/java/org/apache/hadoop/hbase/regionserver/MemStoreFlusher.java b/src/java/org/apache/hadoop/hbase/regionserver/MemStoreFlusher.java index 9512981e7cff..23aa3096d20d 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/MemStoreFlusher.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/MemStoreFlusher.java @@ -133,16 +133,9 @@ static long getMemStoreLimit(final long max, final float limit, @Override public void run() { while (!this.server.isStopRequested()) { - try { - Thread.sleep(threadWakeFrequency); - } catch (InterruptedException ex) { - continue; - } - } - while (!server.isStopRequested()) { HRegion r = null; try { - r = flushQueue.poll(threadWakeFrequency, TimeUnit.MILLISECONDS); + r = this.flushQueue.poll(this.threadWakeFrequency, TimeUnit.MILLISECONDS); if (r == null) { continue; } @@ -162,8 +155,8 @@ public void run() { } } } - regionsInQueue.clear(); - flushQueue.clear(); + this.regionsInQueue.clear(); + this.flushQueue.clear(); LOG.info(getName() + " exiting"); } diff --git a/src/test/org/apache/hadoop/hbase/regionserver/wal/TestLogRolling.java b/src/test/org/apache/hadoop/hbase/regionserver/wal/TestLogRolling.java index e6294d285df3..880391a5a632 100644 --- a/src/test/org/apache/hadoop/hbase/regionserver/wal/TestLogRolling.java +++ b/src/test/org/apache/hadoop/hbase/regionserver/wal/TestLogRolling.java @@ -99,7 +99,6 @@ protected void preHBaseClusterSetup() { private void startAndWriteData() throws Exception { // When the META table can be opened, the region servers are running new HTable(conf, HConstants.META_TABLE_NAME); - this.server = cluster.getRegionThreads().get(0).getRegionServer(); this.log = server.getLog(); @@ -109,15 +108,12 @@ private void startAndWriteData() throws Exception { HBaseAdmin admin = new HBaseAdmin(conf); admin.createTable(desc); HTable table = new HTable(conf, tableName); - for (int i = 1; i <= 256; i++) { // 256 writes should cause 8 log rolls Put put = new Put(Bytes.toBytes("row" + String.format("%1$04d", i))); put.add(HConstants.CATALOG_FAMILY, null, value); table.put(put); - if (i % 32 == 0) { // After every 32 writes sleep to let the log roller run - try { Thread.sleep(2000); } catch (InterruptedException e) { @@ -126,14 +122,14 @@ private void startAndWriteData() throws Exception { } } } - + /** * Tests that logs are deleted * * @throws Exception */ public void testLogRolling() throws Exception { - tableName = getName(); + this.tableName = getName(); try { startAndWriteData(); LOG.info("after writing there are " + log.getNumLogFiles() + " log files"); @@ -158,5 +154,4 @@ public void testLogRolling() throws Exception { throw e; } } - -} +} \ No newline at end of file
386e39f4a2b3112cbbc06bcde6483f1cebaa4734
kotlin
Fixed KT-1797 No completion for nested class name- in extension function definition-- -KT-1797 Fixed-
c
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.kt b/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.kt index c878f009e48ec..a624ef398b15c 100644 --- a/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.kt +++ b/idea/src/org/jetbrains/jet/plugin/completion/JetCompletionContributor.kt @@ -27,19 +27,20 @@ import org.jetbrains.jet.lang.psi.JetExpression import org.jetbrains.jet.lang.psi.JetFile import org.jetbrains.jet.lexer.JetTokens import org.jetbrains.jet.plugin.completion.smart.SmartCompletion -import org.jetbrains.jet.plugin.references.JetSimpleNameReference import com.intellij.patterns.PsiJavaPatterns.elementType import com.intellij.patterns.PsiJavaPatterns.psiElement -import com.intellij.patterns.PsiElementPattern import com.intellij.psi.PsiElement +import com.intellij.psi.PsiComment +import com.intellij.psi.PsiWhiteSpace +import org.jetbrains.jet.lang.psi.JetTypeReference public class JetCompletionContributor : CompletionContributor() { private val AFTER_NUMBER_LITERAL = psiElement().afterLeafSkipping(psiElement().withText(""), psiElement().withElementType(elementType().oneOf(JetTokens.FLOAT_LITERAL, JetTokens.INTEGER_LITERAL))) - private val EXTENSION_RECEIVER_TYPE_DUMMY_IDENTIFIER: String = "KotlinExtensionDummy.fake() {}" // A way to add reference into file at completion place - private val EXTENSION_RECEIVER_TYPE_ACTIVATION_PATTERN: PsiElementPattern.Capture<PsiElement> = PlatformPatterns.psiElement().afterLeaf(JetTokens.FUN_KEYWORD.toString(), JetTokens.VAL_KEYWORD.toString(), JetTokens.VAR_KEYWORD.toString()) + private val EXTENSION_RECEIVER_TYPE_DUMMY_IDENTIFIER = "KotlinExtensionDummy.fake() {}" // A way to add reference into file at completion place + private val EXTENSION_RECEIVER_TYPE_ACTIVATION_PATTERN = psiElement().afterLeaf(JetTokens.FUN_KEYWORD.toString(), JetTokens.VAL_KEYWORD.toString(), JetTokens.VAR_KEYWORD.toString()) ;{ val provider = object : CompletionProvider<CompletionParameters>() { @@ -57,6 +58,7 @@ public class JetCompletionContributor : CompletionContributor() { val offset = context.getStartOffset() val tokenBefore = psiFile.findElementAt(Math.max(0, offset - 1)) + val dummyIdentifier = when { context.getCompletionType() == CompletionType.SMART -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" // add '$' to ignore context after the caret @@ -64,6 +66,8 @@ public class JetCompletionContributor : CompletionContributor() { EXTENSION_RECEIVER_TYPE_ACTIVATION_PATTERN.accepts(tokenBefore) -> EXTENSION_RECEIVER_TYPE_DUMMY_IDENTIFIER + tokenBefore != null && isExtensionReceiverAfterDot(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "." + else -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED } context.setDummyIdentifier(dummyIdentifier) @@ -102,6 +106,25 @@ public class JetCompletionContributor : CompletionContributor() { } } + private val declarationKeywords = setOf(JetTokens.FUN_KEYWORD, JetTokens.VAL_KEYWORD, JetTokens.VAR_KEYWORD) + + private fun isExtensionReceiverAfterDot(tokenBefore: PsiElement): Boolean { + var prev = tokenBefore.getPrevSibling() + if (tokenBefore.getNode()!!.getElementType() != JetTokens.DOT) { + if (prev == null || prev!!.getNode()!!.getElementType() != JetTokens.DOT) return false + prev = prev!!.getPrevSibling() + } + + while (prev != null) { + if (prev!!.getNode()!!.getElementType() in declarationKeywords) { + return true + } + if (prev !is PsiComment && prev !is PsiWhiteSpace && prev !is JetTypeReference) return false + prev = prev!!.getPrevSibling() + } + return false + } + private fun performCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val position = parameters.getPosition() if (position.getContainingFile() !is JetFile) return diff --git a/idea/testData/completion/basic/common/NestedClassNameForExtension.kt b/idea/testData/completion/basic/common/NestedClassNameForExtension.kt new file mode 100644 index 0000000000000..929b6c57652d2 --- /dev/null +++ b/idea/testData/completion/basic/common/NestedClassNameForExtension.kt @@ -0,0 +1,8 @@ +class Test { + public class Nested +} + +fun Test.<caret> +} + +// EXIST: Nested diff --git a/idea/testData/completion/basic/common/NestedClassNameForExtension2.kt b/idea/testData/completion/basic/common/NestedClassNameForExtension2.kt new file mode 100644 index 0000000000000..f2a55c674b56c --- /dev/null +++ b/idea/testData/completion/basic/common/NestedClassNameForExtension2.kt @@ -0,0 +1,8 @@ +class Test { + public class Nested +} + +fun Test.N<caret> +} + +// EXIST: Nested diff --git a/idea/tests/org/jetbrains/jet/completion/JSBasicCompletionTestGenerated.java b/idea/tests/org/jetbrains/jet/completion/JSBasicCompletionTestGenerated.java index a46ed07b0c72a..14eacda04a7f0 100644 --- a/idea/tests/org/jetbrains/jet/completion/JSBasicCompletionTestGenerated.java +++ b/idea/tests/org/jetbrains/jet/completion/JSBasicCompletionTestGenerated.java @@ -334,6 +334,16 @@ public void testNamedObject() throws Exception { doTest("idea/testData/completion/basic/common/NamedObject.kt"); } + @TestMetadata("NestedClassNameForExtension.kt") + public void testNestedClassNameForExtension() throws Exception { + doTest("idea/testData/completion/basic/common/NestedClassNameForExtension.kt"); + } + + @TestMetadata("NestedClassNameForExtension2.kt") + public void testNestedClassNameForExtension2() throws Exception { + doTest("idea/testData/completion/basic/common/NestedClassNameForExtension2.kt"); + } + @TestMetadata("NoClassNameDuplication.kt") public void testNoClassNameDuplication() throws Exception { doTest("idea/testData/completion/basic/common/NoClassNameDuplication.kt"); diff --git a/idea/tests/org/jetbrains/jet/completion/JvmBasicCompletionTestGenerated.java b/idea/tests/org/jetbrains/jet/completion/JvmBasicCompletionTestGenerated.java index 828f934fdc4dd..ea4bcc1bf1012 100644 --- a/idea/tests/org/jetbrains/jet/completion/JvmBasicCompletionTestGenerated.java +++ b/idea/tests/org/jetbrains/jet/completion/JvmBasicCompletionTestGenerated.java @@ -334,6 +334,16 @@ public void testNamedObject() throws Exception { doTest("idea/testData/completion/basic/common/NamedObject.kt"); } + @TestMetadata("NestedClassNameForExtension.kt") + public void testNestedClassNameForExtension() throws Exception { + doTest("idea/testData/completion/basic/common/NestedClassNameForExtension.kt"); + } + + @TestMetadata("NestedClassNameForExtension2.kt") + public void testNestedClassNameForExtension2() throws Exception { + doTest("idea/testData/completion/basic/common/NestedClassNameForExtension2.kt"); + } + @TestMetadata("NoClassNameDuplication.kt") public void testNoClassNameDuplication() throws Exception { doTest("idea/testData/completion/basic/common/NoClassNameDuplication.kt");
f958ffcc8a52d92385cc29ab896eaf294d695815
orientdb
Fixed issue on browsing of entire cluster/class--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java index 8f898a1b469..a0ff55f2bf1 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java @@ -43,7 +43,7 @@ public ORecordIteratorCluster(final ODatabaseRecord<REC> iDatabase, final ODatab currentClusterId = iClusterId; rangeFrom = -1; rangeTo = -1; - clusterSize = database.countClusterElements(currentClusterId); + clusterSize = database.getStorage().getClusterLastEntryPosition(currentClusterId); } @Override
6a3f6b3b9a32d70c7b58bbbf40046497bc415931
intellij-community
Maven: escaping support in the resource- compiler (IDEADEV-35524)--
c
https://github.com/JetBrains/intellij-community
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java index 64d18ee679890..2d9a8b2893f2a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java @@ -11,6 +11,7 @@ import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; @@ -132,10 +133,15 @@ protected void run(Result<ProcessingItem[]> resultObject) throws Throwable { if (mavenProject == null) continue; Properties properties = loadFilters(context, mavenProject); + String escapeString = mavenProject.findPluginConfigurationValue("org.apache.maven.plugins", + "maven-resources-plugin", + "escapeString"); + if (escapeString == null) escapeString = "\\"; + long propertiesHashCode = calculateHashCode(properties); - collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, false, itemsToProcess); - collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, true, itemsToProcess); + collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, escapeString, false, itemsToProcess); + collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, escapeString, true, itemsToProcess); collectItemsToDelete(eachModule, itemsToProcess, filesToDelete); } if (!filesToDelete.isEmpty()) { @@ -181,6 +187,7 @@ private void collectProcessingItems(Module module, CompileContext context, Properties properties, long propertiesHashCode, + String escapeString, boolean tests, List<ProcessingItem> result) { String outputDir = CompilerPaths.getModuleOutputPath(module, tests); @@ -206,6 +213,7 @@ private void collectProcessingItems(Module module, each.isFiltering(), properties, propertiesHashCode, + escapeString, result, context.getProgressIndicator()); } @@ -232,6 +240,7 @@ private void collectProcessingItems(Module module, boolean isSourceRootFiltered, Properties properties, long propertiesHashCode, + String escapeString, List<ProcessingItem> result, ProgressIndicator indicator) { indicator.checkCanceled(); @@ -247,6 +256,7 @@ private void collectProcessingItems(Module module, isSourceRootFiltered, properties, propertiesHashCode, + escapeString, result, indicator); } @@ -255,7 +265,13 @@ private void collectProcessingItems(Module module, if (!MavenUtil.isIncluded(relPath, includes, excludes)) continue; String outputPath = outputDir + "/" + relPath; - result.add(new MyProcessingItem(module, eachSourceFile, outputPath, isSourceRootFiltered, properties, propertiesHashCode)); + result.add(new MyProcessingItem(module, + eachSourceFile, + outputPath, + isSourceRootFiltered, + properties, + propertiesHashCode, + escapeString)); } } } @@ -318,7 +334,7 @@ public ProcessingItem[] process(final CompileContext context, ProcessingItem[] i String charset = getCharsetName(sourceVirtualFile); String text = new String(FileUtil.loadFileBytes(sourceFile), charset); - text = PropertyResolver.resolve(eachItem.getModule(), text, eachItem.getProperties()); + text = PropertyResolver.resolve(eachItem.getModule(), text, eachItem.getProperties(), eachItem.getEscapeString()); FileUtil.writeToFile(outputFile, text.getBytes(charset)); } else { @@ -382,6 +398,7 @@ private static class MyProcessingItem implements ProcessingItem { private final String myOutputPath; private final boolean myFiltered; private final Properties myProperties; + private String myEscapeString; private final MyValididtyState myState; public MyProcessingItem(Module module, @@ -389,13 +406,15 @@ public MyProcessingItem(Module module, String outputPath, boolean isFiltered, Properties properties, - long propertiesHashCode) { + long propertiesHashCode, + String escapeString) { myModule = module; mySourceFile = sourceFile; myOutputPath = outputPath; myFiltered = isFiltered; myProperties = properties; - myState = new MyValididtyState(mySourceFile, isFiltered, propertiesHashCode); + myEscapeString = escapeString; + myState = new MyValididtyState(sourceFile, isFiltered, propertiesHashCode, escapeString); } @NotNull @@ -419,6 +438,10 @@ public Properties getProperties() { return myProperties; } + public String getEscapeString() { + return myEscapeString; + } + public ValidityState getValidityState() { return myState; } @@ -445,19 +468,21 @@ private static class MyValididtyState implements ValidityState { TimestampValidityState myTimestampState; private boolean myFiltered; private long myPropertiesHashCode; + private String myEscapeString; public static MyValididtyState load(DataInput in) throws IOException { - return new MyValididtyState(TimestampValidityState.load(in), in.readBoolean(), in.readLong()); + return new MyValididtyState(TimestampValidityState.load(in), in.readBoolean(), in.readLong(), in.readUTF()); } - public MyValididtyState(VirtualFile file, boolean isFiltered, long propertiesHashCode) { - this(new TimestampValidityState(file.getTimeStamp()), isFiltered, propertiesHashCode); + public MyValididtyState(VirtualFile file, boolean isFiltered, long propertiesHashCode, String escapeString) { + this(new TimestampValidityState(file.getTimeStamp()), isFiltered, propertiesHashCode, escapeString); } - private MyValididtyState(TimestampValidityState timestampState, boolean isFiltered, long propertiesHashCode) { + private MyValididtyState(TimestampValidityState timestampState, boolean isFiltered, long propertiesHashCode, String escapeString) { myTimestampState = timestampState; myFiltered = isFiltered; myPropertiesHashCode = propertiesHashCode; + myEscapeString = escapeString; } public boolean equalsTo(ValidityState otherState) { @@ -465,13 +490,15 @@ public boolean equalsTo(ValidityState otherState) { MyValididtyState state = (MyValididtyState)otherState; return myTimestampState.equalsTo(state.myTimestampState) && myFiltered == state.myFiltered - && myPropertiesHashCode == state.myPropertiesHashCode; + && myPropertiesHashCode == state.myPropertiesHashCode + && Comparing.strEqual(myEscapeString, state.myEscapeString); } public void save(DataOutput out) throws IOException { myTimestampState.save(out); out.writeBoolean(myFiltered); out.writeLong(myPropertiesHashCode); + out.writeUTF(myEscapeString); } } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java index b213b54337ad4..2210fe5da5a49 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java @@ -23,11 +23,11 @@ public class PropertyResolver { private static final Pattern PATTERN = Pattern.compile("\\$\\{([^}]+)\\}"); - public static String resolve(Module module, String text, Properties additionalProperties) { + public static String resolve(Module module, String text, Properties additionalProperties, String escapeString) { MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject()); MavenProjectModel mavenProject = manager.findProject(module); if (mavenProject == null) return text; - return doResolve(text, mavenProject, additionalProperties, new Stack<String>()); + return doResolve(text, mavenProject, additionalProperties, escapeString, new Stack<String>()); } public static String resolve(GenericDomValue<String> value) { @@ -44,7 +44,7 @@ public static String resolve(String text, DomFileElement<MavenModel> dom) { MavenProjectModel mavenProject = manager.findProject(file); if (mavenProject == null) return text; - return doResolve(text, mavenProject, collectPropertiesFromDOM(mavenProject, dom), new Stack<String>()); + return doResolve(text, mavenProject, collectPropertiesFromDOM(mavenProject, dom), null, new Stack<String>()); } private static Properties collectPropertiesFromDOM(MavenProjectModel project, DomFileElement<MavenModel> dom) { @@ -71,18 +71,38 @@ private static void collectPropertiesFromDOM(Properties result, MavenProperties } } - private static String doResolve(String text, MavenProjectModel project, Properties additionalProperties, Stack<String> resolutionStack) { + private static String doResolve(String text, + MavenProjectModel project, + Properties additionalProperties, + String escapeString, + Stack<String> resolutionStack) { Matcher matcher = PATTERN.matcher(text); StringBuffer buff = new StringBuffer(); + StringBuffer dummy = new StringBuffer(); + int last = 0; while (matcher.find()) { String propText = matcher.group(); String propName = matcher.group(1); + + int tempLast = last; + last = matcher.start() + propText.length(); + + if (escapeString != null) { + int pos = matcher.start(); + if (pos > escapeString.length() && text.substring(pos - escapeString.length(), pos).equals(escapeString)) { + buff.append(text.substring(tempLast, pos - escapeString.length())); + buff.append(propText); + matcher.appendReplacement(dummy, ""); + continue; + } + } + String resolved = doResolveProperty(propName, project, additionalProperties); if (resolved == null) resolved = propText; if (!resolved.equals(propText) && !resolutionStack.contains(propName)) { resolutionStack.push(propName); - resolved = doResolve(resolved, project, additionalProperties, resolutionStack); + resolved = doResolve(resolved, project, additionalProperties, escapeString, resolutionStack); resolutionStack.pop(); } matcher.appendReplacement(buff, Matcher.quoteReplacement(resolved)); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java index 397e2092d1d59..3ac9b58a94c5c 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java @@ -456,6 +456,71 @@ public void testPluginDirectoriesFiltering() throws Exception { assertResult("target/classes/file2.properties", "value=${xxx}"); } + public void testEscapingFiltering() throws Exception { + createProjectSubFile("filters/filter.properties", "xxx=value"); + createProjectSubFile("resources/file.properties", + "value1=\\${xxx}\n" + + "value2=${xxx}\n"); + + importProject("<groupId>test</groupId>" + + "<artifactId>project</artifactId>" + + "<version>1</version>" + + + "<build>" + + " <filters>" + + " <filter>filters/filter.properties</filter>" + + " </filters>" + + " <resources>" + + " <resource>" + + " <directory>resources</directory>" + + " <filtering>true</filtering>" + + " </resource>" + + " </resources>" + + "</build>"); + + compileModules("project"); + assertResult("target/classes/file.properties", + "value1=${xxx}\n" + + "value2=value\n"); + } + + public void testCustomEscapingFiltering() throws Exception { + createProjectSubFile("filters/filter.properties", "xxx=value"); + createProjectSubFile("resources/file.properties", + "value1=^${xxx}\n" + + "value2=\\${xxx}\n"); + + importProject("<groupId>test</groupId>" + + "<artifactId>project</artifactId>" + + "<version>1</version>" + + + "<build>" + + " <filters>" + + " <filter>filters/filter.properties</filter>" + + " </filters>" + + " <resources>" + + " <resource>" + + " <directory>resources</directory>" + + " <filtering>true</filtering>" + + " </resource>" + + " </resources>" + + " <plugins>" + + " <plugin>" + + " <groupId>org.apache.maven.plugins</groupId>" + + " <artifactId>maven-resources-plugin</artifactId>" + + " <configuration>" + + " <escapeString>^</escapeString>" + + " </configuration>" + + " </plugin>" + + " </plugins>" + + "</build>"); + + compileModules("project"); + assertResult("target/classes/file.properties", + "value1=${xxx}\n" + + "value2=\\value\n"); + } + private void assertResult(String relativePath, String content) throws IOException { assertResult(myProjectPom, relativePath, content); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java index 03b9c437adf41..18b592f93f67f 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java @@ -12,6 +12,7 @@ import org.jetbrains.idea.maven.dom.model.MavenModel; import java.io.File; +import java.util.Properties; public class PropertyResolverTest extends MavenImportingTestCase { public void testResolvingProjectAttributes() throws Exception { @@ -229,6 +230,21 @@ public void testUncomittedProperties() throws Exception { assertEquals("value", resolve("${uncomitted}", myProjectPom)); } + public void testEscaping() throws Exception { + importProject("<groupId>test</groupId>" + + "<artifactId>project</artifactId>" + + "<version>1</version>"); + + assertEquals("foo ^project bar", + PropertyResolver.resolve(getModule("project"), "foo ^${project.artifactId} bar", new Properties(), "/")); + assertEquals("foo ${project.artifactId} bar", + PropertyResolver.resolve(getModule("project"), "foo ^^${project.artifactId} bar", new Properties(), "^^")); + assertEquals("project ${project.artifactId} project ${project.artifactId}", + PropertyResolver.resolve(getModule("project"), + "${project.artifactId} ^${project.artifactId} ${project.artifactId} ^${project.artifactId}", + new Properties(), "^")); + } + private String resolve(String text, VirtualFile f) { Document d = FileDocumentManager.getInstance().getDocument(f); PsiFile psi = PsiDocumentManager.getInstance(myProject).getPsiFile(d);
e25dcdd6b12a965b6eca0c69c847fd0316b1c455
camel
CAMEL-1255: Fixed missing classes in .jar - osgi- export stuff--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@734408 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/components/camel-jpa/pom.xml b/components/camel-jpa/pom.xml index 4f1fdbc49b782..a2a513db7aa56 100644 --- a/components/camel-jpa/pom.xml +++ b/components/camel-jpa/pom.xml @@ -35,8 +35,9 @@ <properties> <camel.osgi.export.pkg>org.apache.camel.component.jpa.*, - org.apache.camel.processor.idempotent.jpa.* - org.apache.camel.processor.interceptor.*</camel.osgi.export.pkg> + org.apache.camel.processor.idempotent.jpa.*, + org.apache.camel.processor.interceptor.* + </camel.osgi.export.pkg> </properties> <dependencies> diff --git a/components/camel-jpa/src/main/java/org/apache/camel/processor/interceptor/JpaTraceEventMessage.java b/components/camel-jpa/src/main/java/org/apache/camel/processor/interceptor/JpaTraceEventMessage.java index 504079977c49b..bf6b0b1058f9e 100644 --- a/components/camel-jpa/src/main/java/org/apache/camel/processor/interceptor/JpaTraceEventMessage.java +++ b/components/camel-jpa/src/main/java/org/apache/camel/processor/interceptor/JpaTraceEventMessage.java @@ -175,7 +175,7 @@ public void setCausedByException(String causedByException) { @Override public String toString() { - return "TraceEventMessage[" + exchangeId + "] on node: " + toNode; + return "TraceEventMessage[" + getExchangeId() + "] on node: " + getToNode(); } } diff --git a/examples/camel-example-bam/README.txt b/examples/camel-example-bam/README.txt index e0af2baf529a7..cb7f6ceee0fe6 100644 --- a/examples/camel-example-bam/README.txt +++ b/examples/camel-example-bam/README.txt @@ -40,11 +40,10 @@ You can see the BAM activies defined in src/main/java/org/apache/camel/example/bam/MyActivites.java In the HSQL Database Explorer type - select * from activitystate + select * from camel_activitystate to see the states of the activities. Notice that one activity never receives its expected message and when it's overdue Camel reports this as an error. - To stop the example hit ctrl + c To use log4j as the logging framework add this to the pom.xml:
0784391f2ef571fd2a6e184d6b73eca75abec9ce
Vala
sqlite3: add methods to get the source of data in a query result
a
https://github.com/GNOME/vala/
diff --git a/vapi/sqlite3.vapi b/vapi/sqlite3.vapi index 3b680e6707..4ae8cd31d1 100644 --- a/vapi/sqlite3.vapi +++ b/vapi/sqlite3.vapi @@ -365,6 +365,9 @@ namespace Sqlite { public int column_type (int col); public unowned Value column_value (int col); public unowned string column_name (int index); + public unowned string column_database_name (int col); + public unowned string column_table_name (int col); + public unowned string column_origin_name (int col); public unowned string sql (); }
05ee5877e9c07e4dce972f84e0741741fefc8efb
drools
Fixed bug with "disconnected" factHandles- (JBRULES-3187) and added a test to verify that I fixed the bug!!--
c
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandlesCommand.java b/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandlesCommand.java index 39a1dd554be..4c3d4916378 100644 --- a/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandlesCommand.java +++ b/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandlesCommand.java @@ -45,6 +45,9 @@ public GetFactHandlesCommand(ObjectFilter filter, boolean disconnected) { this.filter = filter; this.disconnected = disconnected; } + public GetFactHandlesCommand(boolean disconnected) { + this.disconnected = disconnected; + } public Collection<FactHandle> execute(Context context) { StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession(); @@ -57,8 +60,11 @@ public Collection<FactHandle> execute(Context context) { handle.disconnect(); disconnectedFactHandles.add(handle); } + return disconnectedFactHandles; + } + else { + return ksession.getFactHandles( this.filter ); } - return disconnectedFactHandles; } else { Collection<InternalFactHandle> factHandles = ksession.getFactHandles( ); if(factHandles != null && disconnected){ @@ -67,8 +73,11 @@ public Collection<FactHandle> execute(Context context) { handle.disconnect(); disconnectedFactHandles.add(handle); } + return disconnectedFactHandles; + } + else { + return ksession.getFactHandles(); } - return disconnectedFactHandles; } } diff --git a/drools-core/src/test/java/org/drools/comand/runtime/rule/GetFactHandlesCommandTest.java b/drools-core/src/test/java/org/drools/comand/runtime/rule/GetFactHandlesCommandTest.java new file mode 100644 index 00000000000..a77e722bf39 --- /dev/null +++ b/drools-core/src/test/java/org/drools/comand/runtime/rule/GetFactHandlesCommandTest.java @@ -0,0 +1,223 @@ +package org.drools.comand.runtime.rule; + +import static org.junit.Assert.*; + +import java.lang.ref.Reference; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Random; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.drools.KnowledgeBase; +import org.drools.KnowledgeBaseFactory; +import org.drools.command.impl.ContextImpl; +import org.drools.command.impl.DefaultCommandService; +import org.drools.command.impl.KnowledgeCommandContext; +import org.drools.command.runtime.rule.GetFactHandlesCommand; +import org.drools.common.InternalFactHandle; +import org.drools.runtime.StatefulKnowledgeSession; +import org.drools.runtime.rule.FactHandle; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +@SuppressWarnings("unchecked") +public class GetFactHandlesCommandTest { + + private StatefulKnowledgeSession ksession; + private DefaultCommandService commandService; + private Random random = new Random(); + + @Before + public void setup() { + KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + ksession = kbase.newStatefulKnowledgeSession(); + KnowledgeCommandContext kContext + = new KnowledgeCommandContext( new ContextImpl( "ksession", null ), null, null, this.ksession, null ); + commandService = new DefaultCommandService(kContext); + + } + + @After + public void cleanUp() { + ksession.dispose(); + } + + @Test + public void getEmptyFactHandlesTest() { + GetFactHandlesCommand command = new GetFactHandlesCommand(); + Object result = commandService.execute(command); + if( result instanceof Collection<?> ) { + assertNotNull(result); + assertTrue(((Collection<?>) result).isEmpty()); + } + else { + fail("result of command was NOT a collection of FactHandles"); + } + } + + @Test + public void getOneFactHandleTest() { + String randomFact = "" + random.nextLong(); + ksession.insert(randomFact); + GetFactHandlesCommand command = new GetFactHandlesCommand(); + Object result = commandService.execute(command); + + verifyThatCollectionContains1FactHandleWithThisFact(randomFact, result); + } + + @Test + public void getMultipleFactHandleTest() { + HashSet<String> factSet = new HashSet<String>(); + int numFacts = 4; + for( int i = 0; i < numFacts; ++i ) { + factSet.add("" + random.nextInt()); + } + for( String fact : factSet ) { + ksession.insert(fact); + } + + GetFactHandlesCommand command = new GetFactHandlesCommand(); + Object result = commandService.execute(command); + + verifyThatCollectionContainsTheseFactHandle(factSet, result); + } + + @Test + public void getEmptyDisconnectedFactHandlesTest() { + GetFactHandlesCommand command = new GetFactHandlesCommand(true); + Object result = commandService.execute(command); + if( result instanceof Collection<?> ) { + assertNotNull(result); + assertTrue(((Collection<?>) result).isEmpty()); + } + else { + fail("result of command was NOT a collection of FactHandles"); + } + } + + @Test + public void getOneDisconnectedFactHandleTest() { + System.out.println( Thread.currentThread().getStackTrace()[1].getMethodName() ); + String randomFact = "" + random.nextLong(); + ksession.insert(randomFact); + + // Retrieve and verify fact handle collections + GetFactHandlesCommand command = new GetFactHandlesCommand(false); + Object result = commandService.execute(command); + verifyThatCollectionContains1FactHandleWithThisFact(randomFact, result); + FactHandle factHandle = (FactHandle) ((Collection<FactHandle>) result).toArray()[0]; + + command = new GetFactHandlesCommand(false); + result = commandService.execute(command); + verifyThatCollectionContains1FactHandleWithThisFact(randomFact, result); + FactHandle connectedFactHandle = (FactHandle) ((Collection<FactHandle>) result).toArray()[0]; + + command = new GetFactHandlesCommand(true); + result = commandService.execute(command); + verifyThatCollectionContains1FactHandleWithThisFact(randomFact, result); + FactHandle disconnectedFactHandle = (FactHandle) ((Collection<FactHandle>) result).toArray()[0]; + + // Test fact handle collections + assertTrue( factHandle == connectedFactHandle ); + assertTrue( ! (factHandle == disconnectedFactHandle) ); + } + + @Test + public void getMultipleDisconnectedFactHandleTest() { + System.out.println( "\nTest: " + Thread.currentThread().getStackTrace()[1].getMethodName() ); + HashSet<String> factSet = new HashSet<String>(); + int numFacts = 4; + for( int i = 0; i < numFacts; ++i ) { + factSet.add("" + random.nextInt()); + } + for( String fact : factSet ) { + ksession.insert(fact); + } + + GetFactHandlesCommand command = new GetFactHandlesCommand(false); + Object result = commandService.execute(command); + verifyThatCollectionContainsTheseFactHandle(factSet, result); + Collection<FactHandle> factHandles = ((Collection<FactHandle>) result); + + command = new GetFactHandlesCommand(false); + result = commandService.execute(command); + verifyThatCollectionContainsTheseFactHandle(factSet, result); + Collection<FactHandle> connectedFactHandles = ((Collection<FactHandle>) result); + + command = new GetFactHandlesCommand(true); + result = commandService.execute(command); + verifyThatCollectionContainsTheseFactHandle(factSet, result); + Collection<FactHandle> disconnectedFactHandles = ((Collection<FactHandle>) result); + + // Test fact handle collections + HashSet<FactHandle> factHandlesCopy = new HashSet<FactHandle>(factHandles); + for( int i = 0; i < connectedFactHandles.size(); ++i ) { + for( Object connectedFact : connectedFactHandles ) { + Iterator<FactHandle> iter = factHandlesCopy.iterator(); + while(iter.hasNext() ) { + Object fact = iter.next(); + if( fact == connectedFact ) { + iter.remove(); + } + } + } + } + assertTrue( factHandlesCopy.isEmpty() ); + + for( int i = 0; i < disconnectedFactHandles.size(); ++i ) { + for( Object disconnectedFact : disconnectedFactHandles ) { + for( Object fact : factHandles ) { + assertTrue( ! (fact == disconnectedFact) ); + } + } + } + assertTrue( factHandles.size() == disconnectedFactHandles.size() ); + + } + + /** + * Helper methods + */ + private void verifyThatCollectionContains1FactHandleWithThisFact(String fact, Object collection) { + if( collection instanceof Collection<?> ) { + Collection<FactHandle> factHandles = null; + try { + factHandles = (Collection<FactHandle>) collection; + } + catch( Exception e ) { + fail( "Collection was not a Colleciton<FactHandle> " + e.getMessage()); + } + + assertTrue(! factHandles.isEmpty()); + assertTrue(factHandles.size() == 1); + InternalFactHandle factHandle = (InternalFactHandle) factHandles.toArray()[0]; + assertTrue(fact.equals(factHandle.getObject())); + } + else { + fail("result of command was NOT a collection of FactHandles"); + } + } + + private void verifyThatCollectionContainsTheseFactHandle(HashSet<String> factSet, Object collection) { + factSet = (HashSet<String>) factSet.clone(); + if( collection instanceof Collection<?> ) { + Collection<FactHandle> factHandles = (Collection<FactHandle>) collection; + assertTrue(! factHandles.isEmpty()); + assertTrue(factSet.size() + "inserted but only " + factHandles.size() + " facts retrieved", factHandles.size() == factSet.size()); + Object [] internalFactHandles = factHandles.toArray(); + for( int i = 0; i < internalFactHandles.length; ++i ) { + Object factObject = ((InternalFactHandle) internalFactHandles[i]).getObject(); + assertTrue(factSet.contains(factObject)); + factSet.remove(factObject); + } + assertTrue( "Additional facts found that weren't inserted.", factSet.isEmpty() ); + } + else { + fail("result of command was NOT a collection of FactHandles"); + } + } + +}
37653501dcfc08114bd23b6f4b9ec6f60b846b7a
Delta Spike
DELTASPIKE-365 add a boot(Map) method This is needed to startup some containers with initial properties if they support it.
c
https://github.com/apache/deltaspike
diff --git a/deltaspike/cdictrl/api/src/main/java/org/apache/deltaspike/cdise/api/CdiContainer.java b/deltaspike/cdictrl/api/src/main/java/org/apache/deltaspike/cdise/api/CdiContainer.java index 3b131afd0..62c789837 100644 --- a/deltaspike/cdictrl/api/src/main/java/org/apache/deltaspike/cdise/api/CdiContainer.java +++ b/deltaspike/cdictrl/api/src/main/java/org/apache/deltaspike/cdise/api/CdiContainer.java @@ -20,6 +20,7 @@ import javax.enterprise.inject.spi.BeanManager; +import java.util.Map; /** @@ -35,9 +36,9 @@ public interface CdiContainer { /** - * <b>Booting the CdiTestContainer will scan the whole classpath + * <p>Booting the CdiTestContainer will scan the whole classpath * for Beans and extensions available. - * The container might throw a DeploymentException or similar on startup.</b> + * The container might throw a DeploymentException or similar on startup.</p> * * <p><b>Note:</b> booting the container does <i>not</i> automatically * start all CDI Contexts! Depending on the underlying CDI container you @@ -46,6 +47,15 @@ public interface CdiContainer * {@link ContextControl#startContexts()}</p> */ void boot(); + + /** + * <p>Like {@link #boot()} but allows to pass in a configuration Map + * for the container.</p> + * <p>Please note that the configuration is container implementation dependent!</p> + * + * @param properties + */ + void boot(Map<?,?> properties); /** * This will shutdown the underlying CDI container and stop all contexts. diff --git a/deltaspike/cdictrl/impl-openejb/src/main/java/org/apache/deltaspike/cdise/openejb/OpenEjbContainerControl.java b/deltaspike/cdictrl/impl-openejb/src/main/java/org/apache/deltaspike/cdise/openejb/OpenEjbContainerControl.java index c23cd5db5..aa9dbe6c9 100644 --- a/deltaspike/cdictrl/impl-openejb/src/main/java/org/apache/deltaspike/cdise/openejb/OpenEjbContainerControl.java +++ b/deltaspike/cdictrl/impl-openejb/src/main/java/org/apache/deltaspike/cdise/openejb/OpenEjbContainerControl.java @@ -56,11 +56,17 @@ public BeanManager getBeanManager() @Override public synchronized void boot() + { + boot(null); + } + + @Override + public synchronized void boot(Map<?, ?> properties) { if (openEjbContainer == null) { // this immediately boots the container - openEjbContainer = EJBContainer.createEJBContainer(getConfiguration()); + openEjbContainer = EJBContainer.createEJBContainer(properties); // this magic code performs injection try diff --git a/deltaspike/cdictrl/impl-owb/src/main/java/org/apache/deltaspike/cdise/owb/OpenWebBeansContainerControl.java b/deltaspike/cdictrl/impl-owb/src/main/java/org/apache/deltaspike/cdise/owb/OpenWebBeansContainerControl.java index 9c45aea3e..7f1fa7164 100644 --- a/deltaspike/cdictrl/impl-owb/src/main/java/org/apache/deltaspike/cdise/owb/OpenWebBeansContainerControl.java +++ b/deltaspike/cdictrl/impl-owb/src/main/java/org/apache/deltaspike/cdise/owb/OpenWebBeansContainerControl.java @@ -26,6 +26,7 @@ import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; +import java.util.Map; import java.util.Set; import java.util.logging.Logger; @@ -67,6 +68,13 @@ public synchronized void boot() lifecycle.startApplication(mockServletContextEvent); } + @Override + public void boot(Map<?, ?> properties) + { + // we do not yet support any configuration. + boot(); + } + @Override public synchronized void shutdown() { diff --git a/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/WeldContainerControl.java b/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/WeldContainerControl.java index 65b8fd660..7c1a28aa1 100644 --- a/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/WeldContainerControl.java +++ b/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/WeldContainerControl.java @@ -26,6 +26,7 @@ import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; +import java.util.Map; import java.util.Set; import java.util.logging.Logger; @@ -64,6 +65,14 @@ public synchronized void boot() weldContainer = weld.initialize(); } + @Override + public void boot(Map<?, ?> properties) + { + // no configuration yet. Perform default boot + + boot(); + } + @Override public synchronized void shutdown() {
eb5df87c7ec4d7f62873dcf29108ddc2abcd13ca
ReactiveX-RxJava
avoiding some synchronization on combineLatest--
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java index 382f8ba8aa..2d77c3d3ec 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java +++ b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.mockito.InOrder; @@ -125,17 +126,13 @@ private static class Aggregator<R> implements Func1<Observer<R>, Subscription> { private final FuncN<R> combineLatestFunction; private final AtomicBoolean running = new AtomicBoolean(true); - - // used as an internal lock for handling the latest values and the completed state of each observer + + // Stores how many observers have already completed + private final AtomicInteger numCompleted = new AtomicInteger(0); + + // Used as an internal lock for handling the latest values of each observer private final Object lockObject = new Object(); - /** - * Store when an observer completes. - * <p> - * Note that access to this set MUST BE SYNCHRONIZED via 'lockObject' above. - * */ - private final Set<CombineObserver<R, ?>> completed = new HashSet<CombineObserver<R, ?>>(); - /** * The latest value from each observer * <p> @@ -175,17 +172,14 @@ <T> void addObserver(CombineObserver<R, T> w) { * @param w The observer that has completed. */ <T> void complete(CombineObserver<R, T> w) { - synchronized(lockObject) { - // store that this CombineLatestObserver is completed - completed.add(w); - // if all CombineObservers are completed, we mark the whole thing as completed - if (completed.size() == observers.size()) { - if (running.get()) { - // mark ourselves as done - observer.onCompleted(); - // just to ensure we stop processing in case we receive more onNext/complete/error calls after this - running.set(false); - } + int completed = numCompleted.incrementAndGet(); + // if all CombineObservers are completed, we mark the whole thing as completed + if (completed == observers.size()) { + if (running.get()) { + // mark ourselves as done + observer.onCompleted(); + // just to ensure we stop processing in case we receive more onNext/complete/error calls after this + running.set(false); } } } @@ -228,14 +222,12 @@ <T> void next(CombineObserver<R, T> w, T arg) { // remember that this observer now has a latest value set hasLatestValue.add(w); - // if all observers in the 'observers' list have a value, invoke the combineLatestFunction - for (CombineObserver<R, ?> rw : observers) { - if (!hasLatestValue.contains(rw)) { - // we don't have a value yet for each observer to combine, so we don't have a combined value yet either - return; - } + if (hasLatestValue.size() < observers.size()) { + // we don't have a value yet for each observer to combine, so we don't have a combined value yet either + return; } - // if we get to here this means all the queues have data + + // if we get to here this means all the observers have a latest value int i = 0; for (CombineObserver<R, ?> _w : observers) { argsToCombineLatest[i++] = latestValue.get(_w);
06ae95a8dc8d497e4bc6e8af9dc2129555050638
Valadoc
libvaladoc: Add Struct.copy_function_cname, Struct.destroy_function_cname
a
https://github.com/GNOME/vala/
diff --git a/src/driver/0.14.x/treebuilder.vala b/src/driver/0.14.x/treebuilder.vala index c35de4c82d..6cbec291e0 100644 --- a/src/driver/0.14.x/treebuilder.vala +++ b/src/driver/0.14.x/treebuilder.vala @@ -287,6 +287,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { #endif } + private string? get_struct_destroy_function (Vala.Struct element) { +#if VALA_0_13_0 || VALA_0_13_1 + return element.get_destroy_function (); +#else + return Vala.CCodeBaseModule.get_ccode_destroy_function (element); +#endif + } + private string? get_free_function_name (Vala.Class element) { if (!element.is_compact) { return null; @@ -352,6 +360,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { #endif } + private string? get_copy_function (Vala.TypeSymbol sym) { +#if VALA_0_13_0 || VALA_0_13_1 + return sym.get_copy_function (); +#else + return Vala.CCodeBaseModule.get_ccode_copy_function (sym); +#endif + } + private string get_free_function (Vala.TypeSymbol sym) { #if VALA_0_13_0 || VALA_0_13_1 return sym.get_free_function (); @@ -1101,7 +1117,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { 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_free_function (element), is_basic_type, element); + 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); diff --git a/src/driver/0.16.x/treebuilder.vala b/src/driver/0.16.x/treebuilder.vala index b090d4905c..96cece0ffa 100644 --- a/src/driver/0.16.x/treebuilder.vala +++ b/src/driver/0.16.x/treebuilder.vala @@ -302,6 +302,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { return Vala.CCodeBaseModule.get_ccode_dup_function (sym); } + private string? get_copy_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_copy_function (sym); + } + + private string? get_destroy_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_destroy_function (sym); + } + private string? get_free_function (Vala.TypeSymbol sym) { return Vala.CCodeBaseModule.get_ccode_free_function (sym); } @@ -1009,7 +1017,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { 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_free_function (element), is_basic_type, element); + 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); diff --git a/src/driver/0.18.x/treebuilder.vala b/src/driver/0.18.x/treebuilder.vala index d536f4b1d5..c597f274d2 100644 --- a/src/driver/0.18.x/treebuilder.vala +++ b/src/driver/0.18.x/treebuilder.vala @@ -307,6 +307,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { return Vala.CCodeBaseModule.get_ccode_dup_function (sym); } + private string? get_copy_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_copy_function (sym); + } + + private string? get_destroy_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_destroy_function (sym); + } + private string? get_free_function (Vala.TypeSymbol sym) { return Vala.CCodeBaseModule.get_ccode_free_function (sym); } @@ -1025,7 +1033,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { 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_free_function (element), is_basic_type, element); + 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); diff --git a/src/driver/0.20.x/treebuilder.vala b/src/driver/0.20.x/treebuilder.vala index f9f8fef6f0..4deb224108 100644 --- a/src/driver/0.20.x/treebuilder.vala +++ b/src/driver/0.20.x/treebuilder.vala @@ -299,6 +299,14 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { return Vala.CCodeBaseModule.get_ccode_dup_function (sym); } + private string? get_copy_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_copy_function (sym); + } + + private string? get_destroy_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_destroy_function (sym); + } + private string? get_free_function (Vala.TypeSymbol sym) { return Vala.CCodeBaseModule.get_ccode_free_function (sym); } @@ -987,7 +995,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { 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_free_function (element), is_basic_type, element); + 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); diff --git a/src/libvaladoc/api/struct.vala b/src/libvaladoc/api/struct.vala index 475f6d8081..9910994ded 100644 --- a/src/libvaladoc/api/struct.vala +++ b/src/libvaladoc/api/struct.vala @@ -29,15 +29,19 @@ using Valadoc.Content; */ public class Valadoc.Api.Struct : TypeSymbol { private string? dup_function_cname; + private string? copy_function_cname; private string? free_function_cname; + private string? destroy_function_cname; 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? free_function_cname, bool is_basic_type, void* 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; this.free_function_cname = free_function_cname; + this.destroy_function_cname = destroy_function_cname; this.cname = cname; } @@ -73,6 +77,14 @@ public class Valadoc.Api.Struct : TypeSymbol { return dup_function_cname; } + /** + * Returns the C function name that copies instances of this data + * type. + */ + public string? get_copy_function_cname () { + return copy_function_cname; + } + /** * Returns the C function name that frees instances of this data type. */ @@ -80,6 +92,13 @@ public class Valadoc.Api.Struct : TypeSymbol { return free_function_cname; } + /** + * Returns the C function name that destroys instances of this data type. + */ + public string? get_destroy_function_cname () { + return destroy_function_cname; + } + /** * {@inheritDoc} */
cada9924e156bce05d4c70b086dccbe915c00197
pulse00$twig-eclipse-plugin
improved highlighting stability
p
https://github.com/pulse00/twig-eclipse-plugin
diff --git a/org.eclipse.twig.core/Resources/parserTools/highlighting/TwigTokenizer.jflex b/org.eclipse.twig.core/Resources/parserTools/highlighting/TwigTokenizer.jflex index 17c7741..0bddeca 100644 --- a/org.eclipse.twig.core/Resources/parserTools/highlighting/TwigTokenizer.jflex +++ b/org.eclipse.twig.core/Resources/parserTools/highlighting/TwigTokenizer.jflex @@ -801,14 +801,14 @@ public final ITextRegion getNextToken() throws IOException { // if it is twig content we create a twig script region if ((context == TWIG_CONTENT)) { - if (Debug.debugTokenizer) - System.err.println("create twig region " + context); +// if (Debug.debugTokenizer) +// System.err.println("create twig region " + context); return bufferedTextRegion; } else { - if (Debug.debugTokenizer) - System.err.println("create standard region " + context); +// if (Debug.debugTokenizer) +// System.err.println("create standard region " + context); return fRegionFactory.createToken(context, start, textLength, length, null, fCurrentTagName); } @@ -1425,7 +1425,7 @@ PHP_ASP_END=%> TW_START = \{\{{WHITESPACE}* -TW_STMT_DEL_LEFT = {WHITESPACE}*\{% +TW_STMT_DEL_LEFT = \{%{WHITESPACE}* TWIG_START = \{\{{WHITESPACE}* LABEL=[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* @@ -1777,6 +1777,14 @@ NUMBER=([0-9])+ } +{TW_STMT_DEL_LEFT} { + + if (Debug.debugTokenizer) { + dump("############# tw stmt 2"); + } + return XML_CONTENT; + +} {PHP_START} | {PHP_ASP_START} | {PIstart} { if(Debug.debugTokenizer) @@ -2218,12 +2226,17 @@ NUMBER=([0-9])+ } // this is the "normal" xml content -<YYINITIAL> ![\{][^<&%]*|[&%]{S}+{Name}[^&%<]*|[&%]{Name}([^;&%<]*|{S}+;*) { +<YYINITIAL> [^<&%]* | [&%]{S}+{Name}[^&%<]* | [&%]{Name}([^;&%<]*|{S}+;*) { +//<YYINITIAL> [^<&%]*|[&%]{S}+{Name}[^&%<]*|[&%]{Name}([^;&%<]*|{S}+;*) { - if(Debug.debugTokenizer) - dump("\nXML content");//$NON-NLS-1$ + if(Debug.debugTokenizer) + dump("\nXML content");//$NON-NLS-1$ - return XML_CONTENT; + final String text = yytext(); + assert text != null; + + // checks the smarty case + return findTwigDelimiter(text, XML_CONTENT, twigLeftDelim, TWIG_OPEN, ST_TWIG_CONTENT); } @@ -2236,6 +2249,7 @@ NUMBER=([0-9])+ if(Debug.debugTokenizer) dump("TWIG CLOSE"); + //yybegin(fStateStack.pop()); yybegin(YYINITIAL); return TWIG_CLOSE; } @@ -2485,9 +2499,12 @@ NUMBER=([0-9])+ } . { - if (Debug.debugTokenizer) + if (Debug.debugTokenizer) { + System.out.println("current state " + yy_state); System.out.println("!!!unexpected!!!: \"" + yytext() + "\":" + //$NON-NLS-2$//$NON-NLS-1$ + yychar + "-" + (yychar + yylength()));//$NON-NLS-1$ + } return UNDEFINED; } diff --git a/org.eclipse.twig.core/Resources/parserTools/highlighting/twig/highlighting_scanner.jflex b/org.eclipse.twig.core/Resources/parserTools/highlighting/twig/highlighting_scanner.jflex index 52f25ae..02b1486 100644 --- a/org.eclipse.twig.core/Resources/parserTools/highlighting/twig/highlighting_scanner.jflex +++ b/org.eclipse.twig.core/Resources/parserTools/highlighting/twig/highlighting_scanner.jflex @@ -178,9 +178,9 @@ NUMBER=([0-9])+ <ST_TWIG_CONTENT> "}}"{TWIG_WHITESPACE}? { if(Debug.debugTokenizer) - dump("TWIG_CLOSE"); + dump("TWIG_CLOSETAG"); - return TWIG_CLOSE; + return TWIG_CLOSETAG; } diff --git a/org.eclipse.twig.core/Resources/parserTools/parser/TwigLexer.g b/org.eclipse.twig.core/Resources/parserTools/parser/TwigLexer.g index 12ec257..01cbf25 100644 --- a/org.eclipse.twig.core/Resources/parserTools/parser/TwigLexer.g +++ b/org.eclipse.twig.core/Resources/parserTools/parser/TwigLexer.g @@ -67,7 +67,8 @@ BSLASH : '\\'; JSON_START : '{' ; JSON_END : '}' ; QM : '?'; - +BLOCK : 'block'; +ENDBLOCK : 'endblock'; FOR : 'for'; ENDFOR : 'endfor'; ELSE : 'else'; diff --git a/org.eclipse.twig.core/Resources/parserTools/parser/TwigParser.g b/org.eclipse.twig.core/Resources/parserTools/parser/TwigParser.g index 2fa3d89..a9d8327 100644 --- a/org.eclipse.twig.core/Resources/parserTools/parser/TwigParser.g +++ b/org.eclipse.twig.core/Resources/parserTools/parser/TwigParser.g @@ -70,7 +70,16 @@ twig_control_statement twig_control - : twig_for | ENDFOR | ELSE | twig_if | twig_elseif | ENDIF | twig_macro | twig_import | twig_set | twig_include + : twig_for | ENDFOR | ELSE | twig_if | twig_elseif | ENDIF | twig_macro | twig_import | twig_set | twig_include | twig_block + ; + + +twig_block + : (BLOCK twig_block_param) | (ENDBLOCK) + ; + +twig_block_param + : (variable | method) twig_print? ; twig_include diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.java index 2e23458..462adf2 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.java @@ -1,4 +1,4 @@ -// $ANTLR 3.3 Nov 30, 2010 12:45:30 TwigLexer.g 2011-06-20 09:56:43 +// $ANTLR 3.3 Nov 30, 2010 12:45:30 TwigLexer.g 2011-06-21 02:56:52 package org.eclipse.twig.core.compiler.ast.parser; @@ -31,35 +31,37 @@ public class TwigLexer extends Lexer { public static final int JSON_START=20; public static final int JSON_END=21; public static final int QM=22; - public static final int FOR=23; - public static final int ENDFOR=24; - public static final int ELSE=25; - public static final int IF=26; - public static final int ELSEIF=27; - public static final int ENDIF=28; - public static final int IN=29; - public static final int TWIG_AS=30; - public static final int MACRO=31; - public static final int ENDMACRO=32; - public static final int IMPORT=33; - public static final int FROM=34; - public static final int SET=35; - public static final int ENDSET=36; - public static final int INCLUDE=37; - public static final int WITH=38; - public static final int ONLY=39; - public static final int DIGIT=40; - public static final int NUMBER=41; - public static final int STRING_CHAR=42; - public static final int STRING=43; - public static final int NONCONTROL_CHAR=44; - public static final int STRING_LITERAL=45; - public static final int LOWER=46; - public static final int UPPER=47; - public static final int UNDER=48; - public static final int LETTER=49; - public static final int SYMBOL=50; - public static final int WHITESPACE=51; + public static final int BLOCK=23; + public static final int ENDBLOCK=24; + public static final int FOR=25; + public static final int ENDFOR=26; + public static final int ELSE=27; + public static final int IF=28; + public static final int ELSEIF=29; + public static final int ENDIF=30; + public static final int IN=31; + public static final int TWIG_AS=32; + public static final int MACRO=33; + public static final int ENDMACRO=34; + public static final int IMPORT=35; + public static final int FROM=36; + public static final int SET=37; + public static final int ENDSET=38; + public static final int INCLUDE=39; + public static final int WITH=40; + public static final int ONLY=41; + public static final int DIGIT=42; + public static final int NUMBER=43; + public static final int STRING_CHAR=44; + public static final int STRING=45; + public static final int NONCONTROL_CHAR=46; + public static final int STRING_LITERAL=47; + public static final int LOWER=48; + public static final int UPPER=49; + public static final int UNDER=50; + public static final int LETTER=51; + public static final int SYMBOL=52; + public static final int WHITESPACE=53; private IErrorReporter errorReporter = null; @@ -550,13 +552,55 @@ public final void mQM() throws RecognitionException { } // $ANTLR end "QM" + // $ANTLR start "BLOCK" + public final void mBLOCK() throws RecognitionException { + try { + int _type = BLOCK; + int _channel = DEFAULT_TOKEN_CHANNEL; + // TwigLexer.g:70:9: ( 'block' ) + // TwigLexer.g:70:11: 'block' + { + match("block"); + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "BLOCK" + + // $ANTLR start "ENDBLOCK" + public final void mENDBLOCK() throws RecognitionException { + try { + int _type = ENDBLOCK; + int _channel = DEFAULT_TOKEN_CHANNEL; + // TwigLexer.g:71:11: ( 'endblock' ) + // TwigLexer.g:71:13: 'endblock' + { + match("endblock"); + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "ENDBLOCK" + // $ANTLR start "FOR" public final void mFOR() throws RecognitionException { try { int _type = FOR; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:71:8: ( 'for' ) - // TwigLexer.g:71:10: 'for' + // TwigLexer.g:72:8: ( 'for' ) + // TwigLexer.g:72:10: 'for' { match("for"); @@ -576,8 +620,8 @@ public final void mENDFOR() throws RecognitionException { try { int _type = ENDFOR; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:72:10: ( 'endfor' ) - // TwigLexer.g:72:12: 'endfor' + // TwigLexer.g:73:10: ( 'endfor' ) + // TwigLexer.g:73:12: 'endfor' { match("endfor"); @@ -597,8 +641,8 @@ public final void mELSE() throws RecognitionException { try { int _type = ELSE; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:73:8: ( 'else' ) - // TwigLexer.g:73:10: 'else' + // TwigLexer.g:74:8: ( 'else' ) + // TwigLexer.g:74:10: 'else' { match("else"); @@ -618,8 +662,8 @@ public final void mIF() throws RecognitionException { try { int _type = IF; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:74:7: ( 'if' ) - // TwigLexer.g:74:9: 'if' + // TwigLexer.g:75:7: ( 'if' ) + // TwigLexer.g:75:9: 'if' { match("if"); @@ -639,8 +683,8 @@ public final void mELSEIF() throws RecognitionException { try { int _type = ELSEIF; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:75:10: ( 'elseif' ) - // TwigLexer.g:75:12: 'elseif' + // TwigLexer.g:76:10: ( 'elseif' ) + // TwigLexer.g:76:12: 'elseif' { match("elseif"); @@ -660,8 +704,8 @@ public final void mENDIF() throws RecognitionException { try { int _type = ENDIF; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:76:9: ( 'endif' ) - // TwigLexer.g:76:11: 'endif' + // TwigLexer.g:77:9: ( 'endif' ) + // TwigLexer.g:77:11: 'endif' { match("endif"); @@ -681,8 +725,8 @@ public final void mIN() throws RecognitionException { try { int _type = IN; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:77:7: ( 'in' ) - // TwigLexer.g:77:9: 'in' + // TwigLexer.g:78:7: ( 'in' ) + // TwigLexer.g:78:9: 'in' { match("in"); @@ -702,8 +746,8 @@ public final void mTWIG_AS() throws RecognitionException { try { int _type = TWIG_AS; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:78:11: ( 'as' ) - // TwigLexer.g:78:13: 'as' + // TwigLexer.g:79:11: ( 'as' ) + // TwigLexer.g:79:13: 'as' { match("as"); @@ -723,8 +767,8 @@ public final void mMACRO() throws RecognitionException { try { int _type = MACRO; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:79:9: ( 'macro' ) - // TwigLexer.g:79:11: 'macro' + // TwigLexer.g:80:9: ( 'macro' ) + // TwigLexer.g:80:11: 'macro' { match("macro"); @@ -744,8 +788,8 @@ public final void mENDMACRO() throws RecognitionException { try { int _type = ENDMACRO; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:80:11: ( 'endmacro' ) - // TwigLexer.g:80:13: 'endmacro' + // TwigLexer.g:81:11: ( 'endmacro' ) + // TwigLexer.g:81:13: 'endmacro' { match("endmacro"); @@ -765,8 +809,8 @@ public final void mIMPORT() throws RecognitionException { try { int _type = IMPORT; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:81:10: ( 'import' ) - // TwigLexer.g:81:12: 'import' + // TwigLexer.g:82:10: ( 'import' ) + // TwigLexer.g:82:12: 'import' { match("import"); @@ -786,8 +830,8 @@ public final void mFROM() throws RecognitionException { try { int _type = FROM; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:82:8: ( 'from' ) - // TwigLexer.g:82:10: 'from' + // TwigLexer.g:83:8: ( 'from' ) + // TwigLexer.g:83:10: 'from' { match("from"); @@ -807,8 +851,8 @@ public final void mSET() throws RecognitionException { try { int _type = SET; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:83:8: ( 'set' ) - // TwigLexer.g:83:10: 'set' + // TwigLexer.g:84:8: ( 'set' ) + // TwigLexer.g:84:10: 'set' { match("set"); @@ -828,8 +872,8 @@ public final void mENDSET() throws RecognitionException { try { int _type = ENDSET; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:84:10: ( 'endset' ) - // TwigLexer.g:84:12: 'endset' + // TwigLexer.g:85:10: ( 'endset' ) + // TwigLexer.g:85:12: 'endset' { match("endset"); @@ -849,8 +893,8 @@ public final void mINCLUDE() throws RecognitionException { try { int _type = INCLUDE; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:85:11: ( 'include' ) - // TwigLexer.g:85:13: 'include' + // TwigLexer.g:86:11: ( 'include' ) + // TwigLexer.g:86:13: 'include' { match("include"); @@ -870,8 +914,8 @@ public final void mWITH() throws RecognitionException { try { int _type = WITH; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:86:8: ( 'with' ) - // TwigLexer.g:86:10: 'with' + // TwigLexer.g:87:8: ( 'with' ) + // TwigLexer.g:87:10: 'with' { match("with"); @@ -891,8 +935,8 @@ public final void mONLY() throws RecognitionException { try { int _type = ONLY; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:87:8: ( 'only' ) - // TwigLexer.g:87:10: 'only' + // TwigLexer.g:88:8: ( 'only' ) + // TwigLexer.g:88:10: 'only' { match("only"); @@ -912,10 +956,10 @@ public final void mNUMBER() throws RecognitionException { try { int _type = NUMBER; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:94:8: ( ( DIGIT )+ ) - // TwigLexer.g:94:10: ( DIGIT )+ + // TwigLexer.g:95:8: ( ( DIGIT )+ ) + // TwigLexer.g:95:10: ( DIGIT )+ { - // TwigLexer.g:94:10: ( DIGIT )+ + // TwigLexer.g:95:10: ( DIGIT )+ int cnt3=0; loop3: do { @@ -929,7 +973,7 @@ public final void mNUMBER() throws RecognitionException { switch (alt3) { case 1 : - // TwigLexer.g:94:10: DIGIT + // TwigLexer.g:95:10: DIGIT { mDIGIT(); @@ -961,10 +1005,10 @@ public final void mSTRING() throws RecognitionException { try { int _type = STRING; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:95:8: ( ( STRING_CHAR )+ ) - // TwigLexer.g:95:10: ( STRING_CHAR )+ + // TwigLexer.g:96:8: ( ( STRING_CHAR )+ ) + // TwigLexer.g:96:10: ( STRING_CHAR )+ { - // TwigLexer.g:95:10: ( STRING_CHAR )+ + // TwigLexer.g:96:10: ( STRING_CHAR )+ int cnt4=0; loop4: do { @@ -978,7 +1022,7 @@ public final void mSTRING() throws RecognitionException { switch (alt4) { case 1 : - // TwigLexer.g:95:10: STRING_CHAR + // TwigLexer.g:96:10: STRING_CHAR { mSTRING_CHAR(); @@ -1010,7 +1054,7 @@ public final void mSTRING_LITERAL() throws RecognitionException { try { int _type = STRING_LITERAL; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:100:1: ( '\"' ( NONCONTROL_CHAR )* '\"' | '\\'' ( NONCONTROL_CHAR )* '\\'' ) + // TwigLexer.g:101:1: ( '\"' ( NONCONTROL_CHAR )* '\"' | '\\'' ( NONCONTROL_CHAR )* '\\'' ) int alt7=2; int LA7_0 = input.LA(1); @@ -1028,10 +1072,10 @@ else if ( (LA7_0=='\'') ) { } switch (alt7) { case 1 : - // TwigLexer.g:100:3: '\"' ( NONCONTROL_CHAR )* '\"' + // TwigLexer.g:101:3: '\"' ( NONCONTROL_CHAR )* '\"' { match('\"'); - // TwigLexer.g:100:7: ( NONCONTROL_CHAR )* + // TwigLexer.g:101:7: ( NONCONTROL_CHAR )* loop5: do { int alt5=2; @@ -1044,7 +1088,7 @@ else if ( (LA7_0=='\'') ) { switch (alt5) { case 1 : - // TwigLexer.g:100:7: NONCONTROL_CHAR + // TwigLexer.g:101:7: NONCONTROL_CHAR { mNONCONTROL_CHAR(); @@ -1061,10 +1105,10 @@ else if ( (LA7_0=='\'') ) { } break; case 2 : - // TwigLexer.g:101:3: '\\'' ( NONCONTROL_CHAR )* '\\'' + // TwigLexer.g:102:3: '\\'' ( NONCONTROL_CHAR )* '\\'' { match('\''); - // TwigLexer.g:101:8: ( NONCONTROL_CHAR )* + // TwigLexer.g:102:8: ( NONCONTROL_CHAR )* loop6: do { int alt6=2; @@ -1077,7 +1121,7 @@ else if ( (LA7_0=='\'') ) { switch (alt6) { case 1 : - // TwigLexer.g:101:8: NONCONTROL_CHAR + // TwigLexer.g:102:8: NONCONTROL_CHAR { mNONCONTROL_CHAR(); @@ -1106,7 +1150,7 @@ else if ( (LA7_0=='\'') ) { // $ANTLR start "STRING_CHAR" public final void mSTRING_CHAR() throws RecognitionException { try { - // TwigLexer.g:104:23: ( LOWER | UPPER | DIGIT | UNDER ) + // TwigLexer.g:105:23: ( LOWER | UPPER | DIGIT | UNDER ) // TwigLexer.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) { @@ -1130,7 +1174,7 @@ public final void mSTRING_CHAR() throws RecognitionException { // $ANTLR start "NONCONTROL_CHAR" public final void mNONCONTROL_CHAR() throws RecognitionException { try { - // TwigLexer.g:105:25: ( LETTER | DIGIT | SYMBOL ) + // TwigLexer.g:106:25: ( LETTER | DIGIT | SYMBOL ) // TwigLexer.g: { if ( input.LA(1)==' '||input.LA(1)=='%'||(input.LA(1)>='-' && input.LA(1)<=':')||input.LA(1)=='<'||input.LA(1)=='>'||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z')||input.LA(1)=='|' ) { @@ -1154,7 +1198,7 @@ public final void mNONCONTROL_CHAR() throws RecognitionException { // $ANTLR start "LETTER" public final void mLETTER() throws RecognitionException { try { - // TwigLexer.g:106:17: ( LOWER | UPPER ) + // TwigLexer.g:107:17: ( LOWER | UPPER ) // TwigLexer.g: { if ( (input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { @@ -1178,8 +1222,8 @@ public final void mLETTER() throws RecognitionException { // $ANTLR start "LOWER" public final void mLOWER() throws RecognitionException { try { - // TwigLexer.g:107:16: ( 'a' .. 'z' ) - // TwigLexer.g:107:18: 'a' .. 'z' + // TwigLexer.g:108:16: ( 'a' .. 'z' ) + // TwigLexer.g:108:18: 'a' .. 'z' { matchRange('a','z'); @@ -1194,8 +1238,8 @@ public final void mLOWER() throws RecognitionException { // $ANTLR start "UPPER" public final void mUPPER() throws RecognitionException { try { - // TwigLexer.g:108:16: ( 'A' .. 'Z' ) - // TwigLexer.g:108:18: 'A' .. 'Z' + // TwigLexer.g:109:16: ( 'A' .. 'Z' ) + // TwigLexer.g:109:18: 'A' .. 'Z' { matchRange('A','Z'); @@ -1210,8 +1254,8 @@ public final void mUPPER() throws RecognitionException { // $ANTLR start "DIGIT" public final void mDIGIT() throws RecognitionException { try { - // TwigLexer.g:109:16: ( '0' .. '9' ) - // TwigLexer.g:109:18: '0' .. '9' + // TwigLexer.g:110:16: ( '0' .. '9' ) + // TwigLexer.g:110:18: '0' .. '9' { matchRange('0','9'); @@ -1226,8 +1270,8 @@ public final void mDIGIT() throws RecognitionException { // $ANTLR start "UNDER" public final void mUNDER() throws RecognitionException { try { - // TwigLexer.g:110:16: ( '_' ) - // TwigLexer.g:110:18: '_' + // TwigLexer.g:111:16: ( '_' ) + // TwigLexer.g:111:18: '_' { match('_'); @@ -1242,7 +1286,7 @@ public final void mUNDER() throws RecognitionException { // $ANTLR start "SYMBOL" public final void mSYMBOL() throws RecognitionException { try { - // TwigLexer.g:111:16: ( UNDER | '-' | '/' | ':' | '<' | '>' | ' ' | '%' | '.' | '|' ) + // TwigLexer.g:112:16: ( UNDER | '-' | '/' | ':' | '<' | '>' | ' ' | '%' | '.' | '|' ) // TwigLexer.g: { if ( input.LA(1)==' '||input.LA(1)=='%'||(input.LA(1)>='-' && input.LA(1)<='/')||input.LA(1)==':'||input.LA(1)=='<'||input.LA(1)=='>'||input.LA(1)=='_'||input.LA(1)=='|' ) { @@ -1268,10 +1312,10 @@ public final void mWHITESPACE() throws RecognitionException { try { int _type = WHITESPACE; int _channel = DEFAULT_TOKEN_CHANNEL; - // TwigLexer.g:113:12: ( ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ ) - // TwigLexer.g:113:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ + // TwigLexer.g:114:12: ( ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ ) + // TwigLexer.g:114:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ { - // TwigLexer.g:113:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ + // TwigLexer.g:114:14: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ int cnt8=0; loop8: do { @@ -1322,8 +1366,8 @@ public final void mWHITESPACE() throws RecognitionException { // $ANTLR end "WHITESPACE" public void mTokens() throws RecognitionException { - // TwigLexer.g:1:8: ( PRINT_OPEN | PRINT_CLOSE | CTRL_OPEN | CTRL_CLOSE | METHOD_START | METHOD_END | ARRAY_START | ARRAY_END | ASIG | TILDE | PIPE | DDOT | DOT | COLON | COMMA | BSLASH | JSON_START | JSON_END | QM | FOR | ENDFOR | ELSE | IF | ELSEIF | ENDIF | IN | TWIG_AS | MACRO | ENDMACRO | IMPORT | FROM | SET | ENDSET | INCLUDE | WITH | ONLY | NUMBER | STRING | STRING_LITERAL | WHITESPACE ) - int alt9=40; + // TwigLexer.g:1:8: ( PRINT_OPEN | PRINT_CLOSE | CTRL_OPEN | CTRL_CLOSE | METHOD_START | METHOD_END | ARRAY_START | ARRAY_END | ASIG | TILDE | PIPE | DDOT | DOT | COLON | COMMA | BSLASH | JSON_START | JSON_END | QM | BLOCK | ENDBLOCK | FOR | ENDFOR | ELSE | IF | ELSEIF | ENDIF | IN | TWIG_AS | MACRO | ENDMACRO | IMPORT | FROM | SET | ENDSET | INCLUDE | WITH | ONLY | NUMBER | STRING | STRING_LITERAL | WHITESPACE ) + int alt9=42; alt9 = dfa9.predict(input); switch (alt9) { case 1 : @@ -1460,147 +1504,161 @@ public void mTokens() throws RecognitionException { } break; case 20 : - // TwigLexer.g:1:167: FOR + // TwigLexer.g:1:167: BLOCK { - mFOR(); + mBLOCK(); } break; case 21 : - // TwigLexer.g:1:171: ENDFOR + // TwigLexer.g:1:173: ENDBLOCK { - mENDFOR(); + mENDBLOCK(); } break; case 22 : - // TwigLexer.g:1:178: ELSE + // TwigLexer.g:1:182: FOR { - mELSE(); + mFOR(); } break; case 23 : - // TwigLexer.g:1:183: IF + // TwigLexer.g:1:186: ENDFOR { - mIF(); + mENDFOR(); } break; case 24 : - // TwigLexer.g:1:186: ELSEIF + // TwigLexer.g:1:193: ELSE { - mELSEIF(); + mELSE(); } break; case 25 : - // TwigLexer.g:1:193: ENDIF + // TwigLexer.g:1:198: IF { - mENDIF(); + mIF(); } break; case 26 : - // TwigLexer.g:1:199: IN + // TwigLexer.g:1:201: ELSEIF { - mIN(); + mELSEIF(); } break; case 27 : - // TwigLexer.g:1:202: TWIG_AS + // TwigLexer.g:1:208: ENDIF { - mTWIG_AS(); + mENDIF(); } break; case 28 : - // TwigLexer.g:1:210: MACRO + // TwigLexer.g:1:214: IN { - mMACRO(); + mIN(); } break; case 29 : - // TwigLexer.g:1:216: ENDMACRO + // TwigLexer.g:1:217: TWIG_AS { - mENDMACRO(); + mTWIG_AS(); } break; case 30 : - // TwigLexer.g:1:225: IMPORT + // TwigLexer.g:1:225: MACRO { - mIMPORT(); + mMACRO(); } break; case 31 : - // TwigLexer.g:1:232: FROM + // TwigLexer.g:1:231: ENDMACRO { - mFROM(); + mENDMACRO(); } break; case 32 : - // TwigLexer.g:1:237: SET + // TwigLexer.g:1:240: IMPORT { - mSET(); + mIMPORT(); } break; case 33 : - // TwigLexer.g:1:241: ENDSET + // TwigLexer.g:1:247: FROM { - mENDSET(); + mFROM(); } break; case 34 : - // TwigLexer.g:1:248: INCLUDE + // TwigLexer.g:1:252: SET { - mINCLUDE(); + mSET(); } break; case 35 : - // TwigLexer.g:1:256: WITH + // TwigLexer.g:1:256: ENDSET { - mWITH(); + mENDSET(); } break; case 36 : - // TwigLexer.g:1:261: ONLY + // TwigLexer.g:1:263: INCLUDE { - mONLY(); + mINCLUDE(); } break; case 37 : - // TwigLexer.g:1:266: NUMBER + // TwigLexer.g:1:271: WITH { - mNUMBER(); + mWITH(); } break; case 38 : - // TwigLexer.g:1:273: STRING + // TwigLexer.g:1:276: ONLY { - mSTRING(); + mONLY(); } break; case 39 : - // TwigLexer.g:1:280: STRING_LITERAL + // TwigLexer.g:1:281: NUMBER { - mSTRING_LITERAL(); + mNUMBER(); } break; case 40 : - // TwigLexer.g:1:295: WHITESPACE + // TwigLexer.g:1:288: STRING + { + mSTRING(); + + } + break; + case 41 : + // TwigLexer.g:1:295: STRING_LITERAL + { + mSTRING_LITERAL(); + + } + break; + case 42 : + // TwigLexer.g:1:310: WHITESPACE { mWHITESPACE(); @@ -1614,49 +1672,51 @@ public void mTokens() throws RecognitionException { protected DFA9 dfa9 = new DFA9(this); static final String DFA9_eotS = - "\1\uffff\1\37\1\41\10\uffff\1\43\1\uffff\1\34\3\uffff\10\32\1\60"+ - "\12\uffff\4\32\1\65\1\67\1\32\1\71\4\32\1\uffff\1\76\3\32\1\uffff"+ - "\1\32\1\uffff\1\32\1\uffff\1\32\1\110\2\32\1\uffff\1\113\4\32\1"+ - "\121\3\32\1\uffff\1\125\1\126\1\uffff\1\32\1\130\3\32\1\uffff\2"+ - "\32\1\136\2\uffff\1\137\1\uffff\1\32\1\141\1\142\1\32\1\144\2\uffff"+ - "\1\32\2\uffff\1\146\1\uffff\1\147\2\uffff"; + "\1\uffff\1\40\1\42\10\uffff\1\44\1\uffff\1\35\3\uffff\11\33\1\62"+ + "\12\uffff\5\33\1\70\1\72\1\33\1\74\4\33\1\uffff\3\33\1\110\1\33"+ + "\1\uffff\1\33\1\uffff\1\33\1\uffff\1\33\1\115\10\33\1\127\1\uffff"+ + "\1\130\3\33\1\uffff\1\134\1\135\1\136\2\33\1\141\3\33\2\uffff\2"+ + "\33\1\147\3\uffff\1\33\1\151\1\uffff\1\33\1\153\1\154\1\33\1\156"+ + "\1\uffff\1\33\1\uffff\1\33\2\uffff\1\161\1\uffff\1\162\1\163\3\uffff"; static final String DFA9_eofS = - "\150\uffff"; + "\164\uffff"; static final String DFA9_minS = - "\1\11\1\45\1\175\10\uffff\1\56\1\uffff\1\40\3\uffff\1\157\1\154"+ - "\1\146\1\163\1\141\1\145\1\151\1\156\1\60\12\uffff\1\162\1\157\1"+ - "\144\1\163\2\60\1\160\1\60\1\143\2\164\1\154\1\uffff\1\60\1\155"+ - "\1\146\1\145\1\uffff\1\154\1\uffff\1\157\1\uffff\1\162\1\60\1\150"+ - "\1\171\1\uffff\1\60\1\157\1\146\1\141\1\145\1\60\1\165\1\162\1\157"+ - "\1\uffff\2\60\1\uffff\1\162\1\60\1\143\1\164\1\146\1\uffff\1\144"+ - "\1\164\1\60\2\uffff\1\60\1\uffff\1\162\2\60\1\145\1\60\2\uffff\1"+ - "\157\2\uffff\1\60\1\uffff\1\60\2\uffff"; + "\1\11\1\45\1\175\10\uffff\1\56\1\uffff\1\40\3\uffff\2\154\1\157"+ + "\1\146\1\163\1\141\1\145\1\151\1\156\1\60\12\uffff\1\157\1\144\1"+ + "\163\1\162\1\157\2\60\1\160\1\60\1\143\2\164\1\154\1\uffff\1\143"+ + "\1\142\1\145\1\60\1\155\1\uffff\1\154\1\uffff\1\157\1\uffff\1\162"+ + "\1\60\1\150\1\171\1\153\1\154\1\157\1\146\1\141\1\145\1\60\1\uffff"+ + "\1\60\1\165\1\162\1\157\1\uffff\3\60\1\157\1\162\1\60\1\143\1\164"+ + "\1\146\2\uffff\1\144\1\164\1\60\3\uffff\1\143\1\60\1\uffff\1\162"+ + "\2\60\1\145\1\60\1\uffff\1\153\1\uffff\1\157\2\uffff\1\60\1\uffff"+ + "\2\60\3\uffff"; static final String DFA9_maxS = - "\1\176\1\173\1\175\10\uffff\1\56\1\uffff\1\54\3\uffff\1\162\2\156"+ - "\1\163\1\141\1\145\1\151\1\156\1\172\12\uffff\1\162\1\157\1\144"+ - "\1\163\2\172\1\160\1\172\1\143\2\164\1\154\1\uffff\1\172\1\155\1"+ - "\163\1\145\1\uffff\1\154\1\uffff\1\157\1\uffff\1\162\1\172\1\150"+ - "\1\171\1\uffff\1\172\1\157\1\146\1\141\1\145\1\172\1\165\1\162\1"+ - "\157\1\uffff\2\172\1\uffff\1\162\1\172\1\143\1\164\1\146\1\uffff"+ - "\1\144\1\164\1\172\2\uffff\1\172\1\uffff\1\162\2\172\1\145\1\172"+ - "\2\uffff\1\157\2\uffff\1\172\1\uffff\1\172\2\uffff"; + "\1\176\1\173\1\175\10\uffff\1\56\1\uffff\1\54\3\uffff\1\154\1\156"+ + "\1\162\1\156\1\163\1\141\1\145\1\151\1\156\1\172\12\uffff\1\157"+ + "\1\144\1\163\1\162\1\157\2\172\1\160\1\172\1\143\2\164\1\154\1\uffff"+ + "\1\143\1\163\1\145\1\172\1\155\1\uffff\1\154\1\uffff\1\157\1\uffff"+ + "\1\162\1\172\1\150\1\171\1\153\1\154\1\157\1\146\1\141\1\145\1\172"+ + "\1\uffff\1\172\1\165\1\162\1\157\1\uffff\3\172\1\157\1\162\1\172"+ + "\1\143\1\164\1\146\2\uffff\1\144\1\164\1\172\3\uffff\1\143\1\172"+ + "\1\uffff\1\162\2\172\1\145\1\172\1\uffff\1\153\1\uffff\1\157\2\uffff"+ + "\1\172\1\uffff\2\172\3\uffff"; static final String DFA9_acceptS = "\3\uffff\1\4\1\5\1\6\1\7\1\10\1\11\1\12\1\13\1\uffff\1\16\1\uffff"+ - "\1\17\1\20\1\23\11\uffff\1\46\1\47\1\50\1\1\1\3\1\21\1\2\1\22\1"+ - "\14\1\15\14\uffff\1\45\4\uffff\1\27\1\uffff\1\32\1\uffff\1\33\4"+ - "\uffff\1\24\11\uffff\1\40\2\uffff\1\37\5\uffff\1\26\3\uffff\1\43"+ - "\1\44\1\uffff\1\31\5\uffff\1\34\1\25\1\uffff\1\41\1\30\1\uffff\1"+ - "\36\1\uffff\1\42\1\35"; + "\1\17\1\20\1\23\12\uffff\1\50\1\51\1\52\1\1\1\3\1\21\1\2\1\22\1"+ + "\14\1\15\15\uffff\1\47\5\uffff\1\31\1\uffff\1\34\1\uffff\1\35\13"+ + "\uffff\1\26\4\uffff\1\42\11\uffff\1\30\1\41\3\uffff\1\45\1\46\1"+ + "\24\2\uffff\1\33\5\uffff\1\36\1\uffff\1\27\1\uffff\1\43\1\32\1\uffff"+ + "\1\40\2\uffff\1\44\1\25\1\37"; static final String DFA9_specialS = - "\150\uffff}>"; + "\164\uffff}>"; static final String[] DFA9_transitionS = { - "\2\34\1\uffff\2\34\22\uffff\1\15\1\uffff\1\33\2\uffff\1\3\1"+ - "\uffff\1\33\1\4\1\5\2\uffff\1\16\1\uffff\1\13\1\uffff\12\31"+ - "\1\14\2\uffff\1\10\1\uffff\1\20\1\uffff\32\32\1\6\1\17\1\7\1"+ - "\uffff\1\32\1\uffff\1\24\3\32\1\22\1\21\2\32\1\23\3\32\1\25"+ - "\1\32\1\30\3\32\1\26\3\32\1\27\3\32\1\1\1\12\1\2\1\11", - "\1\36\125\uffff\1\35", - "\1\40", + "\2\35\1\uffff\2\35\22\uffff\1\15\1\uffff\1\34\2\uffff\1\3\1"+ + "\uffff\1\34\1\4\1\5\2\uffff\1\16\1\uffff\1\13\1\uffff\12\32"+ + "\1\14\2\uffff\1\10\1\uffff\1\20\1\uffff\32\33\1\6\1\17\1\7\1"+ + "\uffff\1\33\1\uffff\1\25\1\21\2\33\1\22\1\23\2\33\1\24\3\33"+ + "\1\26\1\33\1\31\3\33\1\27\3\33\1\30\3\33\1\1\1\12\1\2\1\11", + "\1\37\125\uffff\1\36", + "\1\41", "", "", "", @@ -1665,21 +1725,22 @@ public void mTokens() throws RecognitionException { "", "", "", - "\1\42", + "\1\43", "", "\1\15\13\uffff\1\16", "", "", "", - "\1\44\2\uffff\1\45", + "\1\45", "\1\47\1\uffff\1\46", - "\1\50\6\uffff\1\52\1\51", - "\1\53", - "\1\54", + "\1\50\2\uffff\1\51", + "\1\52\6\uffff\1\54\1\53", "\1\55", "\1\56", "\1\57", - "\12\31\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\1\60", + "\1\61", + "\12\32\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", "", "", "", @@ -1690,72 +1751,84 @@ public void mTokens() throws RecognitionException { "", "", "", - "\1\61", - "\1\62", "\1\63", "\1\64", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\2\32\1\66\27\32", - "\1\70", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", - "\1\72", + "\1\65", + "\1\66", + "\1\67", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\2\33\1\71\27\33", "\1\73", - "\1\74", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", "\1\75", - "", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\1\76", "\1\77", - "\1\100\2\uffff\1\101\3\uffff\1\102\5\uffff\1\103", - "\1\104", - "", - "\1\105", - "", - "\1\106", + "\1\100", "", + "\1\101", + "\1\102\3\uffff\1\103\2\uffff\1\104\3\uffff\1\105\5\uffff\1"+ + "\106", "\1\107", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", "\1\111", + "", "\1\112", "", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\1\113", + "", "\1\114", - "\1\115", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", "\1\116", "\1\117", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\10\32\1\120\21\32", + "\1\120", + "\1\121", "\1\122", "\1\123", "\1\124", + "\1\125", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\10\33\1\126\21\33", "", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", - "", - "\1\127", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", "\1\131", "\1\132", "\1\133", "", - "\1\134", - "\1\135", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", - "", - "", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", - "", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\1\137", "\1\140", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\1\142", "\1\143", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\1\144", "", "", "\1\145", + "\1\146", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "", + "", + "", + "\1\150", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "", + "\1\152", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\1\155", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "", + "\1\157", + "", + "\1\160", + "", "", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", "", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", + "\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33", "", - "\12\32\7\uffff\32\32\4\uffff\1\32\1\uffff\32\32", "", "" }; @@ -1790,7 +1863,7 @@ public DFA9(BaseRecognizer recognizer) { this.transition = DFA9_transition; } public String getDescription() { - return "1:1: Tokens : ( PRINT_OPEN | PRINT_CLOSE | CTRL_OPEN | CTRL_CLOSE | METHOD_START | METHOD_END | ARRAY_START | ARRAY_END | ASIG | TILDE | PIPE | DDOT | DOT | COLON | COMMA | BSLASH | JSON_START | JSON_END | QM | FOR | ENDFOR | ELSE | IF | ELSEIF | ENDIF | IN | TWIG_AS | MACRO | ENDMACRO | IMPORT | FROM | SET | ENDSET | INCLUDE | WITH | ONLY | NUMBER | STRING | STRING_LITERAL | WHITESPACE );"; + return "1:1: Tokens : ( PRINT_OPEN | PRINT_CLOSE | CTRL_OPEN | CTRL_CLOSE | METHOD_START | METHOD_END | ARRAY_START | ARRAY_END | ASIG | TILDE | PIPE | DDOT | DOT | COLON | COMMA | BSLASH | JSON_START | JSON_END | QM | BLOCK | ENDBLOCK | FOR | ENDFOR | ELSE | IF | ELSEIF | ENDIF | IN | TWIG_AS | MACRO | ENDMACRO | IMPORT | FROM | SET | ENDSET | INCLUDE | WITH | ONLY | NUMBER | STRING | STRING_LITERAL | WHITESPACE );"; } } diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.tokens b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.tokens index 3e7c4db..f8f5843 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.tokens +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigLexer.tokens @@ -17,32 +17,34 @@ BSLASH=19 JSON_START=20 JSON_END=21 QM=22 -FOR=23 -ENDFOR=24 -ELSE=25 -IF=26 -ELSEIF=27 -ENDIF=28 -IN=29 -TWIG_AS=30 -MACRO=31 -ENDMACRO=32 -IMPORT=33 -FROM=34 -SET=35 -ENDSET=36 -INCLUDE=37 -WITH=38 -ONLY=39 -DIGIT=40 -NUMBER=41 -STRING_CHAR=42 -STRING=43 -NONCONTROL_CHAR=44 -STRING_LITERAL=45 -LOWER=46 -UPPER=47 -UNDER=48 -LETTER=49 -SYMBOL=50 -WHITESPACE=51 +BLOCK=23 +ENDBLOCK=24 +FOR=25 +ENDFOR=26 +ELSE=27 +IF=28 +ELSEIF=29 +ENDIF=30 +IN=31 +TWIG_AS=32 +MACRO=33 +ENDMACRO=34 +IMPORT=35 +FROM=36 +SET=37 +ENDSET=38 +INCLUDE=39 +WITH=40 +ONLY=41 +DIGIT=42 +NUMBER=43 +STRING_CHAR=44 +STRING=45 +NONCONTROL_CHAR=46 +STRING_LITERAL=47 +LOWER=48 +UPPER=49 +UNDER=50 +LETTER=51 +SYMBOL=52 +WHITESPACE=53 diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.java index d6d31d0..7abf818 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.java @@ -1,4 +1,4 @@ -// $ANTLR 3.3 Nov 30, 2010 12:45:30 TwigParser.g 2011-06-20 09:56:44 +// $ANTLR 3.3 Nov 30, 2010 12:45:30 TwigParser.g 2011-06-21 02:56:52 package org.eclipse.twig.core.compiler.ast.parser; @@ -15,7 +15,7 @@ public class TwigParser extends Parser { public static final String[] tokenNames = new String[] { - "<invalid>", "<EOR>", "<DOWN>", "<UP>", "PRINT_OPEN", "PRINT_CLOSE", "CTRL_OPEN", "CTRL_CLOSE", "METHOD_START", "METHOD_END", "ARRAY_START", "ARRAY_END", "ASIG", "TILDE", "PIPE", "DDOT", "DOT", "COLON", "COMMA", "BSLASH", "JSON_START", "JSON_END", "QM", "FOR", "ENDFOR", "ELSE", "IF", "ELSEIF", "ENDIF", "IN", "TWIG_AS", "MACRO", "ENDMACRO", "IMPORT", "FROM", "SET", "ENDSET", "INCLUDE", "WITH", "ONLY", "DIGIT", "NUMBER", "STRING_CHAR", "STRING", "NONCONTROL_CHAR", "STRING_LITERAL", "LOWER", "UPPER", "UNDER", "LETTER", "SYMBOL", "WHITESPACE", "TWIG_PR_STMT", "TWIG_VAR", "LITERAL_ARG" + "<invalid>", "<EOR>", "<DOWN>", "<UP>", "PRINT_OPEN", "PRINT_CLOSE", "CTRL_OPEN", "CTRL_CLOSE", "METHOD_START", "METHOD_END", "ARRAY_START", "ARRAY_END", "ASIG", "TILDE", "PIPE", "DDOT", "DOT", "COLON", "COMMA", "BSLASH", "JSON_START", "JSON_END", "QM", "BLOCK", "ENDBLOCK", "FOR", "ENDFOR", "ELSE", "IF", "ELSEIF", "ENDIF", "IN", "TWIG_AS", "MACRO", "ENDMACRO", "IMPORT", "FROM", "SET", "ENDSET", "INCLUDE", "WITH", "ONLY", "DIGIT", "NUMBER", "STRING_CHAR", "STRING", "NONCONTROL_CHAR", "STRING_LITERAL", "LOWER", "UPPER", "UNDER", "LETTER", "SYMBOL", "WHITESPACE", "TWIG_PR_STMT", "TWIG_VAR", "LITERAL_ARG" }; public static final int EOF=-1; public static final int PRINT_OPEN=4; @@ -37,38 +37,40 @@ public class TwigParser extends Parser { public static final int JSON_START=20; public static final int JSON_END=21; public static final int QM=22; - public static final int FOR=23; - public static final int ENDFOR=24; - public static final int ELSE=25; - public static final int IF=26; - public static final int ELSEIF=27; - public static final int ENDIF=28; - public static final int IN=29; - public static final int TWIG_AS=30; - public static final int MACRO=31; - public static final int ENDMACRO=32; - public static final int IMPORT=33; - public static final int FROM=34; - public static final int SET=35; - public static final int ENDSET=36; - public static final int INCLUDE=37; - public static final int WITH=38; - public static final int ONLY=39; - public static final int DIGIT=40; - public static final int NUMBER=41; - public static final int STRING_CHAR=42; - public static final int STRING=43; - public static final int NONCONTROL_CHAR=44; - public static final int STRING_LITERAL=45; - public static final int LOWER=46; - public static final int UPPER=47; - public static final int UNDER=48; - public static final int LETTER=49; - public static final int SYMBOL=50; - public static final int WHITESPACE=51; - public static final int TWIG_PR_STMT=52; - public static final int TWIG_VAR=53; - public static final int LITERAL_ARG=54; + public static final int BLOCK=23; + public static final int ENDBLOCK=24; + public static final int FOR=25; + public static final int ENDFOR=26; + public static final int ELSE=27; + public static final int IF=28; + public static final int ELSEIF=29; + public static final int ENDIF=30; + public static final int IN=31; + public static final int TWIG_AS=32; + public static final int MACRO=33; + public static final int ENDMACRO=34; + public static final int IMPORT=35; + public static final int FROM=36; + public static final int SET=37; + public static final int ENDSET=38; + public static final int INCLUDE=39; + public static final int WITH=40; + public static final int ONLY=41; + public static final int DIGIT=42; + public static final int NUMBER=43; + public static final int STRING_CHAR=44; + public static final int STRING=45; + public static final int NONCONTROL_CHAR=46; + public static final int STRING_LITERAL=47; + public static final int LOWER=48; + public static final int UPPER=49; + public static final int UNDER=50; + public static final int LETTER=51; + public static final int SYMBOL=52; + public static final int WHITESPACE=53; + public static final int TWIG_PR_STMT=54; + public static final int TWIG_VAR=55; + public static final int LITERAL_ARG=56; // delegates // delegators @@ -250,7 +252,7 @@ public final TwigParser.twig_control_statement_return twig_control_statement() t int alt2=2; int LA2_0 = input.LA(1); - if ( ((LA2_0>=FOR && LA2_0<=ENDIF)||(LA2_0>=MACRO && LA2_0<=INCLUDE)||LA2_0==STRING) ) { + if ( ((LA2_0>=BLOCK && LA2_0<=ENDIF)||(LA2_0>=MACRO && LA2_0<=INCLUDE)||LA2_0==STRING) ) { alt2=1; } switch (alt2) { @@ -300,7 +302,7 @@ public static class twig_control_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_control" - // TwigParser.g:72:1: twig_control : ( twig_for | ENDFOR | ELSE | twig_if | twig_elseif | ENDIF | twig_macro | twig_import | twig_set | twig_include ); + // TwigParser.g:72:1: twig_control : ( twig_for | ENDFOR | ELSE | twig_if | twig_elseif | ENDIF | twig_macro | twig_import | twig_set | twig_include | twig_block ); public final TwigParser.twig_control_return twig_control() throws RecognitionException { TwigParser.twig_control_return retval = new TwigParser.twig_control_return(); retval.start = input.LT(1); @@ -324,14 +326,16 @@ public final TwigParser.twig_control_return twig_control() throws RecognitionExc TwigParser.twig_include_return twig_include15 = null; + TwigParser.twig_block_return twig_block16 = null; + TwigCommonTree ENDFOR7_tree=null; TwigCommonTree ELSE8_tree=null; TwigCommonTree ENDIF11_tree=null; try { - // TwigParser.g:73:3: ( twig_for | ENDFOR | ELSE | twig_if | twig_elseif | ENDIF | twig_macro | twig_import | twig_set | twig_include ) - int alt3=10; + // TwigParser.g:73:3: ( twig_for | ENDFOR | ELSE | twig_if | twig_elseif | ENDIF | twig_macro | twig_import | twig_set | twig_include | twig_block ) + int alt3=11; switch ( input.LA(1) ) { case FOR: { @@ -387,6 +391,12 @@ public final TwigParser.twig_control_return twig_control() throws RecognitionExc alt3=10; } break; + case BLOCK: + case ENDBLOCK: + { + alt3=11; + } + break; default: NoViableAltException nvae = new NoViableAltException("", 3, 0, input); @@ -527,6 +537,20 @@ public final TwigParser.twig_control_return twig_control() throws RecognitionExc adaptor.addChild(root_0, twig_include15.getTree()); + } + break; + case 11 : + // TwigParser.g:73:117: twig_block + { + root_0 = (TwigCommonTree)adaptor.nil(); + + pushFollow(FOLLOW_twig_block_in_twig_control148); + twig_block16=twig_block(); + + state._fsp--; + + adaptor.addChild(root_0, twig_block16.getTree()); + } break; @@ -549,88 +573,291 @@ public final TwigParser.twig_control_return twig_control() throws RecognitionExc } // $ANTLR end "twig_control" + public static class twig_block_return extends ParserRuleReturnScope { + TwigCommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "twig_block" + // TwigParser.g:77:1: twig_block : ( ( BLOCK twig_block_param ) | ( ENDBLOCK ) ); + public final TwigParser.twig_block_return twig_block() throws RecognitionException { + TwigParser.twig_block_return retval = new TwigParser.twig_block_return(); + retval.start = input.LT(1); + + TwigCommonTree root_0 = null; + + CommonToken BLOCK17=null; + CommonToken ENDBLOCK19=null; + TwigParser.twig_block_param_return twig_block_param18 = null; + + + TwigCommonTree BLOCK17_tree=null; + TwigCommonTree ENDBLOCK19_tree=null; + + try { + // TwigParser.g:78:3: ( ( BLOCK twig_block_param ) | ( ENDBLOCK ) ) + int alt4=2; + int LA4_0 = input.LA(1); + + if ( (LA4_0==BLOCK) ) { + alt4=1; + } + else if ( (LA4_0==ENDBLOCK) ) { + alt4=2; + } + else { + NoViableAltException nvae = + new NoViableAltException("", 4, 0, input); + + throw nvae; + } + switch (alt4) { + case 1 : + // TwigParser.g:78:5: ( BLOCK twig_block_param ) + { + root_0 = (TwigCommonTree)adaptor.nil(); + + // TwigParser.g:78:5: ( BLOCK twig_block_param ) + // TwigParser.g:78:6: BLOCK twig_block_param + { + BLOCK17=(CommonToken)match(input,BLOCK,FOLLOW_BLOCK_in_twig_block167); + BLOCK17_tree = (TwigCommonTree)adaptor.create(BLOCK17); + adaptor.addChild(root_0, BLOCK17_tree); + + pushFollow(FOLLOW_twig_block_param_in_twig_block169); + twig_block_param18=twig_block_param(); + + state._fsp--; + + adaptor.addChild(root_0, twig_block_param18.getTree()); + + } + + + } + break; + case 2 : + // TwigParser.g:78:32: ( ENDBLOCK ) + { + root_0 = (TwigCommonTree)adaptor.nil(); + + // TwigParser.g:78:32: ( ENDBLOCK ) + // TwigParser.g:78:33: ENDBLOCK + { + ENDBLOCK19=(CommonToken)match(input,ENDBLOCK,FOLLOW_ENDBLOCK_in_twig_block175); + ENDBLOCK19_tree = (TwigCommonTree)adaptor.create(ENDBLOCK19); + adaptor.addChild(root_0, ENDBLOCK19_tree); + + + } + + + } + break; + + } + retval.stop = input.LT(-1); + + retval.tree = (TwigCommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (TwigCommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "twig_block" + + public static class twig_block_param_return extends ParserRuleReturnScope { + TwigCommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "twig_block_param" + // TwigParser.g:81:1: twig_block_param : ( variable | method ) ( twig_print )? ; + public final TwigParser.twig_block_param_return twig_block_param() throws RecognitionException { + TwigParser.twig_block_param_return retval = new TwigParser.twig_block_param_return(); + retval.start = input.LT(1); + + TwigCommonTree root_0 = null; + + TwigParser.variable_return variable20 = null; + + TwigParser.method_return method21 = null; + + TwigParser.twig_print_return twig_print22 = null; + + + + try { + // TwigParser.g:82:3: ( ( variable | method ) ( twig_print )? ) + // TwigParser.g:82:5: ( variable | method ) ( twig_print )? + { + root_0 = (TwigCommonTree)adaptor.nil(); + + // TwigParser.g:82:5: ( variable | method ) + int alt5=2; + alt5 = dfa5.predict(input); + switch (alt5) { + case 1 : + // TwigParser.g:82:6: variable + { + pushFollow(FOLLOW_variable_in_twig_block_param192); + variable20=variable(); + + state._fsp--; + + adaptor.addChild(root_0, variable20.getTree()); + + } + break; + case 2 : + // TwigParser.g:82:17: method + { + pushFollow(FOLLOW_method_in_twig_block_param196); + method21=method(); + + state._fsp--; + + adaptor.addChild(root_0, method21.getTree()); + + } + break; + + } + + // TwigParser.g:82:25: ( twig_print )? + int alt6=2; + int LA6_0 = input.LA(1); + + if ( (LA6_0==ARRAY_START||LA6_0==STRING||LA6_0==STRING_LITERAL) ) { + alt6=1; + } + switch (alt6) { + case 1 : + // TwigParser.g:82:25: twig_print + { + pushFollow(FOLLOW_twig_print_in_twig_block_param199); + twig_print22=twig_print(); + + state._fsp--; + + adaptor.addChild(root_0, twig_print22.getTree()); + + } + break; + + } + + + } + + retval.stop = input.LT(-1); + + retval.tree = (TwigCommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (TwigCommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "twig_block_param" + public static class twig_include_return extends ParserRuleReturnScope { TwigCommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "twig_include" - // TwigParser.g:76:1: twig_include : INCLUDE ( include_ternary | include_statement ) ; + // TwigParser.g:85:1: twig_include : INCLUDE ( include_ternary | include_statement ) ; public final TwigParser.twig_include_return twig_include() throws RecognitionException { TwigParser.twig_include_return retval = new TwigParser.twig_include_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken INCLUDE16=null; - TwigParser.include_ternary_return include_ternary17 = null; + CommonToken INCLUDE23=null; + TwigParser.include_ternary_return include_ternary24 = null; - TwigParser.include_statement_return include_statement18 = null; + TwigParser.include_statement_return include_statement25 = null; - TwigCommonTree INCLUDE16_tree=null; + TwigCommonTree INCLUDE23_tree=null; try { - // TwigParser.g:77:3: ( INCLUDE ( include_ternary | include_statement ) ) - // TwigParser.g:77:5: INCLUDE ( include_ternary | include_statement ) + // TwigParser.g:86:3: ( INCLUDE ( include_ternary | include_statement ) ) + // TwigParser.g:86:5: INCLUDE ( include_ternary | include_statement ) { root_0 = (TwigCommonTree)adaptor.nil(); - INCLUDE16=(CommonToken)match(input,INCLUDE,FOLLOW_INCLUDE_in_twig_include159); - INCLUDE16_tree = (TwigCommonTree)adaptor.create(INCLUDE16); - adaptor.addChild(root_0, INCLUDE16_tree); + INCLUDE23=(CommonToken)match(input,INCLUDE,FOLLOW_INCLUDE_in_twig_include215); + INCLUDE23_tree = (TwigCommonTree)adaptor.create(INCLUDE23); + adaptor.addChild(root_0, INCLUDE23_tree); - // TwigParser.g:77:13: ( include_ternary | include_statement ) - int alt4=2; - int LA4_0 = input.LA(1); + // TwigParser.g:86:13: ( include_ternary | include_statement ) + int alt7=2; + int LA7_0 = input.LA(1); - if ( (LA4_0==STRING_LITERAL) ) { - int LA4_1 = input.LA(2); + if ( (LA7_0==STRING_LITERAL) ) { + int LA7_1 = input.LA(2); - if ( (LA4_1==QM) ) { - alt4=1; + if ( (LA7_1==QM) ) { + alt7=1; } - else if ( (LA4_1==CTRL_CLOSE||(LA4_1>=WITH && LA4_1<=ONLY)) ) { - alt4=2; + else if ( (LA7_1==CTRL_CLOSE||(LA7_1>=WITH && LA7_1<=ONLY)) ) { + alt7=2; } else { NoViableAltException nvae = - new NoViableAltException("", 4, 1, input); + new NoViableAltException("", 7, 1, input); throw nvae; } } - else if ( (LA4_0==NUMBER||LA4_0==STRING) ) { - alt4=1; + else if ( (LA7_0==NUMBER||LA7_0==STRING) ) { + alt7=1; } else { NoViableAltException nvae = - new NoViableAltException("", 4, 0, input); + new NoViableAltException("", 7, 0, input); throw nvae; } - switch (alt4) { + switch (alt7) { case 1 : - // TwigParser.g:77:14: include_ternary + // TwigParser.g:86:14: include_ternary { - pushFollow(FOLLOW_include_ternary_in_twig_include162); - include_ternary17=include_ternary(); + pushFollow(FOLLOW_include_ternary_in_twig_include218); + include_ternary24=include_ternary(); state._fsp--; - adaptor.addChild(root_0, include_ternary17.getTree()); + adaptor.addChild(root_0, include_ternary24.getTree()); } break; case 2 : - // TwigParser.g:77:32: include_statement + // TwigParser.g:86:32: include_statement { - pushFollow(FOLLOW_include_statement_in_twig_include166); - include_statement18=include_statement(); + pushFollow(FOLLOW_include_statement_in_twig_include222); + include_statement25=include_statement(); state._fsp--; - adaptor.addChild(root_0, include_statement18.getTree()); + adaptor.addChild(root_0, include_statement25.getTree()); } break; @@ -664,45 +891,45 @@ public static class include_ternary_return extends ParserRuleReturnScope { }; // $ANTLR start "include_ternary" - // TwigParser.g:80:1: include_ternary : twig_ternary ( ONLY )? ; + // TwigParser.g:89:1: include_ternary : twig_ternary ( ONLY )? ; public final TwigParser.include_ternary_return include_ternary() throws RecognitionException { TwigParser.include_ternary_return retval = new TwigParser.include_ternary_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken ONLY20=null; - TwigParser.twig_ternary_return twig_ternary19 = null; + CommonToken ONLY27=null; + TwigParser.twig_ternary_return twig_ternary26 = null; - TwigCommonTree ONLY20_tree=null; + TwigCommonTree ONLY27_tree=null; try { - // TwigParser.g:81:3: ( twig_ternary ( ONLY )? ) - // TwigParser.g:81:5: twig_ternary ( ONLY )? + // TwigParser.g:90:3: ( twig_ternary ( ONLY )? ) + // TwigParser.g:90:5: twig_ternary ( ONLY )? { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_twig_ternary_in_include_ternary182); - twig_ternary19=twig_ternary(); + pushFollow(FOLLOW_twig_ternary_in_include_ternary238); + twig_ternary26=twig_ternary(); state._fsp--; - adaptor.addChild(root_0, twig_ternary19.getTree()); - // TwigParser.g:81:18: ( ONLY )? - int alt5=2; - int LA5_0 = input.LA(1); + adaptor.addChild(root_0, twig_ternary26.getTree()); + // TwigParser.g:90:18: ( ONLY )? + int alt8=2; + int LA8_0 = input.LA(1); - if ( (LA5_0==ONLY) ) { - alt5=1; + if ( (LA8_0==ONLY) ) { + alt8=1; } - switch (alt5) { + switch (alt8) { case 1 : - // TwigParser.g:81:18: ONLY + // TwigParser.g:90:18: ONLY { - ONLY20=(CommonToken)match(input,ONLY,FOLLOW_ONLY_in_include_ternary184); - ONLY20_tree = (TwigCommonTree)adaptor.create(ONLY20); - adaptor.addChild(root_0, ONLY20_tree); + ONLY27=(CommonToken)match(input,ONLY,FOLLOW_ONLY_in_include_ternary240); + ONLY27_tree = (TwigCommonTree)adaptor.create(ONLY27); + adaptor.addChild(root_0, ONLY27_tree); } @@ -737,61 +964,61 @@ public static class include_statement_return extends ParserRuleReturnScope { }; // $ANTLR start "include_statement" - // TwigParser.g:84:1: include_statement : ( STRING_LITERAL ) ( ONLY )? ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? ; + // TwigParser.g:93:1: include_statement : ( STRING_LITERAL ) ( ONLY )? ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? ; public final TwigParser.include_statement_return include_statement() throws RecognitionException { TwigParser.include_statement_return retval = new TwigParser.include_statement_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING_LITERAL21=null; - CommonToken ONLY22=null; - CommonToken WITH23=null; - CommonToken STRING_LITERAL25=null; - CommonToken ONLY28=null; - TwigParser.variable_return variable24 = null; + CommonToken STRING_LITERAL28=null; + CommonToken ONLY29=null; + CommonToken WITH30=null; + CommonToken STRING_LITERAL32=null; + CommonToken ONLY35=null; + TwigParser.variable_return variable31 = null; - TwigParser.method_return method26 = null; + TwigParser.method_return method33 = null; - TwigParser.json_return json27 = null; + TwigParser.json_return json34 = null; - TwigCommonTree STRING_LITERAL21_tree=null; - TwigCommonTree ONLY22_tree=null; - TwigCommonTree WITH23_tree=null; - TwigCommonTree STRING_LITERAL25_tree=null; - TwigCommonTree ONLY28_tree=null; + TwigCommonTree STRING_LITERAL28_tree=null; + TwigCommonTree ONLY29_tree=null; + TwigCommonTree WITH30_tree=null; + TwigCommonTree STRING_LITERAL32_tree=null; + TwigCommonTree ONLY35_tree=null; try { - // TwigParser.g:85:3: ( ( STRING_LITERAL ) ( ONLY )? ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? ) - // TwigParser.g:85:5: ( STRING_LITERAL ) ( ONLY )? ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? + // TwigParser.g:94:3: ( ( STRING_LITERAL ) ( ONLY )? ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? ) + // TwigParser.g:94:5: ( STRING_LITERAL ) ( ONLY )? ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:85:5: ( STRING_LITERAL ) - // TwigParser.g:85:6: STRING_LITERAL + // TwigParser.g:94:5: ( STRING_LITERAL ) + // TwigParser.g:94:6: STRING_LITERAL { - STRING_LITERAL21=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_include_statement201); - STRING_LITERAL21_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL21); - adaptor.addChild(root_0, STRING_LITERAL21_tree); + STRING_LITERAL28=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_include_statement257); + STRING_LITERAL28_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL28); + adaptor.addChild(root_0, STRING_LITERAL28_tree); } - // TwigParser.g:85:22: ( ONLY )? - int alt6=2; - int LA6_0 = input.LA(1); + // TwigParser.g:94:22: ( ONLY )? + int alt9=2; + int LA9_0 = input.LA(1); - if ( (LA6_0==ONLY) ) { - alt6=1; + if ( (LA9_0==ONLY) ) { + alt9=1; } - switch (alt6) { + switch (alt9) { case 1 : - // TwigParser.g:85:22: ONLY + // TwigParser.g:94:22: ONLY { - ONLY22=(CommonToken)match(input,ONLY,FOLLOW_ONLY_in_include_statement204); - ONLY22_tree = (TwigCommonTree)adaptor.create(ONLY22); - adaptor.addChild(root_0, ONLY22_tree); + ONLY29=(CommonToken)match(input,ONLY,FOLLOW_ONLY_in_include_statement260); + ONLY29_tree = (TwigCommonTree)adaptor.create(ONLY29); + adaptor.addChild(root_0, ONLY29_tree); } @@ -799,88 +1026,88 @@ public final TwigParser.include_statement_return include_statement() throws Reco } - // TwigParser.g:85:28: ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? - int alt9=2; - int LA9_0 = input.LA(1); + // TwigParser.g:94:28: ( WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? )? + int alt12=2; + int LA12_0 = input.LA(1); - if ( (LA9_0==WITH) ) { - alt9=1; + if ( (LA12_0==WITH) ) { + alt12=1; } - switch (alt9) { + switch (alt12) { case 1 : - // TwigParser.g:85:29: WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? + // TwigParser.g:94:29: WITH ( variable | STRING_LITERAL | method | json ) ( ONLY )? { - WITH23=(CommonToken)match(input,WITH,FOLLOW_WITH_in_include_statement208); - WITH23_tree = (TwigCommonTree)adaptor.create(WITH23); - adaptor.addChild(root_0, WITH23_tree); - - // TwigParser.g:85:34: ( variable | STRING_LITERAL | method | json ) - int alt7=4; - alt7 = dfa7.predict(input); - switch (alt7) { + WITH30=(CommonToken)match(input,WITH,FOLLOW_WITH_in_include_statement264); + WITH30_tree = (TwigCommonTree)adaptor.create(WITH30); + adaptor.addChild(root_0, WITH30_tree); + + // TwigParser.g:94:34: ( variable | STRING_LITERAL | method | json ) + int alt10=4; + alt10 = dfa10.predict(input); + switch (alt10) { case 1 : - // TwigParser.g:85:35: variable + // TwigParser.g:94:35: variable { - pushFollow(FOLLOW_variable_in_include_statement211); - variable24=variable(); + pushFollow(FOLLOW_variable_in_include_statement267); + variable31=variable(); state._fsp--; - adaptor.addChild(root_0, variable24.getTree()); + adaptor.addChild(root_0, variable31.getTree()); } break; case 2 : - // TwigParser.g:85:46: STRING_LITERAL + // TwigParser.g:94:46: STRING_LITERAL { - STRING_LITERAL25=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_include_statement215); - STRING_LITERAL25_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL25); - adaptor.addChild(root_0, STRING_LITERAL25_tree); + STRING_LITERAL32=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_include_statement271); + STRING_LITERAL32_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL32); + adaptor.addChild(root_0, STRING_LITERAL32_tree); } break; case 3 : - // TwigParser.g:85:63: method + // TwigParser.g:94:63: method { - pushFollow(FOLLOW_method_in_include_statement219); - method26=method(); + pushFollow(FOLLOW_method_in_include_statement275); + method33=method(); state._fsp--; - adaptor.addChild(root_0, method26.getTree()); + adaptor.addChild(root_0, method33.getTree()); } break; case 4 : - // TwigParser.g:85:72: json + // TwigParser.g:94:72: json { - pushFollow(FOLLOW_json_in_include_statement223); - json27=json(); + pushFollow(FOLLOW_json_in_include_statement279); + json34=json(); state._fsp--; - adaptor.addChild(root_0, json27.getTree()); + adaptor.addChild(root_0, json34.getTree()); } break; } - // TwigParser.g:85:78: ( ONLY )? - int alt8=2; - int LA8_0 = input.LA(1); + // TwigParser.g:94:78: ( ONLY )? + int alt11=2; + int LA11_0 = input.LA(1); - if ( (LA8_0==ONLY) ) { - alt8=1; + if ( (LA11_0==ONLY) ) { + alt11=1; } - switch (alt8) { + switch (alt11) { case 1 : - // TwigParser.g:85:78: ONLY + // TwigParser.g:94:78: ONLY { - ONLY28=(CommonToken)match(input,ONLY,FOLLOW_ONLY_in_include_statement226); - ONLY28_tree = (TwigCommonTree)adaptor.create(ONLY28); - adaptor.addChild(root_0, ONLY28_tree); + ONLY35=(CommonToken)match(input,ONLY,FOLLOW_ONLY_in_include_statement282); + ONLY35_tree = (TwigCommonTree)adaptor.create(ONLY35); + adaptor.addChild(root_0, ONLY35_tree); } @@ -921,92 +1148,92 @@ public static class twig_set_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_set" - // TwigParser.g:88:1: twig_set : ( ( SET twig_assignment ( COMMA twig_assignment )* ) | ENDSET ); + // TwigParser.g:97:1: twig_set : ( ( SET twig_assignment ( COMMA twig_assignment )* ) | ENDSET ); public final TwigParser.twig_set_return twig_set() throws RecognitionException { TwigParser.twig_set_return retval = new TwigParser.twig_set_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken SET29=null; - CommonToken COMMA31=null; - CommonToken ENDSET33=null; - TwigParser.twig_assignment_return twig_assignment30 = null; + CommonToken SET36=null; + CommonToken COMMA38=null; + CommonToken ENDSET40=null; + TwigParser.twig_assignment_return twig_assignment37 = null; - TwigParser.twig_assignment_return twig_assignment32 = null; + TwigParser.twig_assignment_return twig_assignment39 = null; - TwigCommonTree SET29_tree=null; - TwigCommonTree COMMA31_tree=null; - TwigCommonTree ENDSET33_tree=null; + TwigCommonTree SET36_tree=null; + TwigCommonTree COMMA38_tree=null; + TwigCommonTree ENDSET40_tree=null; try { - // TwigParser.g:89:3: ( ( SET twig_assignment ( COMMA twig_assignment )* ) | ENDSET ) - int alt11=2; - int LA11_0 = input.LA(1); + // TwigParser.g:98:3: ( ( SET twig_assignment ( COMMA twig_assignment )* ) | ENDSET ) + int alt14=2; + int LA14_0 = input.LA(1); - if ( (LA11_0==SET) ) { - alt11=1; + if ( (LA14_0==SET) ) { + alt14=1; } - else if ( (LA11_0==ENDSET) ) { - alt11=2; + else if ( (LA14_0==ENDSET) ) { + alt14=2; } else { NoViableAltException nvae = - new NoViableAltException("", 11, 0, input); + new NoViableAltException("", 14, 0, input); throw nvae; } - switch (alt11) { + switch (alt14) { case 1 : - // TwigParser.g:89:5: ( SET twig_assignment ( COMMA twig_assignment )* ) + // TwigParser.g:98:5: ( SET twig_assignment ( COMMA twig_assignment )* ) { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:89:5: ( SET twig_assignment ( COMMA twig_assignment )* ) - // TwigParser.g:89:6: SET twig_assignment ( COMMA twig_assignment )* + // TwigParser.g:98:5: ( SET twig_assignment ( COMMA twig_assignment )* ) + // TwigParser.g:98:6: SET twig_assignment ( COMMA twig_assignment )* { - SET29=(CommonToken)match(input,SET,FOLLOW_SET_in_twig_set245); - SET29_tree = (TwigCommonTree)adaptor.create(SET29); - adaptor.addChild(root_0, SET29_tree); + SET36=(CommonToken)match(input,SET,FOLLOW_SET_in_twig_set301); + SET36_tree = (TwigCommonTree)adaptor.create(SET36); + adaptor.addChild(root_0, SET36_tree); - pushFollow(FOLLOW_twig_assignment_in_twig_set247); - twig_assignment30=twig_assignment(); + pushFollow(FOLLOW_twig_assignment_in_twig_set303); + twig_assignment37=twig_assignment(); state._fsp--; - adaptor.addChild(root_0, twig_assignment30.getTree()); - // TwigParser.g:89:26: ( COMMA twig_assignment )* - loop10: + adaptor.addChild(root_0, twig_assignment37.getTree()); + // TwigParser.g:98:26: ( COMMA twig_assignment )* + loop13: do { - int alt10=2; - int LA10_0 = input.LA(1); + int alt13=2; + int LA13_0 = input.LA(1); - if ( (LA10_0==COMMA) ) { - alt10=1; + if ( (LA13_0==COMMA) ) { + alt13=1; } - switch (alt10) { + switch (alt13) { case 1 : - // TwigParser.g:89:27: COMMA twig_assignment + // TwigParser.g:98:27: COMMA twig_assignment { - COMMA31=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_set250); - COMMA31_tree = (TwigCommonTree)adaptor.create(COMMA31); - adaptor.addChild(root_0, COMMA31_tree); + COMMA38=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_set306); + COMMA38_tree = (TwigCommonTree)adaptor.create(COMMA38); + adaptor.addChild(root_0, COMMA38_tree); - pushFollow(FOLLOW_twig_assignment_in_twig_set252); - twig_assignment32=twig_assignment(); + pushFollow(FOLLOW_twig_assignment_in_twig_set308); + twig_assignment39=twig_assignment(); state._fsp--; - adaptor.addChild(root_0, twig_assignment32.getTree()); + adaptor.addChild(root_0, twig_assignment39.getTree()); } break; default : - break loop10; + break loop13; } } while (true); @@ -1017,13 +1244,13 @@ else if ( (LA11_0==ENDSET) ) { } break; case 2 : - // TwigParser.g:89:54: ENDSET + // TwigParser.g:98:54: ENDSET { root_0 = (TwigCommonTree)adaptor.nil(); - ENDSET33=(CommonToken)match(input,ENDSET,FOLLOW_ENDSET_in_twig_set259); - ENDSET33_tree = (TwigCommonTree)adaptor.create(ENDSET33); - adaptor.addChild(root_0, ENDSET33_tree); + ENDSET40=(CommonToken)match(input,ENDSET,FOLLOW_ENDSET_in_twig_set315); + ENDSET40_tree = (TwigCommonTree)adaptor.create(ENDSET40); + adaptor.addChild(root_0, ENDSET40_tree); } @@ -1054,54 +1281,54 @@ public static class twig_assignment_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_assignment" - // TwigParser.g:92:1: twig_assignment : twig_left_assignment ( ASIG twig_right_assignment )? ; + // TwigParser.g:101:1: twig_assignment : twig_left_assignment ( ASIG twig_right_assignment )? ; public final TwigParser.twig_assignment_return twig_assignment() throws RecognitionException { TwigParser.twig_assignment_return retval = new TwigParser.twig_assignment_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken ASIG35=null; - TwigParser.twig_left_assignment_return twig_left_assignment34 = null; + CommonToken ASIG42=null; + TwigParser.twig_left_assignment_return twig_left_assignment41 = null; - TwigParser.twig_right_assignment_return twig_right_assignment36 = null; + TwigParser.twig_right_assignment_return twig_right_assignment43 = null; - TwigCommonTree ASIG35_tree=null; + TwigCommonTree ASIG42_tree=null; try { - // TwigParser.g:93:3: ( twig_left_assignment ( ASIG twig_right_assignment )? ) - // TwigParser.g:93:6: twig_left_assignment ( ASIG twig_right_assignment )? + // TwigParser.g:102:3: ( twig_left_assignment ( ASIG twig_right_assignment )? ) + // TwigParser.g:102:6: twig_left_assignment ( ASIG twig_right_assignment )? { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_twig_left_assignment_in_twig_assignment274); - twig_left_assignment34=twig_left_assignment(); + pushFollow(FOLLOW_twig_left_assignment_in_twig_assignment330); + twig_left_assignment41=twig_left_assignment(); state._fsp--; - adaptor.addChild(root_0, twig_left_assignment34.getTree()); - // TwigParser.g:93:27: ( ASIG twig_right_assignment )? - int alt12=2; - int LA12_0 = input.LA(1); + adaptor.addChild(root_0, twig_left_assignment41.getTree()); + // TwigParser.g:102:27: ( ASIG twig_right_assignment )? + int alt15=2; + int LA15_0 = input.LA(1); - if ( (LA12_0==ASIG) ) { - alt12=1; + if ( (LA15_0==ASIG) ) { + alt15=1; } - switch (alt12) { + switch (alt15) { case 1 : - // TwigParser.g:93:28: ASIG twig_right_assignment + // TwigParser.g:102:28: ASIG twig_right_assignment { - ASIG35=(CommonToken)match(input,ASIG,FOLLOW_ASIG_in_twig_assignment277); - ASIG35_tree = (TwigCommonTree)adaptor.create(ASIG35); - adaptor.addChild(root_0, ASIG35_tree); + ASIG42=(CommonToken)match(input,ASIG,FOLLOW_ASIG_in_twig_assignment333); + ASIG42_tree = (TwigCommonTree)adaptor.create(ASIG42); + adaptor.addChild(root_0, ASIG42_tree); - pushFollow(FOLLOW_twig_right_assignment_in_twig_assignment279); - twig_right_assignment36=twig_right_assignment(); + pushFollow(FOLLOW_twig_right_assignment_in_twig_assignment335); + twig_right_assignment43=twig_right_assignment(); state._fsp--; - adaptor.addChild(root_0, twig_right_assignment36.getTree()); + adaptor.addChild(root_0, twig_right_assignment43.getTree()); } break; @@ -1135,73 +1362,73 @@ public static class twig_left_assignment_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_left_assignment" - // TwigParser.g:96:1: twig_left_assignment : ( variable ( COMMA variable )* ) ; + // TwigParser.g:105:1: twig_left_assignment : ( variable ( COMMA variable )* ) ; public final TwigParser.twig_left_assignment_return twig_left_assignment() throws RecognitionException { TwigParser.twig_left_assignment_return retval = new TwigParser.twig_left_assignment_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken COMMA38=null; - TwigParser.variable_return variable37 = null; + CommonToken COMMA45=null; + TwigParser.variable_return variable44 = null; - TwigParser.variable_return variable39 = null; + TwigParser.variable_return variable46 = null; - TwigCommonTree COMMA38_tree=null; + TwigCommonTree COMMA45_tree=null; try { - // TwigParser.g:97:3: ( ( variable ( COMMA variable )* ) ) - // TwigParser.g:97:5: ( variable ( COMMA variable )* ) + // TwigParser.g:106:3: ( ( variable ( COMMA variable )* ) ) + // TwigParser.g:106:5: ( variable ( COMMA variable )* ) { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:97:5: ( variable ( COMMA variable )* ) - // TwigParser.g:97:6: variable ( COMMA variable )* + // TwigParser.g:106:5: ( variable ( COMMA variable )* ) + // TwigParser.g:106:6: variable ( COMMA variable )* { - pushFollow(FOLLOW_variable_in_twig_left_assignment297); - variable37=variable(); + pushFollow(FOLLOW_variable_in_twig_left_assignment353); + variable44=variable(); state._fsp--; - adaptor.addChild(root_0, variable37.getTree()); - // TwigParser.g:97:15: ( COMMA variable )* - loop13: + adaptor.addChild(root_0, variable44.getTree()); + // TwigParser.g:106:15: ( COMMA variable )* + loop16: do { - int alt13=2; - int LA13_0 = input.LA(1); + int alt16=2; + int LA16_0 = input.LA(1); - if ( (LA13_0==COMMA) ) { - int LA13_2 = input.LA(2); + if ( (LA16_0==COMMA) ) { + int LA16_2 = input.LA(2); - if ( (LA13_2==STRING) ) { - alt13=1; + if ( (LA16_2==STRING) ) { + alt16=1; } } - switch (alt13) { + switch (alt16) { case 1 : - // TwigParser.g:97:16: COMMA variable + // TwigParser.g:106:16: COMMA variable { - COMMA38=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_left_assignment300); - COMMA38_tree = (TwigCommonTree)adaptor.create(COMMA38); - adaptor.addChild(root_0, COMMA38_tree); + COMMA45=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_left_assignment356); + COMMA45_tree = (TwigCommonTree)adaptor.create(COMMA45); + adaptor.addChild(root_0, COMMA45_tree); - pushFollow(FOLLOW_variable_in_twig_left_assignment302); - variable39=variable(); + pushFollow(FOLLOW_variable_in_twig_left_assignment358); + variable46=variable(); state._fsp--; - adaptor.addChild(root_0, variable39.getTree()); + adaptor.addChild(root_0, variable46.getTree()); } break; default : - break loop13; + break loop16; } } while (true); @@ -1235,26 +1462,16 @@ public static class twig_right_assignment_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_right_assignment" - // TwigParser.g:100:1: twig_right_assignment : ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* ; + // TwigParser.g:109:1: twig_right_assignment : ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* ; public final TwigParser.twig_right_assignment_return twig_right_assignment() throws RecognitionException { TwigParser.twig_right_assignment_return retval = new TwigParser.twig_right_assignment_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING_LITERAL40=null; - CommonToken COMMA46=null; CommonToken STRING_LITERAL47=null; - TwigParser.variable_return variable41 = null; - - TwigParser.method_return method42 = null; - - TwigParser.array_return array43 = null; - - TwigParser.json_return json44 = null; - - TwigParser.twig_tilde_argument_return twig_tilde_argument45 = null; - + CommonToken COMMA53=null; + CommonToken STRING_LITERAL54=null; TwigParser.variable_return variable48 = null; TwigParser.method_return method49 = null; @@ -1265,190 +1482,200 @@ public final TwigParser.twig_right_assignment_return twig_right_assignment() thr TwigParser.twig_tilde_argument_return twig_tilde_argument52 = null; + TwigParser.variable_return variable55 = null; + + TwigParser.method_return method56 = null; + + TwigParser.array_return array57 = null; + + TwigParser.json_return json58 = null; + + TwigParser.twig_tilde_argument_return twig_tilde_argument59 = null; + - TwigCommonTree STRING_LITERAL40_tree=null; - TwigCommonTree COMMA46_tree=null; TwigCommonTree STRING_LITERAL47_tree=null; + TwigCommonTree COMMA53_tree=null; + TwigCommonTree STRING_LITERAL54_tree=null; try { - // TwigParser.g:101:3: ( ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* ) - // TwigParser.g:101:5: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* + // TwigParser.g:110:3: ( ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* ) + // TwigParser.g:110:5: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:101:5: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) - int alt14=6; - alt14 = dfa14.predict(input); - switch (alt14) { + // TwigParser.g:110:5: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) + int alt17=6; + alt17 = dfa17.predict(input); + switch (alt17) { case 1 : - // TwigParser.g:101:6: STRING_LITERAL + // TwigParser.g:110:6: STRING_LITERAL { - STRING_LITERAL40=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_right_assignment321); - STRING_LITERAL40_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL40); - adaptor.addChild(root_0, STRING_LITERAL40_tree); + STRING_LITERAL47=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_right_assignment377); + STRING_LITERAL47_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL47); + adaptor.addChild(root_0, STRING_LITERAL47_tree); } break; case 2 : - // TwigParser.g:101:23: variable + // TwigParser.g:110:23: variable { - pushFollow(FOLLOW_variable_in_twig_right_assignment325); - variable41=variable(); + pushFollow(FOLLOW_variable_in_twig_right_assignment381); + variable48=variable(); state._fsp--; - adaptor.addChild(root_0, variable41.getTree()); + adaptor.addChild(root_0, variable48.getTree()); } break; case 3 : - // TwigParser.g:101:34: method + // TwigParser.g:110:34: method { - pushFollow(FOLLOW_method_in_twig_right_assignment329); - method42=method(); + pushFollow(FOLLOW_method_in_twig_right_assignment385); + method49=method(); state._fsp--; - adaptor.addChild(root_0, method42.getTree()); + adaptor.addChild(root_0, method49.getTree()); } break; case 4 : - // TwigParser.g:101:43: array + // TwigParser.g:110:43: array { - pushFollow(FOLLOW_array_in_twig_right_assignment333); - array43=array(); + pushFollow(FOLLOW_array_in_twig_right_assignment389); + array50=array(); state._fsp--; - adaptor.addChild(root_0, array43.getTree()); + adaptor.addChild(root_0, array50.getTree()); } break; case 5 : - // TwigParser.g:101:51: json + // TwigParser.g:110:51: json { - pushFollow(FOLLOW_json_in_twig_right_assignment337); - json44=json(); + pushFollow(FOLLOW_json_in_twig_right_assignment393); + json51=json(); state._fsp--; - adaptor.addChild(root_0, json44.getTree()); + adaptor.addChild(root_0, json51.getTree()); } break; case 6 : - // TwigParser.g:101:58: twig_tilde_argument + // TwigParser.g:110:58: twig_tilde_argument { - pushFollow(FOLLOW_twig_tilde_argument_in_twig_right_assignment341); - twig_tilde_argument45=twig_tilde_argument(); + pushFollow(FOLLOW_twig_tilde_argument_in_twig_right_assignment397); + twig_tilde_argument52=twig_tilde_argument(); state._fsp--; - adaptor.addChild(root_0, twig_tilde_argument45.getTree()); + adaptor.addChild(root_0, twig_tilde_argument52.getTree()); } break; } - // TwigParser.g:101:79: ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* - loop16: + // TwigParser.g:110:79: ( COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) )* + loop19: do { - int alt16=2; - int LA16_0 = input.LA(1); + int alt19=2; + int LA19_0 = input.LA(1); - if ( (LA16_0==COMMA) ) { - int LA16_1 = input.LA(2); + if ( (LA19_0==COMMA) ) { + int LA19_1 = input.LA(2); - if ( (LA16_1==ARRAY_START||LA16_1==JSON_START||LA16_1==STRING||LA16_1==STRING_LITERAL) ) { - alt16=1; + if ( (LA19_1==ARRAY_START||LA19_1==JSON_START||LA19_1==STRING||LA19_1==STRING_LITERAL) ) { + alt19=1; } } - switch (alt16) { + switch (alt19) { case 1 : - // TwigParser.g:101:80: COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) + // TwigParser.g:110:80: COMMA ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) { - COMMA46=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_right_assignment345); - COMMA46_tree = (TwigCommonTree)adaptor.create(COMMA46); - adaptor.addChild(root_0, COMMA46_tree); - - // TwigParser.g:101:86: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) - int alt15=6; - alt15 = dfa15.predict(input); - switch (alt15) { + COMMA53=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_right_assignment401); + COMMA53_tree = (TwigCommonTree)adaptor.create(COMMA53); + adaptor.addChild(root_0, COMMA53_tree); + + // TwigParser.g:110:86: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument ) + int alt18=6; + alt18 = dfa18.predict(input); + switch (alt18) { case 1 : - // TwigParser.g:101:87: STRING_LITERAL + // TwigParser.g:110:87: STRING_LITERAL { - STRING_LITERAL47=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_right_assignment348); - STRING_LITERAL47_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL47); - adaptor.addChild(root_0, STRING_LITERAL47_tree); + STRING_LITERAL54=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_right_assignment404); + STRING_LITERAL54_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL54); + adaptor.addChild(root_0, STRING_LITERAL54_tree); } break; case 2 : - // TwigParser.g:101:104: variable + // TwigParser.g:110:104: variable { - pushFollow(FOLLOW_variable_in_twig_right_assignment352); - variable48=variable(); + pushFollow(FOLLOW_variable_in_twig_right_assignment408); + variable55=variable(); state._fsp--; - adaptor.addChild(root_0, variable48.getTree()); + adaptor.addChild(root_0, variable55.getTree()); } break; case 3 : - // TwigParser.g:101:115: method + // TwigParser.g:110:115: method { - pushFollow(FOLLOW_method_in_twig_right_assignment356); - method49=method(); + pushFollow(FOLLOW_method_in_twig_right_assignment412); + method56=method(); state._fsp--; - adaptor.addChild(root_0, method49.getTree()); + adaptor.addChild(root_0, method56.getTree()); } break; case 4 : - // TwigParser.g:101:124: array + // TwigParser.g:110:124: array { - pushFollow(FOLLOW_array_in_twig_right_assignment360); - array50=array(); + pushFollow(FOLLOW_array_in_twig_right_assignment416); + array57=array(); state._fsp--; - adaptor.addChild(root_0, array50.getTree()); + adaptor.addChild(root_0, array57.getTree()); } break; case 5 : - // TwigParser.g:101:132: json + // TwigParser.g:110:132: json { - pushFollow(FOLLOW_json_in_twig_right_assignment364); - json51=json(); + pushFollow(FOLLOW_json_in_twig_right_assignment420); + json58=json(); state._fsp--; - adaptor.addChild(root_0, json51.getTree()); + adaptor.addChild(root_0, json58.getTree()); } break; case 6 : - // TwigParser.g:101:139: twig_tilde_argument + // TwigParser.g:110:139: twig_tilde_argument { - pushFollow(FOLLOW_twig_tilde_argument_in_twig_right_assignment368); - twig_tilde_argument52=twig_tilde_argument(); + pushFollow(FOLLOW_twig_tilde_argument_in_twig_right_assignment424); + twig_tilde_argument59=twig_tilde_argument(); state._fsp--; - adaptor.addChild(root_0, twig_tilde_argument52.getTree()); + adaptor.addChild(root_0, twig_tilde_argument59.getTree()); } break; @@ -1460,7 +1687,7 @@ public final TwigParser.twig_right_assignment_return twig_right_assignment() thr break; default : - break loop16; + break loop19; } } while (true); @@ -1491,171 +1718,171 @@ public static class twig_tilde_argument_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_tilde_argument" - // TwigParser.g:104:1: twig_tilde_argument : ( STRING_LITERAL | variable | method | array | json ) TILDE ( STRING_LITERAL | variable | method | array | json ) ; + // TwigParser.g:113:1: twig_tilde_argument : ( STRING_LITERAL | variable | method | array | json ) TILDE ( STRING_LITERAL | variable | method | array | json ) ; public final TwigParser.twig_tilde_argument_return twig_tilde_argument() throws RecognitionException { TwigParser.twig_tilde_argument_return retval = new TwigParser.twig_tilde_argument_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING_LITERAL53=null; - CommonToken TILDE58=null; - CommonToken STRING_LITERAL59=null; - TwigParser.variable_return variable54 = null; + CommonToken STRING_LITERAL60=null; + CommonToken TILDE65=null; + CommonToken STRING_LITERAL66=null; + TwigParser.variable_return variable61 = null; - TwigParser.method_return method55 = null; + TwigParser.method_return method62 = null; - TwigParser.array_return array56 = null; + TwigParser.array_return array63 = null; - TwigParser.json_return json57 = null; + TwigParser.json_return json64 = null; - TwigParser.variable_return variable60 = null; + TwigParser.variable_return variable67 = null; - TwigParser.method_return method61 = null; + TwigParser.method_return method68 = null; - TwigParser.array_return array62 = null; + TwigParser.array_return array69 = null; - TwigParser.json_return json63 = null; + TwigParser.json_return json70 = null; - TwigCommonTree STRING_LITERAL53_tree=null; - TwigCommonTree TILDE58_tree=null; - TwigCommonTree STRING_LITERAL59_tree=null; + TwigCommonTree STRING_LITERAL60_tree=null; + TwigCommonTree TILDE65_tree=null; + TwigCommonTree STRING_LITERAL66_tree=null; try { - // TwigParser.g:105:3: ( ( STRING_LITERAL | variable | method | array | json ) TILDE ( STRING_LITERAL | variable | method | array | json ) ) - // TwigParser.g:105:5: ( STRING_LITERAL | variable | method | array | json ) TILDE ( STRING_LITERAL | variable | method | array | json ) + // TwigParser.g:114:3: ( ( STRING_LITERAL | variable | method | array | json ) TILDE ( STRING_LITERAL | variable | method | array | json ) ) + // TwigParser.g:114:5: ( STRING_LITERAL | variable | method | array | json ) TILDE ( STRING_LITERAL | variable | method | array | json ) { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:105:5: ( STRING_LITERAL | variable | method | array | json ) - int alt17=5; - alt17 = dfa17.predict(input); - switch (alt17) { + // TwigParser.g:114:5: ( STRING_LITERAL | variable | method | array | json ) + int alt20=5; + alt20 = dfa20.predict(input); + switch (alt20) { case 1 : - // TwigParser.g:105:6: STRING_LITERAL + // TwigParser.g:114:6: STRING_LITERAL { - STRING_LITERAL53=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_tilde_argument387); - STRING_LITERAL53_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL53); - adaptor.addChild(root_0, STRING_LITERAL53_tree); + STRING_LITERAL60=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_tilde_argument443); + STRING_LITERAL60_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL60); + adaptor.addChild(root_0, STRING_LITERAL60_tree); } break; case 2 : - // TwigParser.g:105:23: variable + // TwigParser.g:114:23: variable { - pushFollow(FOLLOW_variable_in_twig_tilde_argument391); - variable54=variable(); + pushFollow(FOLLOW_variable_in_twig_tilde_argument447); + variable61=variable(); state._fsp--; - adaptor.addChild(root_0, variable54.getTree()); + adaptor.addChild(root_0, variable61.getTree()); } break; case 3 : - // TwigParser.g:105:34: method + // TwigParser.g:114:34: method { - pushFollow(FOLLOW_method_in_twig_tilde_argument395); - method55=method(); + pushFollow(FOLLOW_method_in_twig_tilde_argument451); + method62=method(); state._fsp--; - adaptor.addChild(root_0, method55.getTree()); + adaptor.addChild(root_0, method62.getTree()); } break; case 4 : - // TwigParser.g:105:43: array + // TwigParser.g:114:43: array { - pushFollow(FOLLOW_array_in_twig_tilde_argument399); - array56=array(); + pushFollow(FOLLOW_array_in_twig_tilde_argument455); + array63=array(); state._fsp--; - adaptor.addChild(root_0, array56.getTree()); + adaptor.addChild(root_0, array63.getTree()); } break; case 5 : - // TwigParser.g:105:51: json + // TwigParser.g:114:51: json { - pushFollow(FOLLOW_json_in_twig_tilde_argument403); - json57=json(); + pushFollow(FOLLOW_json_in_twig_tilde_argument459); + json64=json(); state._fsp--; - adaptor.addChild(root_0, json57.getTree()); + adaptor.addChild(root_0, json64.getTree()); } break; } - TILDE58=(CommonToken)match(input,TILDE,FOLLOW_TILDE_in_twig_tilde_argument406); - TILDE58_tree = (TwigCommonTree)adaptor.create(TILDE58); - adaptor.addChild(root_0, TILDE58_tree); + TILDE65=(CommonToken)match(input,TILDE,FOLLOW_TILDE_in_twig_tilde_argument462); + TILDE65_tree = (TwigCommonTree)adaptor.create(TILDE65); + adaptor.addChild(root_0, TILDE65_tree); - // TwigParser.g:105:63: ( STRING_LITERAL | variable | method | array | json ) - int alt18=5; - alt18 = dfa18.predict(input); - switch (alt18) { + // TwigParser.g:114:63: ( STRING_LITERAL | variable | method | array | json ) + int alt21=5; + alt21 = dfa21.predict(input); + switch (alt21) { case 1 : - // TwigParser.g:105:64: STRING_LITERAL + // TwigParser.g:114:64: STRING_LITERAL { - STRING_LITERAL59=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_tilde_argument409); - STRING_LITERAL59_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL59); - adaptor.addChild(root_0, STRING_LITERAL59_tree); + STRING_LITERAL66=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_tilde_argument465); + STRING_LITERAL66_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL66); + adaptor.addChild(root_0, STRING_LITERAL66_tree); } break; case 2 : - // TwigParser.g:105:81: variable + // TwigParser.g:114:81: variable { - pushFollow(FOLLOW_variable_in_twig_tilde_argument413); - variable60=variable(); + pushFollow(FOLLOW_variable_in_twig_tilde_argument469); + variable67=variable(); state._fsp--; - adaptor.addChild(root_0, variable60.getTree()); + adaptor.addChild(root_0, variable67.getTree()); } break; case 3 : - // TwigParser.g:105:92: method + // TwigParser.g:114:92: method { - pushFollow(FOLLOW_method_in_twig_tilde_argument417); - method61=method(); + pushFollow(FOLLOW_method_in_twig_tilde_argument473); + method68=method(); state._fsp--; - adaptor.addChild(root_0, method61.getTree()); + adaptor.addChild(root_0, method68.getTree()); } break; case 4 : - // TwigParser.g:105:101: array + // TwigParser.g:114:101: array { - pushFollow(FOLLOW_array_in_twig_tilde_argument421); - array62=array(); + pushFollow(FOLLOW_array_in_twig_tilde_argument477); + array69=array(); state._fsp--; - adaptor.addChild(root_0, array62.getTree()); + adaptor.addChild(root_0, array69.getTree()); } break; case 5 : - // TwigParser.g:105:109: json + // TwigParser.g:114:109: json { - pushFollow(FOLLOW_json_in_twig_tilde_argument425); - json63=json(); + pushFollow(FOLLOW_json_in_twig_tilde_argument481); + json70=json(); state._fsp--; - adaptor.addChild(root_0, json63.getTree()); + adaptor.addChild(root_0, json70.getTree()); } break; @@ -1689,60 +1916,60 @@ public static class twig_import_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_import" - // TwigParser.g:108:1: twig_import : ( FROM ( STRING_LITERAL ) )? IMPORT ( STRING_LITERAL | variable ) ( TWIG_AS ( STRING ( COMMA STRING )* ) )? ; + // TwigParser.g:117:1: twig_import : ( FROM ( STRING_LITERAL ) )? IMPORT ( STRING_LITERAL | variable ) ( TWIG_AS ( STRING ( COMMA STRING )* ) )? ; public final TwigParser.twig_import_return twig_import() throws RecognitionException { TwigParser.twig_import_return retval = new TwigParser.twig_import_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken FROM64=null; - CommonToken STRING_LITERAL65=null; - CommonToken IMPORT66=null; - CommonToken STRING_LITERAL67=null; - CommonToken TWIG_AS69=null; - CommonToken STRING70=null; - CommonToken COMMA71=null; - CommonToken STRING72=null; - TwigParser.variable_return variable68 = null; - - - TwigCommonTree FROM64_tree=null; - TwigCommonTree STRING_LITERAL65_tree=null; - TwigCommonTree IMPORT66_tree=null; - TwigCommonTree STRING_LITERAL67_tree=null; - TwigCommonTree TWIG_AS69_tree=null; - TwigCommonTree STRING70_tree=null; - TwigCommonTree COMMA71_tree=null; - TwigCommonTree STRING72_tree=null; + CommonToken FROM71=null; + CommonToken STRING_LITERAL72=null; + CommonToken IMPORT73=null; + CommonToken STRING_LITERAL74=null; + CommonToken TWIG_AS76=null; + CommonToken STRING77=null; + CommonToken COMMA78=null; + CommonToken STRING79=null; + TwigParser.variable_return variable75 = null; + + + TwigCommonTree FROM71_tree=null; + TwigCommonTree STRING_LITERAL72_tree=null; + TwigCommonTree IMPORT73_tree=null; + TwigCommonTree STRING_LITERAL74_tree=null; + TwigCommonTree TWIG_AS76_tree=null; + TwigCommonTree STRING77_tree=null; + TwigCommonTree COMMA78_tree=null; + TwigCommonTree STRING79_tree=null; try { - // TwigParser.g:109:3: ( ( FROM ( STRING_LITERAL ) )? IMPORT ( STRING_LITERAL | variable ) ( TWIG_AS ( STRING ( COMMA STRING )* ) )? ) - // TwigParser.g:109:5: ( FROM ( STRING_LITERAL ) )? IMPORT ( STRING_LITERAL | variable ) ( TWIG_AS ( STRING ( COMMA STRING )* ) )? + // TwigParser.g:118:3: ( ( FROM ( STRING_LITERAL ) )? IMPORT ( STRING_LITERAL | variable ) ( TWIG_AS ( STRING ( COMMA STRING )* ) )? ) + // TwigParser.g:118:5: ( FROM ( STRING_LITERAL ) )? IMPORT ( STRING_LITERAL | variable ) ( TWIG_AS ( STRING ( COMMA STRING )* ) )? { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:109:5: ( FROM ( STRING_LITERAL ) )? - int alt19=2; - int LA19_0 = input.LA(1); + // TwigParser.g:118:5: ( FROM ( STRING_LITERAL ) )? + int alt22=2; + int LA22_0 = input.LA(1); - if ( (LA19_0==FROM) ) { - alt19=1; + if ( (LA22_0==FROM) ) { + alt22=1; } - switch (alt19) { + switch (alt22) { case 1 : - // TwigParser.g:109:6: FROM ( STRING_LITERAL ) + // TwigParser.g:118:6: FROM ( STRING_LITERAL ) { - FROM64=(CommonToken)match(input,FROM,FOLLOW_FROM_in_twig_import442); - FROM64_tree = (TwigCommonTree)adaptor.create(FROM64); - adaptor.addChild(root_0, FROM64_tree); + FROM71=(CommonToken)match(input,FROM,FOLLOW_FROM_in_twig_import498); + FROM71_tree = (TwigCommonTree)adaptor.create(FROM71); + adaptor.addChild(root_0, FROM71_tree); - // TwigParser.g:109:11: ( STRING_LITERAL ) - // TwigParser.g:109:12: STRING_LITERAL + // TwigParser.g:118:11: ( STRING_LITERAL ) + // TwigParser.g:118:12: STRING_LITERAL { - STRING_LITERAL65=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_import445); - STRING_LITERAL65_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL65); - adaptor.addChild(root_0, STRING_LITERAL65_tree); + STRING_LITERAL72=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_import501); + STRING_LITERAL72_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL72); + adaptor.addChild(root_0, STRING_LITERAL72_tree); } @@ -1753,103 +1980,103 @@ public final TwigParser.twig_import_return twig_import() throws RecognitionExcep } - IMPORT66=(CommonToken)match(input,IMPORT,FOLLOW_IMPORT_in_twig_import450); - IMPORT66_tree = (TwigCommonTree)adaptor.create(IMPORT66); - adaptor.addChild(root_0, IMPORT66_tree); + IMPORT73=(CommonToken)match(input,IMPORT,FOLLOW_IMPORT_in_twig_import506); + IMPORT73_tree = (TwigCommonTree)adaptor.create(IMPORT73); + adaptor.addChild(root_0, IMPORT73_tree); - // TwigParser.g:109:37: ( STRING_LITERAL | variable ) - int alt20=2; - int LA20_0 = input.LA(1); + // TwigParser.g:118:37: ( STRING_LITERAL | variable ) + int alt23=2; + int LA23_0 = input.LA(1); - if ( (LA20_0==STRING_LITERAL) ) { - alt20=1; + if ( (LA23_0==STRING_LITERAL) ) { + alt23=1; } - else if ( (LA20_0==STRING) ) { - alt20=2; + else if ( (LA23_0==STRING) ) { + alt23=2; } else { NoViableAltException nvae = - new NoViableAltException("", 20, 0, input); + new NoViableAltException("", 23, 0, input); throw nvae; } - switch (alt20) { + switch (alt23) { case 1 : - // TwigParser.g:109:38: STRING_LITERAL + // TwigParser.g:118:38: STRING_LITERAL { - STRING_LITERAL67=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_import453); - STRING_LITERAL67_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL67); - adaptor.addChild(root_0, STRING_LITERAL67_tree); + STRING_LITERAL74=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_import509); + STRING_LITERAL74_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL74); + adaptor.addChild(root_0, STRING_LITERAL74_tree); } break; case 2 : - // TwigParser.g:109:55: variable + // TwigParser.g:118:55: variable { - pushFollow(FOLLOW_variable_in_twig_import457); - variable68=variable(); + pushFollow(FOLLOW_variable_in_twig_import513); + variable75=variable(); state._fsp--; - adaptor.addChild(root_0, variable68.getTree()); + adaptor.addChild(root_0, variable75.getTree()); } break; } - // TwigParser.g:109:65: ( TWIG_AS ( STRING ( COMMA STRING )* ) )? - int alt22=2; - int LA22_0 = input.LA(1); + // TwigParser.g:118:65: ( TWIG_AS ( STRING ( COMMA STRING )* ) )? + int alt25=2; + int LA25_0 = input.LA(1); - if ( (LA22_0==TWIG_AS) ) { - alt22=1; + if ( (LA25_0==TWIG_AS) ) { + alt25=1; } - switch (alt22) { + switch (alt25) { case 1 : - // TwigParser.g:109:66: TWIG_AS ( STRING ( COMMA STRING )* ) + // TwigParser.g:118:66: TWIG_AS ( STRING ( COMMA STRING )* ) { - TWIG_AS69=(CommonToken)match(input,TWIG_AS,FOLLOW_TWIG_AS_in_twig_import461); - TWIG_AS69_tree = (TwigCommonTree)adaptor.create(TWIG_AS69); - adaptor.addChild(root_0, TWIG_AS69_tree); + TWIG_AS76=(CommonToken)match(input,TWIG_AS,FOLLOW_TWIG_AS_in_twig_import517); + TWIG_AS76_tree = (TwigCommonTree)adaptor.create(TWIG_AS76); + adaptor.addChild(root_0, TWIG_AS76_tree); - // TwigParser.g:109:74: ( STRING ( COMMA STRING )* ) - // TwigParser.g:109:75: STRING ( COMMA STRING )* + // TwigParser.g:118:74: ( STRING ( COMMA STRING )* ) + // TwigParser.g:118:75: STRING ( COMMA STRING )* { - STRING70=(CommonToken)match(input,STRING,FOLLOW_STRING_in_twig_import464); - STRING70_tree = (TwigCommonTree)adaptor.create(STRING70); - adaptor.addChild(root_0, STRING70_tree); + STRING77=(CommonToken)match(input,STRING,FOLLOW_STRING_in_twig_import520); + STRING77_tree = (TwigCommonTree)adaptor.create(STRING77); + adaptor.addChild(root_0, STRING77_tree); - // TwigParser.g:109:82: ( COMMA STRING )* - loop21: + // TwigParser.g:118:82: ( COMMA STRING )* + loop24: do { - int alt21=2; - int LA21_0 = input.LA(1); + int alt24=2; + int LA24_0 = input.LA(1); - if ( (LA21_0==COMMA) ) { - alt21=1; + if ( (LA24_0==COMMA) ) { + alt24=1; } - switch (alt21) { + switch (alt24) { case 1 : - // TwigParser.g:109:83: COMMA STRING + // TwigParser.g:118:83: COMMA STRING { - COMMA71=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_import467); - COMMA71_tree = (TwigCommonTree)adaptor.create(COMMA71); - adaptor.addChild(root_0, COMMA71_tree); + COMMA78=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_twig_import523); + COMMA78_tree = (TwigCommonTree)adaptor.create(COMMA78); + adaptor.addChild(root_0, COMMA78_tree); - STRING72=(CommonToken)match(input,STRING,FOLLOW_STRING_in_twig_import469); - STRING72_tree = (TwigCommonTree)adaptor.create(STRING72); - adaptor.addChild(root_0, STRING72_tree); + STRING79=(CommonToken)match(input,STRING,FOLLOW_STRING_in_twig_import525); + STRING79_tree = (TwigCommonTree)adaptor.create(STRING79); + adaptor.addChild(root_0, STRING79_tree); } break; default : - break loop21; + break loop24; } } while (true); @@ -1889,78 +2116,78 @@ public static class twig_macro_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_macro" - // TwigParser.g:112:1: twig_macro : ( ( MACRO ( variable | method ) ) | ENDMACRO ); + // TwigParser.g:121:1: twig_macro : ( ( MACRO ( variable | method ) ) | ENDMACRO ); public final TwigParser.twig_macro_return twig_macro() throws RecognitionException { TwigParser.twig_macro_return retval = new TwigParser.twig_macro_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken MACRO73=null; - CommonToken ENDMACRO76=null; - TwigParser.variable_return variable74 = null; + CommonToken MACRO80=null; + CommonToken ENDMACRO83=null; + TwigParser.variable_return variable81 = null; - TwigParser.method_return method75 = null; + TwigParser.method_return method82 = null; - TwigCommonTree MACRO73_tree=null; - TwigCommonTree ENDMACRO76_tree=null; + TwigCommonTree MACRO80_tree=null; + TwigCommonTree ENDMACRO83_tree=null; try { - // TwigParser.g:113:3: ( ( MACRO ( variable | method ) ) | ENDMACRO ) - int alt24=2; - int LA24_0 = input.LA(1); + // TwigParser.g:122:3: ( ( MACRO ( variable | method ) ) | ENDMACRO ) + int alt27=2; + int LA27_0 = input.LA(1); - if ( (LA24_0==MACRO) ) { - alt24=1; + if ( (LA27_0==MACRO) ) { + alt27=1; } - else if ( (LA24_0==ENDMACRO) ) { - alt24=2; + else if ( (LA27_0==ENDMACRO) ) { + alt27=2; } else { NoViableAltException nvae = - new NoViableAltException("", 24, 0, input); + new NoViableAltException("", 27, 0, input); throw nvae; } - switch (alt24) { + switch (alt27) { case 1 : - // TwigParser.g:113:5: ( MACRO ( variable | method ) ) + // TwigParser.g:122:5: ( MACRO ( variable | method ) ) { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:113:5: ( MACRO ( variable | method ) ) - // TwigParser.g:113:6: MACRO ( variable | method ) + // TwigParser.g:122:5: ( MACRO ( variable | method ) ) + // TwigParser.g:122:6: MACRO ( variable | method ) { - MACRO73=(CommonToken)match(input,MACRO,FOLLOW_MACRO_in_twig_macro491); - MACRO73_tree = (TwigCommonTree)adaptor.create(MACRO73); - adaptor.addChild(root_0, MACRO73_tree); - - // TwigParser.g:113:12: ( variable | method ) - int alt23=2; - alt23 = dfa23.predict(input); - switch (alt23) { + MACRO80=(CommonToken)match(input,MACRO,FOLLOW_MACRO_in_twig_macro547); + MACRO80_tree = (TwigCommonTree)adaptor.create(MACRO80); + adaptor.addChild(root_0, MACRO80_tree); + + // TwigParser.g:122:12: ( variable | method ) + int alt26=2; + alt26 = dfa26.predict(input); + switch (alt26) { case 1 : - // TwigParser.g:113:13: variable + // TwigParser.g:122:13: variable { - pushFollow(FOLLOW_variable_in_twig_macro494); - variable74=variable(); + pushFollow(FOLLOW_variable_in_twig_macro550); + variable81=variable(); state._fsp--; - adaptor.addChild(root_0, variable74.getTree()); + adaptor.addChild(root_0, variable81.getTree()); } break; case 2 : - // TwigParser.g:113:24: method + // TwigParser.g:122:24: method { - pushFollow(FOLLOW_method_in_twig_macro498); - method75=method(); + pushFollow(FOLLOW_method_in_twig_macro554); + method82=method(); state._fsp--; - adaptor.addChild(root_0, method75.getTree()); + adaptor.addChild(root_0, method82.getTree()); } break; @@ -1974,13 +2201,13 @@ else if ( (LA24_0==ENDMACRO) ) { } break; case 2 : - // TwigParser.g:113:35: ENDMACRO + // TwigParser.g:122:35: ENDMACRO { root_0 = (TwigCommonTree)adaptor.nil(); - ENDMACRO76=(CommonToken)match(input,ENDMACRO,FOLLOW_ENDMACRO_in_twig_macro504); - ENDMACRO76_tree = (TwigCommonTree)adaptor.create(ENDMACRO76); - adaptor.addChild(root_0, ENDMACRO76_tree); + ENDMACRO83=(CommonToken)match(input,ENDMACRO,FOLLOW_ENDMACRO_in_twig_macro560); + ENDMACRO83_tree = (TwigCommonTree)adaptor.create(ENDMACRO83); + adaptor.addChild(root_0, ENDMACRO83_tree); } @@ -2011,68 +2238,68 @@ public static class twig_if_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_if" - // TwigParser.g:116:1: twig_if : ( IF variable | method ); + // TwigParser.g:125:1: twig_if : ( IF variable | method ); public final TwigParser.twig_if_return twig_if() throws RecognitionException { TwigParser.twig_if_return retval = new TwigParser.twig_if_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken IF77=null; - TwigParser.variable_return variable78 = null; + CommonToken IF84=null; + TwigParser.variable_return variable85 = null; - TwigParser.method_return method79 = null; + TwigParser.method_return method86 = null; - TwigCommonTree IF77_tree=null; + TwigCommonTree IF84_tree=null; try { - // TwigParser.g:117:3: ( IF variable | method ) - int alt25=2; - int LA25_0 = input.LA(1); + // TwigParser.g:126:3: ( IF variable | method ) + int alt28=2; + int LA28_0 = input.LA(1); - if ( (LA25_0==IF) ) { - alt25=1; + if ( (LA28_0==IF) ) { + alt28=1; } - else if ( (LA25_0==STRING) ) { - alt25=2; + else if ( (LA28_0==STRING) ) { + alt28=2; } else { NoViableAltException nvae = - new NoViableAltException("", 25, 0, input); + new NoViableAltException("", 28, 0, input); throw nvae; } - switch (alt25) { + switch (alt28) { case 1 : - // TwigParser.g:117:5: IF variable + // TwigParser.g:126:5: IF variable { root_0 = (TwigCommonTree)adaptor.nil(); - IF77=(CommonToken)match(input,IF,FOLLOW_IF_in_twig_if519); - IF77_tree = (TwigCommonTree)adaptor.create(IF77); - adaptor.addChild(root_0, IF77_tree); + IF84=(CommonToken)match(input,IF,FOLLOW_IF_in_twig_if575); + IF84_tree = (TwigCommonTree)adaptor.create(IF84); + adaptor.addChild(root_0, IF84_tree); - pushFollow(FOLLOW_variable_in_twig_if521); - variable78=variable(); + pushFollow(FOLLOW_variable_in_twig_if577); + variable85=variable(); state._fsp--; - adaptor.addChild(root_0, variable78.getTree()); + adaptor.addChild(root_0, variable85.getTree()); } break; case 2 : - // TwigParser.g:117:19: method + // TwigParser.g:126:19: method { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_method_in_twig_if525); - method79=method(); + pushFollow(FOLLOW_method_in_twig_if581); + method86=method(); state._fsp--; - adaptor.addChild(root_0, method79.getTree()); + adaptor.addChild(root_0, method86.getTree()); } break; @@ -2102,56 +2329,56 @@ public static class twig_elseif_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_elseif" - // TwigParser.g:120:1: twig_elseif : ELSEIF ( variable | method ) ; + // TwigParser.g:129:1: twig_elseif : ELSEIF ( variable | method ) ; public final TwigParser.twig_elseif_return twig_elseif() throws RecognitionException { TwigParser.twig_elseif_return retval = new TwigParser.twig_elseif_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken ELSEIF80=null; - TwigParser.variable_return variable81 = null; + CommonToken ELSEIF87=null; + TwigParser.variable_return variable88 = null; - TwigParser.method_return method82 = null; + TwigParser.method_return method89 = null; - TwigCommonTree ELSEIF80_tree=null; + TwigCommonTree ELSEIF87_tree=null; try { - // TwigParser.g:121:3: ( ELSEIF ( variable | method ) ) - // TwigParser.g:121:5: ELSEIF ( variable | method ) + // TwigParser.g:130:3: ( ELSEIF ( variable | method ) ) + // TwigParser.g:130:5: ELSEIF ( variable | method ) { root_0 = (TwigCommonTree)adaptor.nil(); - ELSEIF80=(CommonToken)match(input,ELSEIF,FOLLOW_ELSEIF_in_twig_elseif540); - ELSEIF80_tree = (TwigCommonTree)adaptor.create(ELSEIF80); - adaptor.addChild(root_0, ELSEIF80_tree); + ELSEIF87=(CommonToken)match(input,ELSEIF,FOLLOW_ELSEIF_in_twig_elseif596); + ELSEIF87_tree = (TwigCommonTree)adaptor.create(ELSEIF87); + adaptor.addChild(root_0, ELSEIF87_tree); - // TwigParser.g:121:12: ( variable | method ) - int alt26=2; - alt26 = dfa26.predict(input); - switch (alt26) { + // TwigParser.g:130:12: ( variable | method ) + int alt29=2; + alt29 = dfa29.predict(input); + switch (alt29) { case 1 : - // TwigParser.g:121:13: variable + // TwigParser.g:130:13: variable { - pushFollow(FOLLOW_variable_in_twig_elseif543); - variable81=variable(); + pushFollow(FOLLOW_variable_in_twig_elseif599); + variable88=variable(); state._fsp--; - adaptor.addChild(root_0, variable81.getTree()); + adaptor.addChild(root_0, variable88.getTree()); } break; case 2 : - // TwigParser.g:121:24: method + // TwigParser.g:130:24: method { - pushFollow(FOLLOW_method_in_twig_elseif547); - method82=method(); + pushFollow(FOLLOW_method_in_twig_elseif603); + method89=method(); state._fsp--; - adaptor.addChild(root_0, method82.getTree()); + adaptor.addChild(root_0, method89.getTree()); } break; @@ -2185,47 +2412,47 @@ public static class twig_for_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_for" - // TwigParser.g:124:1: twig_for : FOR STRING IN for_arguments ; + // TwigParser.g:133:1: twig_for : FOR STRING IN for_arguments ; public final TwigParser.twig_for_return twig_for() throws RecognitionException { TwigParser.twig_for_return retval = new TwigParser.twig_for_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken FOR83=null; - CommonToken STRING84=null; - CommonToken IN85=null; - TwigParser.for_arguments_return for_arguments86 = null; + CommonToken FOR90=null; + CommonToken STRING91=null; + CommonToken IN92=null; + TwigParser.for_arguments_return for_arguments93 = null; - TwigCommonTree FOR83_tree=null; - TwigCommonTree STRING84_tree=null; - TwigCommonTree IN85_tree=null; + TwigCommonTree FOR90_tree=null; + TwigCommonTree STRING91_tree=null; + TwigCommonTree IN92_tree=null; try { - // TwigParser.g:125:3: ( FOR STRING IN for_arguments ) - // TwigParser.g:125:5: FOR STRING IN for_arguments + // TwigParser.g:134:3: ( FOR STRING IN for_arguments ) + // TwigParser.g:134:5: FOR STRING IN for_arguments { root_0 = (TwigCommonTree)adaptor.nil(); - FOR83=(CommonToken)match(input,FOR,FOLLOW_FOR_in_twig_for563); - FOR83_tree = (TwigCommonTree)adaptor.create(FOR83); - adaptor.addChild(root_0, FOR83_tree); + FOR90=(CommonToken)match(input,FOR,FOLLOW_FOR_in_twig_for619); + FOR90_tree = (TwigCommonTree)adaptor.create(FOR90); + adaptor.addChild(root_0, FOR90_tree); - STRING84=(CommonToken)match(input,STRING,FOLLOW_STRING_in_twig_for565); - STRING84_tree = (TwigCommonTree)adaptor.create(STRING84); - adaptor.addChild(root_0, STRING84_tree); + STRING91=(CommonToken)match(input,STRING,FOLLOW_STRING_in_twig_for621); + STRING91_tree = (TwigCommonTree)adaptor.create(STRING91); + adaptor.addChild(root_0, STRING91_tree); - IN85=(CommonToken)match(input,IN,FOLLOW_IN_in_twig_for567); - IN85_tree = (TwigCommonTree)adaptor.create(IN85); - adaptor.addChild(root_0, IN85_tree); + IN92=(CommonToken)match(input,IN,FOLLOW_IN_in_twig_for623); + IN92_tree = (TwigCommonTree)adaptor.create(IN92); + adaptor.addChild(root_0, IN92_tree); - pushFollow(FOLLOW_for_arguments_in_twig_for569); - for_arguments86=for_arguments(); + pushFollow(FOLLOW_for_arguments_in_twig_for625); + for_arguments93=for_arguments(); state._fsp--; - adaptor.addChild(root_0, for_arguments86.getTree()); + adaptor.addChild(root_0, for_arguments93.getTree()); } @@ -2253,64 +2480,64 @@ public static class for_arguments_return extends ParserRuleReturnScope { }; // $ANTLR start "for_arguments" - // TwigParser.g:128:1: for_arguments : for_value ( PIPE for_value )* ; + // TwigParser.g:137:1: for_arguments : for_value ( PIPE for_value )* ; public final TwigParser.for_arguments_return for_arguments() throws RecognitionException { TwigParser.for_arguments_return retval = new TwigParser.for_arguments_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken PIPE88=null; - TwigParser.for_value_return for_value87 = null; + CommonToken PIPE95=null; + TwigParser.for_value_return for_value94 = null; - TwigParser.for_value_return for_value89 = null; + TwigParser.for_value_return for_value96 = null; - TwigCommonTree PIPE88_tree=null; + TwigCommonTree PIPE95_tree=null; try { - // TwigParser.g:129:3: ( for_value ( PIPE for_value )* ) - // TwigParser.g:129:5: for_value ( PIPE for_value )* + // TwigParser.g:138:3: ( for_value ( PIPE for_value )* ) + // TwigParser.g:138:5: for_value ( PIPE for_value )* { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_for_value_in_for_arguments584); - for_value87=for_value(); + pushFollow(FOLLOW_for_value_in_for_arguments640); + for_value94=for_value(); state._fsp--; - adaptor.addChild(root_0, for_value87.getTree()); - // TwigParser.g:129:15: ( PIPE for_value )* - loop27: + adaptor.addChild(root_0, for_value94.getTree()); + // TwigParser.g:138:15: ( PIPE for_value )* + loop30: do { - int alt27=2; - int LA27_0 = input.LA(1); + int alt30=2; + int LA30_0 = input.LA(1); - if ( (LA27_0==PIPE) ) { - alt27=1; + if ( (LA30_0==PIPE) ) { + alt30=1; } - switch (alt27) { + switch (alt30) { case 1 : - // TwigParser.g:129:16: PIPE for_value + // TwigParser.g:138:16: PIPE for_value { - PIPE88=(CommonToken)match(input,PIPE,FOLLOW_PIPE_in_for_arguments587); - PIPE88_tree = (TwigCommonTree)adaptor.create(PIPE88); - adaptor.addChild(root_0, PIPE88_tree); + PIPE95=(CommonToken)match(input,PIPE,FOLLOW_PIPE_in_for_arguments643); + PIPE95_tree = (TwigCommonTree)adaptor.create(PIPE95); + adaptor.addChild(root_0, PIPE95_tree); - pushFollow(FOLLOW_for_value_in_for_arguments589); - for_value89=for_value(); + pushFollow(FOLLOW_for_value_in_for_arguments645); + for_value96=for_value(); state._fsp--; - adaptor.addChild(root_0, for_value89.getTree()); + adaptor.addChild(root_0, for_value96.getTree()); } break; default : - break loop27; + break loop30; } } while (true); @@ -2341,50 +2568,50 @@ public static class for_value_return extends ParserRuleReturnScope { }; // $ANTLR start "for_value" - // TwigParser.g:132:1: for_value : ( STRING | STRING_LITERAL | method | range ); + // TwigParser.g:141:1: for_value : ( STRING | STRING_LITERAL | method | range ); public final TwigParser.for_value_return for_value() throws RecognitionException { TwigParser.for_value_return retval = new TwigParser.for_value_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING90=null; - CommonToken STRING_LITERAL91=null; - TwigParser.method_return method92 = null; + CommonToken STRING97=null; + CommonToken STRING_LITERAL98=null; + TwigParser.method_return method99 = null; - TwigParser.range_return range93 = null; + TwigParser.range_return range100 = null; - TwigCommonTree STRING90_tree=null; - TwigCommonTree STRING_LITERAL91_tree=null; + TwigCommonTree STRING97_tree=null; + TwigCommonTree STRING_LITERAL98_tree=null; try { - // TwigParser.g:133:3: ( STRING | STRING_LITERAL | method | range ) - int alt28=4; + // TwigParser.g:142:3: ( STRING | STRING_LITERAL | method | range ) + int alt31=4; switch ( input.LA(1) ) { case STRING: { switch ( input.LA(2) ) { case DDOT: { - alt28=4; + alt31=4; } break; case CTRL_CLOSE: case PIPE: { - alt28=1; + alt31=1; } break; case METHOD_START: case DOT: { - alt28=3; + alt31=3; } break; default: NoViableAltException nvae = - new NoViableAltException("", 28, 1, input); + new NoViableAltException("", 31, 1, input); throw nvae; } @@ -2393,17 +2620,17 @@ public final TwigParser.for_value_return for_value() throws RecognitionException break; case STRING_LITERAL: { - int LA28_2 = input.LA(2); + int LA31_2 = input.LA(2); - if ( (LA28_2==DDOT) ) { - alt28=4; + if ( (LA31_2==DDOT) ) { + alt31=4; } - else if ( (LA28_2==CTRL_CLOSE||LA28_2==PIPE) ) { - alt28=2; + else if ( (LA31_2==CTRL_CLOSE||LA31_2==PIPE) ) { + alt31=2; } else { NoViableAltException nvae = - new NoViableAltException("", 28, 2, input); + new NoViableAltException("", 31, 2, input); throw nvae; } @@ -2411,66 +2638,66 @@ else if ( (LA28_2==CTRL_CLOSE||LA28_2==PIPE) ) { break; case NUMBER: { - alt28=4; + alt31=4; } break; default: NoViableAltException nvae = - new NoViableAltException("", 28, 0, input); + new NoViableAltException("", 31, 0, input); throw nvae; } - switch (alt28) { + switch (alt31) { case 1 : - // TwigParser.g:133:5: STRING + // TwigParser.g:142:5: STRING { root_0 = (TwigCommonTree)adaptor.nil(); - STRING90=(CommonToken)match(input,STRING,FOLLOW_STRING_in_for_value606); - STRING90_tree = (TwigCommonTree)adaptor.create(STRING90); - adaptor.addChild(root_0, STRING90_tree); + STRING97=(CommonToken)match(input,STRING,FOLLOW_STRING_in_for_value662); + STRING97_tree = (TwigCommonTree)adaptor.create(STRING97); + adaptor.addChild(root_0, STRING97_tree); } break; case 2 : - // TwigParser.g:133:14: STRING_LITERAL + // TwigParser.g:142:14: STRING_LITERAL { root_0 = (TwigCommonTree)adaptor.nil(); - STRING_LITERAL91=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_for_value610); - STRING_LITERAL91_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL91); - adaptor.addChild(root_0, STRING_LITERAL91_tree); + STRING_LITERAL98=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_for_value666); + STRING_LITERAL98_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL98); + adaptor.addChild(root_0, STRING_LITERAL98_tree); } break; case 3 : - // TwigParser.g:133:31: method + // TwigParser.g:142:31: method { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_method_in_for_value614); - method92=method(); + pushFollow(FOLLOW_method_in_for_value670); + method99=method(); state._fsp--; - adaptor.addChild(root_0, method92.getTree()); + adaptor.addChild(root_0, method99.getTree()); } break; case 4 : - // TwigParser.g:133:40: range + // TwigParser.g:142:40: range { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_range_in_for_value618); - range93=range(); + pushFollow(FOLLOW_range_in_for_value674); + range100=range(); state._fsp--; - adaptor.addChild(root_0, range93.getTree()); + adaptor.addChild(root_0, range100.getTree()); } break; @@ -2500,31 +2727,31 @@ public static class range_return extends ParserRuleReturnScope { }; // $ANTLR start "range" - // TwigParser.g:136:1: range : ( NUMBER | STRING_LITERAL | STRING ) DDOT ( NUMBER | STRING_LITERAL | STRING ) ; + // TwigParser.g:145:1: range : ( NUMBER | STRING_LITERAL | STRING ) DDOT ( NUMBER | STRING_LITERAL | STRING ) ; public final TwigParser.range_return range() throws RecognitionException { TwigParser.range_return retval = new TwigParser.range_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken set94=null; - CommonToken DDOT95=null; - CommonToken set96=null; + CommonToken set101=null; + CommonToken DDOT102=null; + CommonToken set103=null; - TwigCommonTree set94_tree=null; - TwigCommonTree DDOT95_tree=null; - TwigCommonTree set96_tree=null; + TwigCommonTree set101_tree=null; + TwigCommonTree DDOT102_tree=null; + TwigCommonTree set103_tree=null; try { - // TwigParser.g:137:3: ( ( NUMBER | STRING_LITERAL | STRING ) DDOT ( NUMBER | STRING_LITERAL | STRING ) ) - // TwigParser.g:137:5: ( NUMBER | STRING_LITERAL | STRING ) DDOT ( NUMBER | STRING_LITERAL | STRING ) + // TwigParser.g:146:3: ( ( NUMBER | STRING_LITERAL | STRING ) DDOT ( NUMBER | STRING_LITERAL | STRING ) ) + // TwigParser.g:146:5: ( NUMBER | STRING_LITERAL | STRING ) DDOT ( NUMBER | STRING_LITERAL | STRING ) { root_0 = (TwigCommonTree)adaptor.nil(); - set94=(CommonToken)input.LT(1); + set101=(CommonToken)input.LT(1); if ( input.LA(1)==NUMBER||input.LA(1)==STRING||input.LA(1)==STRING_LITERAL ) { input.consume(); - adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set94)); + adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set101)); state.errorRecovery=false; } else { @@ -2532,14 +2759,14 @@ public final TwigParser.range_return range() throws RecognitionException { throw mse; } - DDOT95=(CommonToken)match(input,DDOT,FOLLOW_DDOT_in_range645); - DDOT95_tree = (TwigCommonTree)adaptor.create(DDOT95); - adaptor.addChild(root_0, DDOT95_tree); + DDOT102=(CommonToken)match(input,DDOT,FOLLOW_DDOT_in_range701); + DDOT102_tree = (TwigCommonTree)adaptor.create(DDOT102); + adaptor.addChild(root_0, DDOT102_tree); - set96=(CommonToken)input.LT(1); + set103=(CommonToken)input.LT(1); if ( input.LA(1)==NUMBER||input.LA(1)==STRING||input.LA(1)==STRING_LITERAL ) { input.consume(); - adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set96)); + adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set103)); state.errorRecovery=false; } else { @@ -2574,204 +2801,204 @@ public static class twig_ternary_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_ternary" - // TwigParser.g:140:1: twig_ternary : ( STRING_LITERAL | NUMBER | variable | method ) QM ( STRING_LITERAL | NUMBER | variable | method ) COLON ( STRING_LITERAL | NUMBER | variable | method ) ; + // TwigParser.g:149:1: twig_ternary : ( STRING_LITERAL | NUMBER | variable | method ) QM ( STRING_LITERAL | NUMBER | variable | method ) COLON ( STRING_LITERAL | NUMBER | variable | method ) ; public final TwigParser.twig_ternary_return twig_ternary() throws RecognitionException { TwigParser.twig_ternary_return retval = new TwigParser.twig_ternary_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING_LITERAL97=null; - CommonToken NUMBER98=null; - CommonToken QM101=null; - CommonToken STRING_LITERAL102=null; - CommonToken NUMBER103=null; - CommonToken COLON106=null; - CommonToken STRING_LITERAL107=null; - CommonToken NUMBER108=null; - TwigParser.variable_return variable99 = null; + CommonToken STRING_LITERAL104=null; + CommonToken NUMBER105=null; + CommonToken QM108=null; + CommonToken STRING_LITERAL109=null; + CommonToken NUMBER110=null; + CommonToken COLON113=null; + CommonToken STRING_LITERAL114=null; + CommonToken NUMBER115=null; + TwigParser.variable_return variable106 = null; - TwigParser.method_return method100 = null; + TwigParser.method_return method107 = null; - TwigParser.variable_return variable104 = null; + TwigParser.variable_return variable111 = null; - TwigParser.method_return method105 = null; + TwigParser.method_return method112 = null; - TwigParser.variable_return variable109 = null; + TwigParser.variable_return variable116 = null; - TwigParser.method_return method110 = null; + TwigParser.method_return method117 = null; - TwigCommonTree STRING_LITERAL97_tree=null; - TwigCommonTree NUMBER98_tree=null; - TwigCommonTree QM101_tree=null; - TwigCommonTree STRING_LITERAL102_tree=null; - TwigCommonTree NUMBER103_tree=null; - TwigCommonTree COLON106_tree=null; - TwigCommonTree STRING_LITERAL107_tree=null; - TwigCommonTree NUMBER108_tree=null; + TwigCommonTree STRING_LITERAL104_tree=null; + TwigCommonTree NUMBER105_tree=null; + TwigCommonTree QM108_tree=null; + TwigCommonTree STRING_LITERAL109_tree=null; + TwigCommonTree NUMBER110_tree=null; + TwigCommonTree COLON113_tree=null; + TwigCommonTree STRING_LITERAL114_tree=null; + TwigCommonTree NUMBER115_tree=null; try { - // TwigParser.g:141:3: ( ( STRING_LITERAL | NUMBER | variable | method ) QM ( STRING_LITERAL | NUMBER | variable | method ) COLON ( STRING_LITERAL | NUMBER | variable | method ) ) - // TwigParser.g:141:5: ( STRING_LITERAL | NUMBER | variable | method ) QM ( STRING_LITERAL | NUMBER | variable | method ) COLON ( STRING_LITERAL | NUMBER | variable | method ) + // TwigParser.g:150:3: ( ( STRING_LITERAL | NUMBER | variable | method ) QM ( STRING_LITERAL | NUMBER | variable | method ) COLON ( STRING_LITERAL | NUMBER | variable | method ) ) + // TwigParser.g:150:5: ( STRING_LITERAL | NUMBER | variable | method ) QM ( STRING_LITERAL | NUMBER | variable | method ) COLON ( STRING_LITERAL | NUMBER | variable | method ) { root_0 = (TwigCommonTree)adaptor.nil(); - // TwigParser.g:141:5: ( STRING_LITERAL | NUMBER | variable | method ) - int alt29=4; - alt29 = dfa29.predict(input); - switch (alt29) { + // TwigParser.g:150:5: ( STRING_LITERAL | NUMBER | variable | method ) + int alt32=4; + alt32 = dfa32.predict(input); + switch (alt32) { case 1 : - // TwigParser.g:141:6: STRING_LITERAL + // TwigParser.g:150:6: STRING_LITERAL { - STRING_LITERAL97=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_ternary674); - STRING_LITERAL97_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL97); - adaptor.addChild(root_0, STRING_LITERAL97_tree); + STRING_LITERAL104=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_ternary730); + STRING_LITERAL104_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL104); + adaptor.addChild(root_0, STRING_LITERAL104_tree); } break; case 2 : - // TwigParser.g:141:23: NUMBER + // TwigParser.g:150:23: NUMBER { - NUMBER98=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_twig_ternary678); - NUMBER98_tree = (TwigCommonTree)adaptor.create(NUMBER98); - adaptor.addChild(root_0, NUMBER98_tree); + NUMBER105=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_twig_ternary734); + NUMBER105_tree = (TwigCommonTree)adaptor.create(NUMBER105); + adaptor.addChild(root_0, NUMBER105_tree); } break; case 3 : - // TwigParser.g:141:32: variable + // TwigParser.g:150:32: variable { - pushFollow(FOLLOW_variable_in_twig_ternary682); - variable99=variable(); + pushFollow(FOLLOW_variable_in_twig_ternary738); + variable106=variable(); state._fsp--; - adaptor.addChild(root_0, variable99.getTree()); + adaptor.addChild(root_0, variable106.getTree()); } break; case 4 : - // TwigParser.g:141:43: method + // TwigParser.g:150:43: method { - pushFollow(FOLLOW_method_in_twig_ternary686); - method100=method(); + pushFollow(FOLLOW_method_in_twig_ternary742); + method107=method(); state._fsp--; - adaptor.addChild(root_0, method100.getTree()); + adaptor.addChild(root_0, method107.getTree()); } break; } - QM101=(CommonToken)match(input,QM,FOLLOW_QM_in_twig_ternary689); - QM101_tree = (TwigCommonTree)adaptor.create(QM101); - adaptor.addChild(root_0, QM101_tree); + QM108=(CommonToken)match(input,QM,FOLLOW_QM_in_twig_ternary745); + QM108_tree = (TwigCommonTree)adaptor.create(QM108); + adaptor.addChild(root_0, QM108_tree); - // TwigParser.g:141:54: ( STRING_LITERAL | NUMBER | variable | method ) - int alt30=4; - alt30 = dfa30.predict(input); - switch (alt30) { + // TwigParser.g:150:54: ( STRING_LITERAL | NUMBER | variable | method ) + int alt33=4; + alt33 = dfa33.predict(input); + switch (alt33) { case 1 : - // TwigParser.g:141:55: STRING_LITERAL + // TwigParser.g:150:55: STRING_LITERAL { - STRING_LITERAL102=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_ternary692); - STRING_LITERAL102_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL102); - adaptor.addChild(root_0, STRING_LITERAL102_tree); + STRING_LITERAL109=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_ternary748); + STRING_LITERAL109_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL109); + adaptor.addChild(root_0, STRING_LITERAL109_tree); } break; case 2 : - // TwigParser.g:141:72: NUMBER + // TwigParser.g:150:72: NUMBER { - NUMBER103=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_twig_ternary696); - NUMBER103_tree = (TwigCommonTree)adaptor.create(NUMBER103); - adaptor.addChild(root_0, NUMBER103_tree); + NUMBER110=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_twig_ternary752); + NUMBER110_tree = (TwigCommonTree)adaptor.create(NUMBER110); + adaptor.addChild(root_0, NUMBER110_tree); } break; case 3 : - // TwigParser.g:141:81: variable + // TwigParser.g:150:81: variable { - pushFollow(FOLLOW_variable_in_twig_ternary700); - variable104=variable(); + pushFollow(FOLLOW_variable_in_twig_ternary756); + variable111=variable(); state._fsp--; - adaptor.addChild(root_0, variable104.getTree()); + adaptor.addChild(root_0, variable111.getTree()); } break; case 4 : - // TwigParser.g:141:92: method + // TwigParser.g:150:92: method { - pushFollow(FOLLOW_method_in_twig_ternary704); - method105=method(); + pushFollow(FOLLOW_method_in_twig_ternary760); + method112=method(); state._fsp--; - adaptor.addChild(root_0, method105.getTree()); + adaptor.addChild(root_0, method112.getTree()); } break; } - COLON106=(CommonToken)match(input,COLON,FOLLOW_COLON_in_twig_ternary707); - COLON106_tree = (TwigCommonTree)adaptor.create(COLON106); - adaptor.addChild(root_0, COLON106_tree); + COLON113=(CommonToken)match(input,COLON,FOLLOW_COLON_in_twig_ternary763); + COLON113_tree = (TwigCommonTree)adaptor.create(COLON113); + adaptor.addChild(root_0, COLON113_tree); - // TwigParser.g:141:106: ( STRING_LITERAL | NUMBER | variable | method ) - int alt31=4; - alt31 = dfa31.predict(input); - switch (alt31) { + // TwigParser.g:150:106: ( STRING_LITERAL | NUMBER | variable | method ) + int alt34=4; + alt34 = dfa34.predict(input); + switch (alt34) { case 1 : - // TwigParser.g:141:107: STRING_LITERAL + // TwigParser.g:150:107: STRING_LITERAL { - STRING_LITERAL107=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_ternary710); - STRING_LITERAL107_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL107); - adaptor.addChild(root_0, STRING_LITERAL107_tree); + STRING_LITERAL114=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_twig_ternary766); + STRING_LITERAL114_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL114); + adaptor.addChild(root_0, STRING_LITERAL114_tree); } break; case 2 : - // TwigParser.g:141:124: NUMBER + // TwigParser.g:150:124: NUMBER { - NUMBER108=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_twig_ternary714); - NUMBER108_tree = (TwigCommonTree)adaptor.create(NUMBER108); - adaptor.addChild(root_0, NUMBER108_tree); + NUMBER115=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_twig_ternary770); + NUMBER115_tree = (TwigCommonTree)adaptor.create(NUMBER115); + adaptor.addChild(root_0, NUMBER115_tree); } break; case 3 : - // TwigParser.g:141:133: variable + // TwigParser.g:150:133: variable { - pushFollow(FOLLOW_variable_in_twig_ternary718); - variable109=variable(); + pushFollow(FOLLOW_variable_in_twig_ternary774); + variable116=variable(); state._fsp--; - adaptor.addChild(root_0, variable109.getTree()); + adaptor.addChild(root_0, variable116.getTree()); } break; case 4 : - // TwigParser.g:141:144: method + // TwigParser.g:150:144: method { - pushFollow(FOLLOW_method_in_twig_ternary722); - method110=method(); + pushFollow(FOLLOW_method_in_twig_ternary778); + method117=method(); state._fsp--; - adaptor.addChild(root_0, method110.getTree()); + adaptor.addChild(root_0, method117.getTree()); } break; @@ -2805,55 +3032,55 @@ public static class twig_print_statement_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_print_statement" - // TwigParser.g:146:1: twig_print_statement : PRINT_OPEN ( twig_print )? PRINT_CLOSE -> ^( TWIG_PR_STMT ( twig_print )? ) ; + // TwigParser.g:155:1: twig_print_statement : PRINT_OPEN ( twig_print )? PRINT_CLOSE -> ^( TWIG_PR_STMT ( twig_print )? ) ; public final TwigParser.twig_print_statement_return twig_print_statement() throws RecognitionException { TwigParser.twig_print_statement_return retval = new TwigParser.twig_print_statement_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken PRINT_OPEN111=null; - CommonToken PRINT_CLOSE113=null; - TwigParser.twig_print_return twig_print112 = null; + CommonToken PRINT_OPEN118=null; + CommonToken PRINT_CLOSE120=null; + TwigParser.twig_print_return twig_print119 = null; - TwigCommonTree PRINT_OPEN111_tree=null; - TwigCommonTree PRINT_CLOSE113_tree=null; + TwigCommonTree PRINT_OPEN118_tree=null; + TwigCommonTree PRINT_CLOSE120_tree=null; RewriteRuleTokenStream stream_PRINT_OPEN=new RewriteRuleTokenStream(adaptor,"token PRINT_OPEN"); RewriteRuleTokenStream stream_PRINT_CLOSE=new RewriteRuleTokenStream(adaptor,"token PRINT_CLOSE"); RewriteRuleSubtreeStream stream_twig_print=new RewriteRuleSubtreeStream(adaptor,"rule twig_print"); try { - // TwigParser.g:147:3: ( PRINT_OPEN ( twig_print )? PRINT_CLOSE -> ^( TWIG_PR_STMT ( twig_print )? ) ) - // TwigParser.g:147:6: PRINT_OPEN ( twig_print )? PRINT_CLOSE + // TwigParser.g:156:3: ( PRINT_OPEN ( twig_print )? PRINT_CLOSE -> ^( TWIG_PR_STMT ( twig_print )? ) ) + // TwigParser.g:156:6: PRINT_OPEN ( twig_print )? PRINT_CLOSE { - PRINT_OPEN111=(CommonToken)match(input,PRINT_OPEN,FOLLOW_PRINT_OPEN_in_twig_print_statement740); - stream_PRINT_OPEN.add(PRINT_OPEN111); + PRINT_OPEN118=(CommonToken)match(input,PRINT_OPEN,FOLLOW_PRINT_OPEN_in_twig_print_statement796); + stream_PRINT_OPEN.add(PRINT_OPEN118); - // TwigParser.g:147:17: ( twig_print )? - int alt32=2; - int LA32_0 = input.LA(1); + // TwigParser.g:156:17: ( twig_print )? + int alt35=2; + int LA35_0 = input.LA(1); - if ( (LA32_0==ARRAY_START||LA32_0==STRING||LA32_0==STRING_LITERAL) ) { - alt32=1; + if ( (LA35_0==ARRAY_START||LA35_0==STRING||LA35_0==STRING_LITERAL) ) { + alt35=1; } - switch (alt32) { + switch (alt35) { case 1 : - // TwigParser.g:147:17: twig_print + // TwigParser.g:156:17: twig_print { - pushFollow(FOLLOW_twig_print_in_twig_print_statement742); - twig_print112=twig_print(); + pushFollow(FOLLOW_twig_print_in_twig_print_statement798); + twig_print119=twig_print(); state._fsp--; - stream_twig_print.add(twig_print112.getTree()); + stream_twig_print.add(twig_print119.getTree()); } break; } - PRINT_CLOSE113=(CommonToken)match(input,PRINT_CLOSE,FOLLOW_PRINT_CLOSE_in_twig_print_statement745); - stream_PRINT_CLOSE.add(PRINT_CLOSE113); + PRINT_CLOSE120=(CommonToken)match(input,PRINT_CLOSE,FOLLOW_PRINT_CLOSE_in_twig_print_statement801); + stream_PRINT_CLOSE.add(PRINT_CLOSE120); @@ -2868,14 +3095,14 @@ public final TwigParser.twig_print_statement_return twig_print_statement() throw RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); root_0 = (TwigCommonTree)adaptor.nil(); - // 148:5: -> ^( TWIG_PR_STMT ( twig_print )? ) + // 157:5: -> ^( TWIG_PR_STMT ( twig_print )? ) { - // TwigParser.g:148:7: ^( TWIG_PR_STMT ( twig_print )? ) + // TwigParser.g:157:7: ^( TWIG_PR_STMT ( twig_print )? ) { TwigCommonTree root_1 = (TwigCommonTree)adaptor.nil(); root_1 = (TwigCommonTree)adaptor.becomeRoot((TwigCommonTree)adaptor.create(TWIG_PR_STMT, "TWIG_PR_STMT"), root_1); - // TwigParser.g:148:22: ( twig_print )? + // TwigParser.g:157:22: ( twig_print )? if ( stream_twig_print.hasNext() ) { adaptor.addChild(root_1, stream_twig_print.nextTree()); @@ -2914,64 +3141,64 @@ public static class twig_print_return extends ParserRuleReturnScope { }; // $ANTLR start "twig_print" - // TwigParser.g:151:1: twig_print : p_input ( PIPE p_input )* ; + // TwigParser.g:160:1: twig_print : p_input ( PIPE p_input )* ; public final TwigParser.twig_print_return twig_print() throws RecognitionException { TwigParser.twig_print_return retval = new TwigParser.twig_print_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken PIPE115=null; - TwigParser.p_input_return p_input114 = null; + CommonToken PIPE122=null; + TwigParser.p_input_return p_input121 = null; - TwigParser.p_input_return p_input116 = null; + TwigParser.p_input_return p_input123 = null; - TwigCommonTree PIPE115_tree=null; + TwigCommonTree PIPE122_tree=null; try { - // TwigParser.g:152:3: ( p_input ( PIPE p_input )* ) - // TwigParser.g:152:5: p_input ( PIPE p_input )* + // TwigParser.g:161:3: ( p_input ( PIPE p_input )* ) + // TwigParser.g:161:5: p_input ( PIPE p_input )* { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_p_input_in_twig_print772); - p_input114=p_input(); + pushFollow(FOLLOW_p_input_in_twig_print828); + p_input121=p_input(); state._fsp--; - adaptor.addChild(root_0, p_input114.getTree()); - // TwigParser.g:152:13: ( PIPE p_input )* - loop33: + adaptor.addChild(root_0, p_input121.getTree()); + // TwigParser.g:161:13: ( PIPE p_input )* + loop36: do { - int alt33=2; - int LA33_0 = input.LA(1); + int alt36=2; + int LA36_0 = input.LA(1); - if ( (LA33_0==PIPE) ) { - alt33=1; + if ( (LA36_0==PIPE) ) { + alt36=1; } - switch (alt33) { + switch (alt36) { case 1 : - // TwigParser.g:152:14: PIPE p_input + // TwigParser.g:161:14: PIPE p_input { - PIPE115=(CommonToken)match(input,PIPE,FOLLOW_PIPE_in_twig_print775); - PIPE115_tree = (TwigCommonTree)adaptor.create(PIPE115); - adaptor.addChild(root_0, PIPE115_tree); + PIPE122=(CommonToken)match(input,PIPE,FOLLOW_PIPE_in_twig_print831); + PIPE122_tree = (TwigCommonTree)adaptor.create(PIPE122); + adaptor.addChild(root_0, PIPE122_tree); - pushFollow(FOLLOW_p_input_in_twig_print777); - p_input116=p_input(); + pushFollow(FOLLOW_p_input_in_twig_print833); + p_input123=p_input(); state._fsp--; - adaptor.addChild(root_0, p_input116.getTree()); + adaptor.addChild(root_0, p_input123.getTree()); } break; default : - break loop33; + break loop36; } } while (true); @@ -3002,78 +3229,78 @@ public static class p_input_return extends ParserRuleReturnScope { }; // $ANTLR start "p_input" - // TwigParser.g:155:1: p_input : ( variable | method | array | STRING_LITERAL ); + // TwigParser.g:164:1: p_input : ( variable | method | array | STRING_LITERAL ); public final TwigParser.p_input_return p_input() throws RecognitionException { TwigParser.p_input_return retval = new TwigParser.p_input_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING_LITERAL120=null; - TwigParser.variable_return variable117 = null; + CommonToken STRING_LITERAL127=null; + TwigParser.variable_return variable124 = null; - TwigParser.method_return method118 = null; + TwigParser.method_return method125 = null; - TwigParser.array_return array119 = null; + TwigParser.array_return array126 = null; - TwigCommonTree STRING_LITERAL120_tree=null; + TwigCommonTree STRING_LITERAL127_tree=null; try { - // TwigParser.g:156:3: ( variable | method | array | STRING_LITERAL ) - int alt34=4; - alt34 = dfa34.predict(input); - switch (alt34) { + // TwigParser.g:165:3: ( variable | method | array | STRING_LITERAL ) + int alt37=4; + alt37 = dfa37.predict(input); + switch (alt37) { case 1 : - // TwigParser.g:156:5: variable + // TwigParser.g:165:5: variable { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_variable_in_p_input794); - variable117=variable(); + pushFollow(FOLLOW_variable_in_p_input850); + variable124=variable(); state._fsp--; - adaptor.addChild(root_0, variable117.getTree()); + adaptor.addChild(root_0, variable124.getTree()); } break; case 2 : - // TwigParser.g:156:16: method + // TwigParser.g:165:16: method { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_method_in_p_input798); - method118=method(); + pushFollow(FOLLOW_method_in_p_input854); + method125=method(); state._fsp--; - adaptor.addChild(root_0, method118.getTree()); + adaptor.addChild(root_0, method125.getTree()); } break; case 3 : - // TwigParser.g:156:25: array + // TwigParser.g:165:25: array { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_array_in_p_input802); - array119=array(); + pushFollow(FOLLOW_array_in_p_input858); + array126=array(); state._fsp--; - adaptor.addChild(root_0, array119.getTree()); + adaptor.addChild(root_0, array126.getTree()); } break; case 4 : - // TwigParser.g:156:33: STRING_LITERAL + // TwigParser.g:165:33: STRING_LITERAL { root_0 = (TwigCommonTree)adaptor.nil(); - STRING_LITERAL120=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_p_input806); - STRING_LITERAL120_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL120); - adaptor.addChild(root_0, STRING_LITERAL120_tree); + STRING_LITERAL127=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_p_input862); + STRING_LITERAL127_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL127); + adaptor.addChild(root_0, STRING_LITERAL127_tree); } @@ -3104,40 +3331,40 @@ public static class array_return extends ParserRuleReturnScope { }; // $ANTLR start "array" - // TwigParser.g:160:1: array : ARRAY_START array_elements ARRAY_END ; + // TwigParser.g:169:1: array : ARRAY_START array_elements ARRAY_END ; public final TwigParser.array_return array() throws RecognitionException { TwigParser.array_return retval = new TwigParser.array_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken ARRAY_START121=null; - CommonToken ARRAY_END123=null; - TwigParser.array_elements_return array_elements122 = null; + CommonToken ARRAY_START128=null; + CommonToken ARRAY_END130=null; + TwigParser.array_elements_return array_elements129 = null; - TwigCommonTree ARRAY_START121_tree=null; - TwigCommonTree ARRAY_END123_tree=null; + TwigCommonTree ARRAY_START128_tree=null; + TwigCommonTree ARRAY_END130_tree=null; try { - // TwigParser.g:161:3: ( ARRAY_START array_elements ARRAY_END ) - // TwigParser.g:161:5: ARRAY_START array_elements ARRAY_END + // TwigParser.g:170:3: ( ARRAY_START array_elements ARRAY_END ) + // TwigParser.g:170:5: ARRAY_START array_elements ARRAY_END { root_0 = (TwigCommonTree)adaptor.nil(); - ARRAY_START121=(CommonToken)match(input,ARRAY_START,FOLLOW_ARRAY_START_in_array824); - ARRAY_START121_tree = (TwigCommonTree)adaptor.create(ARRAY_START121); - adaptor.addChild(root_0, ARRAY_START121_tree); + ARRAY_START128=(CommonToken)match(input,ARRAY_START,FOLLOW_ARRAY_START_in_array880); + ARRAY_START128_tree = (TwigCommonTree)adaptor.create(ARRAY_START128); + adaptor.addChild(root_0, ARRAY_START128_tree); - pushFollow(FOLLOW_array_elements_in_array826); - array_elements122=array_elements(); + pushFollow(FOLLOW_array_elements_in_array882); + array_elements129=array_elements(); state._fsp--; - adaptor.addChild(root_0, array_elements122.getTree()); - ARRAY_END123=(CommonToken)match(input,ARRAY_END,FOLLOW_ARRAY_END_in_array828); - ARRAY_END123_tree = (TwigCommonTree)adaptor.create(ARRAY_END123); - adaptor.addChild(root_0, ARRAY_END123_tree); + adaptor.addChild(root_0, array_elements129.getTree()); + ARRAY_END130=(CommonToken)match(input,ARRAY_END,FOLLOW_ARRAY_END_in_array884); + ARRAY_END130_tree = (TwigCommonTree)adaptor.create(ARRAY_END130); + adaptor.addChild(root_0, ARRAY_END130_tree); } @@ -3166,64 +3393,64 @@ public static class array_elements_return extends ParserRuleReturnScope { }; // $ANTLR start "array_elements" - // TwigParser.g:164:1: array_elements : array_element ( COMMA array_element )* ; + // TwigParser.g:173:1: array_elements : array_element ( COMMA array_element )* ; public final TwigParser.array_elements_return array_elements() throws RecognitionException { TwigParser.array_elements_return retval = new TwigParser.array_elements_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken COMMA125=null; - TwigParser.array_element_return array_element124 = null; + CommonToken COMMA132=null; + TwigParser.array_element_return array_element131 = null; - TwigParser.array_element_return array_element126 = null; + TwigParser.array_element_return array_element133 = null; - TwigCommonTree COMMA125_tree=null; + TwigCommonTree COMMA132_tree=null; try { - // TwigParser.g:165:3: ( array_element ( COMMA array_element )* ) - // TwigParser.g:165:5: array_element ( COMMA array_element )* + // TwigParser.g:174:3: ( array_element ( COMMA array_element )* ) + // TwigParser.g:174:5: array_element ( COMMA array_element )* { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_array_element_in_array_elements843); - array_element124=array_element(); + pushFollow(FOLLOW_array_element_in_array_elements899); + array_element131=array_element(); state._fsp--; - adaptor.addChild(root_0, array_element124.getTree()); - // TwigParser.g:165:19: ( COMMA array_element )* - loop35: + adaptor.addChild(root_0, array_element131.getTree()); + // TwigParser.g:174:19: ( COMMA array_element )* + loop38: do { - int alt35=2; - int LA35_0 = input.LA(1); + int alt38=2; + int LA38_0 = input.LA(1); - if ( (LA35_0==COMMA) ) { - alt35=1; + if ( (LA38_0==COMMA) ) { + alt38=1; } - switch (alt35) { + switch (alt38) { case 1 : - // TwigParser.g:165:20: COMMA array_element + // TwigParser.g:174:20: COMMA array_element { - COMMA125=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_array_elements846); - COMMA125_tree = (TwigCommonTree)adaptor.create(COMMA125); - adaptor.addChild(root_0, COMMA125_tree); + COMMA132=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_array_elements902); + COMMA132_tree = (TwigCommonTree)adaptor.create(COMMA132); + adaptor.addChild(root_0, COMMA132_tree); - pushFollow(FOLLOW_array_element_in_array_elements848); - array_element126=array_element(); + pushFollow(FOLLOW_array_element_in_array_elements904); + array_element133=array_element(); state._fsp--; - adaptor.addChild(root_0, array_element126.getTree()); + adaptor.addChild(root_0, array_element133.getTree()); } break; default : - break loop35; + break loop38; } } while (true); @@ -3254,102 +3481,102 @@ public static class array_element_return extends ParserRuleReturnScope { }; // $ANTLR start "array_element" - // TwigParser.g:168:1: array_element : ( STRING | STRING_LITERAL | NUMBER | json ); + // TwigParser.g:177:1: array_element : ( STRING | STRING_LITERAL | NUMBER | json ); public final TwigParser.array_element_return array_element() throws RecognitionException { TwigParser.array_element_return retval = new TwigParser.array_element_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING127=null; - CommonToken STRING_LITERAL128=null; - CommonToken NUMBER129=null; - TwigParser.json_return json130 = null; + CommonToken STRING134=null; + CommonToken STRING_LITERAL135=null; + CommonToken NUMBER136=null; + TwigParser.json_return json137 = null; - TwigCommonTree STRING127_tree=null; - TwigCommonTree STRING_LITERAL128_tree=null; - TwigCommonTree NUMBER129_tree=null; + TwigCommonTree STRING134_tree=null; + TwigCommonTree STRING_LITERAL135_tree=null; + TwigCommonTree NUMBER136_tree=null; try { - // TwigParser.g:169:3: ( STRING | STRING_LITERAL | NUMBER | json ) - int alt36=4; + // TwigParser.g:178:3: ( STRING | STRING_LITERAL | NUMBER | json ) + int alt39=4; switch ( input.LA(1) ) { case STRING: { - alt36=1; + alt39=1; } break; case STRING_LITERAL: { - alt36=2; + alt39=2; } break; case NUMBER: { - alt36=3; + alt39=3; } break; case JSON_START: { - alt36=4; + alt39=4; } break; default: NoViableAltException nvae = - new NoViableAltException("", 36, 0, input); + new NoViableAltException("", 39, 0, input); throw nvae; } - switch (alt36) { + switch (alt39) { case 1 : - // TwigParser.g:169:5: STRING + // TwigParser.g:178:5: STRING { root_0 = (TwigCommonTree)adaptor.nil(); - STRING127=(CommonToken)match(input,STRING,FOLLOW_STRING_in_array_element865); - STRING127_tree = (TwigCommonTree)adaptor.create(STRING127); - adaptor.addChild(root_0, STRING127_tree); + STRING134=(CommonToken)match(input,STRING,FOLLOW_STRING_in_array_element921); + STRING134_tree = (TwigCommonTree)adaptor.create(STRING134); + adaptor.addChild(root_0, STRING134_tree); } break; case 2 : - // TwigParser.g:169:14: STRING_LITERAL + // TwigParser.g:178:14: STRING_LITERAL { root_0 = (TwigCommonTree)adaptor.nil(); - STRING_LITERAL128=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_array_element869); - STRING_LITERAL128_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL128); - adaptor.addChild(root_0, STRING_LITERAL128_tree); + STRING_LITERAL135=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_array_element925); + STRING_LITERAL135_tree = (TwigCommonTree)adaptor.create(STRING_LITERAL135); + adaptor.addChild(root_0, STRING_LITERAL135_tree); } break; case 3 : - // TwigParser.g:169:31: NUMBER + // TwigParser.g:178:31: NUMBER { root_0 = (TwigCommonTree)adaptor.nil(); - NUMBER129=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_array_element873); - NUMBER129_tree = (TwigCommonTree)adaptor.create(NUMBER129); - adaptor.addChild(root_0, NUMBER129_tree); + NUMBER136=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_array_element929); + NUMBER136_tree = (TwigCommonTree)adaptor.create(NUMBER136); + adaptor.addChild(root_0, NUMBER136_tree); } break; case 4 : - // TwigParser.g:169:40: json + // TwigParser.g:178:40: json { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_json_in_array_element877); - json130=json(); + pushFollow(FOLLOW_json_in_array_element933); + json137=json(); state._fsp--; - adaptor.addChild(root_0, json130.getTree()); + adaptor.addChild(root_0, json137.getTree()); } break; @@ -3379,7 +3606,7 @@ public static class variable_return extends ParserRuleReturnScope { }; // $ANTLR start "variable" - // TwigParser.g:172:1: variable : param= STRING ( DOT ( STRING ) )* -> ^( TWIG_VAR $param) ; + // TwigParser.g:181:1: variable : param= STRING ( DOT ( STRING ) )* -> ^( TWIG_VAR $param) ; public final TwigParser.variable_return variable() throws RecognitionException { TwigParser.variable_return retval = new TwigParser.variable_return(); retval.start = input.LT(1); @@ -3387,45 +3614,45 @@ public final TwigParser.variable_return variable() throws RecognitionException { TwigCommonTree root_0 = null; CommonToken param=null; - CommonToken DOT131=null; - CommonToken STRING132=null; + CommonToken DOT138=null; + CommonToken STRING139=null; TwigCommonTree param_tree=null; - TwigCommonTree DOT131_tree=null; - TwigCommonTree STRING132_tree=null; + TwigCommonTree DOT138_tree=null; + TwigCommonTree STRING139_tree=null; RewriteRuleTokenStream stream_DOT=new RewriteRuleTokenStream(adaptor,"token DOT"); RewriteRuleTokenStream stream_STRING=new RewriteRuleTokenStream(adaptor,"token STRING"); try { - // TwigParser.g:173:3: (param= STRING ( DOT ( STRING ) )* -> ^( TWIG_VAR $param) ) - // TwigParser.g:173:5: param= STRING ( DOT ( STRING ) )* + // TwigParser.g:182:3: (param= STRING ( DOT ( STRING ) )* -> ^( TWIG_VAR $param) ) + // TwigParser.g:182:5: param= STRING ( DOT ( STRING ) )* { - param=(CommonToken)match(input,STRING,FOLLOW_STRING_in_variable894); + param=(CommonToken)match(input,STRING,FOLLOW_STRING_in_variable950); stream_STRING.add(param); - // TwigParser.g:173:18: ( DOT ( STRING ) )* - loop37: + // TwigParser.g:182:18: ( DOT ( STRING ) )* + loop40: do { - int alt37=2; - int LA37_0 = input.LA(1); + int alt40=2; + int LA40_0 = input.LA(1); - if ( (LA37_0==DOT) ) { - alt37=1; + if ( (LA40_0==DOT) ) { + alt40=1; } - switch (alt37) { + switch (alt40) { case 1 : - // TwigParser.g:173:19: DOT ( STRING ) + // TwigParser.g:182:19: DOT ( STRING ) { - DOT131=(CommonToken)match(input,DOT,FOLLOW_DOT_in_variable897); - stream_DOT.add(DOT131); + DOT138=(CommonToken)match(input,DOT,FOLLOW_DOT_in_variable953); + stream_DOT.add(DOT138); - // TwigParser.g:173:23: ( STRING ) - // TwigParser.g:173:24: STRING + // TwigParser.g:182:23: ( STRING ) + // TwigParser.g:182:24: STRING { - STRING132=(CommonToken)match(input,STRING,FOLLOW_STRING_in_variable900); - stream_STRING.add(STRING132); + STRING139=(CommonToken)match(input,STRING,FOLLOW_STRING_in_variable956); + stream_STRING.add(STRING139); } @@ -3435,7 +3662,7 @@ public final TwigParser.variable_return variable() throws RecognitionException { break; default : - break loop37; + break loop40; } } while (true); @@ -3453,9 +3680,9 @@ public final TwigParser.variable_return variable() throws RecognitionException { RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); root_0 = (TwigCommonTree)adaptor.nil(); - // 174:5: -> ^( TWIG_VAR $param) + // 183:5: -> ^( TWIG_VAR $param) { - // TwigParser.g:174:7: ^( TWIG_VAR $param) + // TwigParser.g:183:7: ^( TWIG_VAR $param) { TwigCommonTree root_1 = (TwigCommonTree)adaptor.nil(); root_1 = (TwigCommonTree)adaptor.becomeRoot((TwigCommonTree)adaptor.create(TWIG_VAR, "TWIG_VAR"), root_1); @@ -3494,65 +3721,65 @@ public static class method_return extends ParserRuleReturnScope { }; // $ANTLR start "method" - // TwigParser.g:177:1: method : variable METHOD_START ( arguments )? METHOD_END ; + // TwigParser.g:186:1: method : variable METHOD_START ( arguments )? METHOD_END ; public final TwigParser.method_return method() throws RecognitionException { TwigParser.method_return retval = new TwigParser.method_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken METHOD_START134=null; - CommonToken METHOD_END136=null; - TwigParser.variable_return variable133 = null; + CommonToken METHOD_START141=null; + CommonToken METHOD_END143=null; + TwigParser.variable_return variable140 = null; - TwigParser.arguments_return arguments135 = null; + TwigParser.arguments_return arguments142 = null; - TwigCommonTree METHOD_START134_tree=null; - TwigCommonTree METHOD_END136_tree=null; + TwigCommonTree METHOD_START141_tree=null; + TwigCommonTree METHOD_END143_tree=null; try { - // TwigParser.g:178:3: ( variable METHOD_START ( arguments )? METHOD_END ) - // TwigParser.g:178:5: variable METHOD_START ( arguments )? METHOD_END + // TwigParser.g:187:3: ( variable METHOD_START ( arguments )? METHOD_END ) + // TwigParser.g:187:5: variable METHOD_START ( arguments )? METHOD_END { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_variable_in_method930); - variable133=variable(); + pushFollow(FOLLOW_variable_in_method986); + variable140=variable(); state._fsp--; - adaptor.addChild(root_0, variable133.getTree()); - METHOD_START134=(CommonToken)match(input,METHOD_START,FOLLOW_METHOD_START_in_method932); - METHOD_START134_tree = (TwigCommonTree)adaptor.create(METHOD_START134); - adaptor.addChild(root_0, METHOD_START134_tree); + adaptor.addChild(root_0, variable140.getTree()); + METHOD_START141=(CommonToken)match(input,METHOD_START,FOLLOW_METHOD_START_in_method988); + METHOD_START141_tree = (TwigCommonTree)adaptor.create(METHOD_START141); + adaptor.addChild(root_0, METHOD_START141_tree); - // TwigParser.g:178:27: ( arguments )? - int alt38=2; - int LA38_0 = input.LA(1); + // TwigParser.g:187:27: ( arguments )? + int alt41=2; + int LA41_0 = input.LA(1); - if ( (LA38_0==JSON_START||LA38_0==NUMBER||LA38_0==STRING||LA38_0==STRING_LITERAL) ) { - alt38=1; + if ( (LA41_0==JSON_START||LA41_0==NUMBER||LA41_0==STRING||LA41_0==STRING_LITERAL) ) { + alt41=1; } - switch (alt38) { + switch (alt41) { case 1 : - // TwigParser.g:178:27: arguments + // TwigParser.g:187:27: arguments { - pushFollow(FOLLOW_arguments_in_method934); - arguments135=arguments(); + pushFollow(FOLLOW_arguments_in_method990); + arguments142=arguments(); state._fsp--; - adaptor.addChild(root_0, arguments135.getTree()); + adaptor.addChild(root_0, arguments142.getTree()); } break; } - METHOD_END136=(CommonToken)match(input,METHOD_END,FOLLOW_METHOD_END_in_method937); - METHOD_END136_tree = (TwigCommonTree)adaptor.create(METHOD_END136); - adaptor.addChild(root_0, METHOD_END136_tree); + METHOD_END143=(CommonToken)match(input,METHOD_END,FOLLOW_METHOD_END_in_method993); + METHOD_END143_tree = (TwigCommonTree)adaptor.create(METHOD_END143); + adaptor.addChild(root_0, METHOD_END143_tree); } @@ -3581,61 +3808,61 @@ public static class arguments_return extends ParserRuleReturnScope { }; // $ANTLR start "arguments" - // TwigParser.g:181:1: arguments : argument ( COMMA ( argument ) )* ; + // TwigParser.g:190:1: arguments : argument ( COMMA ( argument ) )* ; public final TwigParser.arguments_return arguments() throws RecognitionException { TwigParser.arguments_return retval = new TwigParser.arguments_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken COMMA138=null; - TwigParser.argument_return argument137 = null; + CommonToken COMMA145=null; + TwigParser.argument_return argument144 = null; - TwigParser.argument_return argument139 = null; + TwigParser.argument_return argument146 = null; - TwigCommonTree COMMA138_tree=null; + TwigCommonTree COMMA145_tree=null; try { - // TwigParser.g:182:3: ( argument ( COMMA ( argument ) )* ) - // TwigParser.g:182:5: argument ( COMMA ( argument ) )* + // TwigParser.g:191:3: ( argument ( COMMA ( argument ) )* ) + // TwigParser.g:191:5: argument ( COMMA ( argument ) )* { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_argument_in_arguments953); - argument137=argument(); + pushFollow(FOLLOW_argument_in_arguments1009); + argument144=argument(); state._fsp--; - adaptor.addChild(root_0, argument137.getTree()); - // TwigParser.g:182:15: ( COMMA ( argument ) )* - loop39: + adaptor.addChild(root_0, argument144.getTree()); + // TwigParser.g:191:15: ( COMMA ( argument ) )* + loop42: do { - int alt39=2; - int LA39_0 = input.LA(1); + int alt42=2; + int LA42_0 = input.LA(1); - if ( (LA39_0==COMMA) ) { - alt39=1; + if ( (LA42_0==COMMA) ) { + alt42=1; } - switch (alt39) { + switch (alt42) { case 1 : - // TwigParser.g:182:16: COMMA ( argument ) + // TwigParser.g:191:16: COMMA ( argument ) { - COMMA138=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_arguments957); - COMMA138_tree = (TwigCommonTree)adaptor.create(COMMA138); - adaptor.addChild(root_0, COMMA138_tree); + COMMA145=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_arguments1013); + COMMA145_tree = (TwigCommonTree)adaptor.create(COMMA145); + adaptor.addChild(root_0, COMMA145_tree); - // TwigParser.g:182:22: ( argument ) - // TwigParser.g:182:23: argument + // TwigParser.g:191:22: ( argument ) + // TwigParser.g:191:23: argument { - pushFollow(FOLLOW_argument_in_arguments960); - argument139=argument(); + pushFollow(FOLLOW_argument_in_arguments1016); + argument146=argument(); state._fsp--; - adaptor.addChild(root_0, argument139.getTree()); + adaptor.addChild(root_0, argument146.getTree()); } @@ -3644,7 +3871,7 @@ public final TwigParser.arguments_return arguments() throws RecognitionException break; default : - break loop39; + break loop42; } } while (true); @@ -3675,103 +3902,103 @@ public static class argument_return extends ParserRuleReturnScope { }; // $ANTLR start "argument" - // TwigParser.g:185:1: argument : ( literal_argument | STRING | json | NUMBER ); + // TwigParser.g:194:1: argument : ( literal_argument | STRING | json | NUMBER ); public final TwigParser.argument_return argument() throws RecognitionException { TwigParser.argument_return retval = new TwigParser.argument_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken STRING141=null; - CommonToken NUMBER143=null; - TwigParser.literal_argument_return literal_argument140 = null; + CommonToken STRING148=null; + CommonToken NUMBER150=null; + TwigParser.literal_argument_return literal_argument147 = null; - TwigParser.json_return json142 = null; + TwigParser.json_return json149 = null; - TwigCommonTree STRING141_tree=null; - TwigCommonTree NUMBER143_tree=null; + TwigCommonTree STRING148_tree=null; + TwigCommonTree NUMBER150_tree=null; try { - // TwigParser.g:186:1: ( literal_argument | STRING | json | NUMBER ) - int alt40=4; + // TwigParser.g:195:1: ( literal_argument | STRING | json | NUMBER ) + int alt43=4; switch ( input.LA(1) ) { case STRING_LITERAL: { - alt40=1; + alt43=1; } break; case STRING: { - alt40=2; + alt43=2; } break; case JSON_START: { - alt40=3; + alt43=3; } break; case NUMBER: { - alt40=4; + alt43=4; } break; default: NoViableAltException nvae = - new NoViableAltException("", 40, 0, input); + new NoViableAltException("", 43, 0, input); throw nvae; } - switch (alt40) { + switch (alt43) { case 1 : - // TwigParser.g:186:3: literal_argument + // TwigParser.g:195:3: literal_argument { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_literal_argument_in_argument974); - literal_argument140=literal_argument(); + pushFollow(FOLLOW_literal_argument_in_argument1030); + literal_argument147=literal_argument(); state._fsp--; - adaptor.addChild(root_0, literal_argument140.getTree()); + adaptor.addChild(root_0, literal_argument147.getTree()); } break; case 2 : - // TwigParser.g:186:22: STRING + // TwigParser.g:195:22: STRING { root_0 = (TwigCommonTree)adaptor.nil(); - STRING141=(CommonToken)match(input,STRING,FOLLOW_STRING_in_argument978); - STRING141_tree = (TwigCommonTree)adaptor.create(STRING141); - adaptor.addChild(root_0, STRING141_tree); + STRING148=(CommonToken)match(input,STRING,FOLLOW_STRING_in_argument1034); + STRING148_tree = (TwigCommonTree)adaptor.create(STRING148); + adaptor.addChild(root_0, STRING148_tree); } break; case 3 : - // TwigParser.g:186:31: json + // TwigParser.g:195:31: json { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_json_in_argument982); - json142=json(); + pushFollow(FOLLOW_json_in_argument1038); + json149=json(); state._fsp--; - adaptor.addChild(root_0, json142.getTree()); + adaptor.addChild(root_0, json149.getTree()); } break; case 4 : - // TwigParser.g:186:38: NUMBER + // TwigParser.g:195:38: NUMBER { root_0 = (TwigCommonTree)adaptor.nil(); - NUMBER143=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_argument986); - NUMBER143_tree = (TwigCommonTree)adaptor.create(NUMBER143); - adaptor.addChild(root_0, NUMBER143_tree); + NUMBER150=(CommonToken)match(input,NUMBER,FOLLOW_NUMBER_in_argument1042); + NUMBER150_tree = (TwigCommonTree)adaptor.create(NUMBER150); + adaptor.addChild(root_0, NUMBER150_tree); } @@ -3802,7 +4029,7 @@ public static class literal_argument_return extends ParserRuleReturnScope { }; // $ANTLR start "literal_argument" - // TwigParser.g:189:1: literal_argument : param= STRING_LITERAL -> ^( LITERAL_ARG $param) ; + // TwigParser.g:198:1: literal_argument : param= STRING_LITERAL -> ^( LITERAL_ARG $param) ; public final TwigParser.literal_argument_return literal_argument() throws RecognitionException { TwigParser.literal_argument_return retval = new TwigParser.literal_argument_return(); retval.start = input.LT(1); @@ -3815,10 +4042,10 @@ public final TwigParser.literal_argument_return literal_argument() throws Recogn RewriteRuleTokenStream stream_STRING_LITERAL=new RewriteRuleTokenStream(adaptor,"token STRING_LITERAL"); try { - // TwigParser.g:190:3: (param= STRING_LITERAL -> ^( LITERAL_ARG $param) ) - // TwigParser.g:190:5: param= STRING_LITERAL + // TwigParser.g:199:3: (param= STRING_LITERAL -> ^( LITERAL_ARG $param) ) + // TwigParser.g:199:5: param= STRING_LITERAL { - param=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_literal_argument999); + param=(CommonToken)match(input,STRING_LITERAL,FOLLOW_STRING_LITERAL_in_literal_argument1055); stream_STRING_LITERAL.add(param); @@ -3835,9 +4062,9 @@ public final TwigParser.literal_argument_return literal_argument() throws Recogn RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); root_0 = (TwigCommonTree)adaptor.nil(); - // 191:5: -> ^( LITERAL_ARG $param) + // 200:5: -> ^( LITERAL_ARG $param) { - // TwigParser.g:191:8: ^( LITERAL_ARG $param) + // TwigParser.g:200:8: ^( LITERAL_ARG $param) { TwigCommonTree root_1 = (TwigCommonTree)adaptor.nil(); root_1 = (TwigCommonTree)adaptor.becomeRoot((TwigCommonTree)adaptor.create(LITERAL_ARG, "LITERAL_ARG"), root_1); @@ -3876,57 +4103,57 @@ public static class json_return extends ParserRuleReturnScope { }; // $ANTLR start "json" - // TwigParser.g:194:1: json : JSON_START ( json_arguments )? JSON_END ; + // TwigParser.g:203:1: json : JSON_START ( json_arguments )? JSON_END ; public final TwigParser.json_return json() throws RecognitionException { TwigParser.json_return retval = new TwigParser.json_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken JSON_START144=null; - CommonToken JSON_END146=null; - TwigParser.json_arguments_return json_arguments145 = null; + CommonToken JSON_START151=null; + CommonToken JSON_END153=null; + TwigParser.json_arguments_return json_arguments152 = null; - TwigCommonTree JSON_START144_tree=null; - TwigCommonTree JSON_END146_tree=null; + TwigCommonTree JSON_START151_tree=null; + TwigCommonTree JSON_END153_tree=null; try { - // TwigParser.g:195:3: ( JSON_START ( json_arguments )? JSON_END ) - // TwigParser.g:195:5: JSON_START ( json_arguments )? JSON_END + // TwigParser.g:204:3: ( JSON_START ( json_arguments )? JSON_END ) + // TwigParser.g:204:5: JSON_START ( json_arguments )? JSON_END { root_0 = (TwigCommonTree)adaptor.nil(); - JSON_START144=(CommonToken)match(input,JSON_START,FOLLOW_JSON_START_in_json1025); - JSON_START144_tree = (TwigCommonTree)adaptor.create(JSON_START144); - adaptor.addChild(root_0, JSON_START144_tree); + JSON_START151=(CommonToken)match(input,JSON_START,FOLLOW_JSON_START_in_json1081); + JSON_START151_tree = (TwigCommonTree)adaptor.create(JSON_START151); + adaptor.addChild(root_0, JSON_START151_tree); - // TwigParser.g:195:16: ( json_arguments )? - int alt41=2; - int LA41_0 = input.LA(1); + // TwigParser.g:204:16: ( json_arguments )? + int alt44=2; + int LA44_0 = input.LA(1); - if ( (LA41_0==STRING||LA41_0==STRING_LITERAL) ) { - alt41=1; + if ( (LA44_0==STRING||LA44_0==STRING_LITERAL) ) { + alt44=1; } - switch (alt41) { + switch (alt44) { case 1 : - // TwigParser.g:195:16: json_arguments + // TwigParser.g:204:16: json_arguments { - pushFollow(FOLLOW_json_arguments_in_json1027); - json_arguments145=json_arguments(); + pushFollow(FOLLOW_json_arguments_in_json1083); + json_arguments152=json_arguments(); state._fsp--; - adaptor.addChild(root_0, json_arguments145.getTree()); + adaptor.addChild(root_0, json_arguments152.getTree()); } break; } - JSON_END146=(CommonToken)match(input,JSON_END,FOLLOW_JSON_END_in_json1030); - JSON_END146_tree = (TwigCommonTree)adaptor.create(JSON_END146); - adaptor.addChild(root_0, JSON_END146_tree); + JSON_END153=(CommonToken)match(input,JSON_END,FOLLOW_JSON_END_in_json1086); + JSON_END153_tree = (TwigCommonTree)adaptor.create(JSON_END153); + adaptor.addChild(root_0, JSON_END153_tree); } @@ -3955,61 +4182,61 @@ public static class json_arguments_return extends ParserRuleReturnScope { }; // $ANTLR start "json_arguments" - // TwigParser.g:198:1: json_arguments : json_argument ( COMMA ( json_argument ) )* ; + // TwigParser.g:207:1: json_arguments : json_argument ( COMMA ( json_argument ) )* ; public final TwigParser.json_arguments_return json_arguments() throws RecognitionException { TwigParser.json_arguments_return retval = new TwigParser.json_arguments_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken COMMA148=null; - TwigParser.json_argument_return json_argument147 = null; + CommonToken COMMA155=null; + TwigParser.json_argument_return json_argument154 = null; - TwigParser.json_argument_return json_argument149 = null; + TwigParser.json_argument_return json_argument156 = null; - TwigCommonTree COMMA148_tree=null; + TwigCommonTree COMMA155_tree=null; try { - // TwigParser.g:199:3: ( json_argument ( COMMA ( json_argument ) )* ) - // TwigParser.g:199:5: json_argument ( COMMA ( json_argument ) )* + // TwigParser.g:208:3: ( json_argument ( COMMA ( json_argument ) )* ) + // TwigParser.g:208:5: json_argument ( COMMA ( json_argument ) )* { root_0 = (TwigCommonTree)adaptor.nil(); - pushFollow(FOLLOW_json_argument_in_json_arguments1045); - json_argument147=json_argument(); + pushFollow(FOLLOW_json_argument_in_json_arguments1101); + json_argument154=json_argument(); state._fsp--; - adaptor.addChild(root_0, json_argument147.getTree()); - // TwigParser.g:199:19: ( COMMA ( json_argument ) )* - loop42: + adaptor.addChild(root_0, json_argument154.getTree()); + // TwigParser.g:208:19: ( COMMA ( json_argument ) )* + loop45: do { - int alt42=2; - int LA42_0 = input.LA(1); + int alt45=2; + int LA45_0 = input.LA(1); - if ( (LA42_0==COMMA) ) { - alt42=1; + if ( (LA45_0==COMMA) ) { + alt45=1; } - switch (alt42) { + switch (alt45) { case 1 : - // TwigParser.g:199:20: COMMA ( json_argument ) + // TwigParser.g:208:20: COMMA ( json_argument ) { - COMMA148=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_json_arguments1048); - COMMA148_tree = (TwigCommonTree)adaptor.create(COMMA148); - adaptor.addChild(root_0, COMMA148_tree); + COMMA155=(CommonToken)match(input,COMMA,FOLLOW_COMMA_in_json_arguments1104); + COMMA155_tree = (TwigCommonTree)adaptor.create(COMMA155); + adaptor.addChild(root_0, COMMA155_tree); - // TwigParser.g:199:26: ( json_argument ) - // TwigParser.g:199:27: json_argument + // TwigParser.g:208:26: ( json_argument ) + // TwigParser.g:208:27: json_argument { - pushFollow(FOLLOW_json_argument_in_json_arguments1051); - json_argument149=json_argument(); + pushFollow(FOLLOW_json_argument_in_json_arguments1107); + json_argument156=json_argument(); state._fsp--; - adaptor.addChild(root_0, json_argument149.getTree()); + adaptor.addChild(root_0, json_argument156.getTree()); } @@ -4018,7 +4245,7 @@ public final TwigParser.json_arguments_return json_arguments() throws Recognitio break; default : - break loop42; + break loop45; } } while (true); @@ -4049,31 +4276,31 @@ public static class json_argument_return extends ParserRuleReturnScope { }; // $ANTLR start "json_argument" - // TwigParser.g:202:1: json_argument : ( STRING_LITERAL | STRING ) ( COLON ) ( STRING_LITERAL | STRING ) ; + // TwigParser.g:211:1: json_argument : ( STRING_LITERAL | STRING ) ( COLON ) ( STRING_LITERAL | STRING ) ; public final TwigParser.json_argument_return json_argument() throws RecognitionException { TwigParser.json_argument_return retval = new TwigParser.json_argument_return(); retval.start = input.LT(1); TwigCommonTree root_0 = null; - CommonToken set150=null; - CommonToken COLON151=null; - CommonToken set152=null; + CommonToken set157=null; + CommonToken COLON158=null; + CommonToken set159=null; - TwigCommonTree set150_tree=null; - TwigCommonTree COLON151_tree=null; - TwigCommonTree set152_tree=null; + TwigCommonTree set157_tree=null; + TwigCommonTree COLON158_tree=null; + TwigCommonTree set159_tree=null; try { - // TwigParser.g:203:3: ( ( STRING_LITERAL | STRING ) ( COLON ) ( STRING_LITERAL | STRING ) ) - // TwigParser.g:203:5: ( STRING_LITERAL | STRING ) ( COLON ) ( STRING_LITERAL | STRING ) + // TwigParser.g:212:3: ( ( STRING_LITERAL | STRING ) ( COLON ) ( STRING_LITERAL | STRING ) ) + // TwigParser.g:212:5: ( STRING_LITERAL | STRING ) ( COLON ) ( STRING_LITERAL | STRING ) { root_0 = (TwigCommonTree)adaptor.nil(); - set150=(CommonToken)input.LT(1); + set157=(CommonToken)input.LT(1); if ( input.LA(1)==STRING||input.LA(1)==STRING_LITERAL ) { input.consume(); - adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set150)); + adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set157)); state.errorRecovery=false; } else { @@ -4081,20 +4308,20 @@ public final TwigParser.json_argument_return json_argument() throws RecognitionE throw mse; } - // TwigParser.g:203:31: ( COLON ) - // TwigParser.g:203:32: COLON + // TwigParser.g:212:31: ( COLON ) + // TwigParser.g:212:32: COLON { - COLON151=(CommonToken)match(input,COLON,FOLLOW_COLON_in_json_argument1078); - COLON151_tree = (TwigCommonTree)adaptor.create(COLON151); - adaptor.addChild(root_0, COLON151_tree); + COLON158=(CommonToken)match(input,COLON,FOLLOW_COLON_in_json_argument1134); + COLON158_tree = (TwigCommonTree)adaptor.create(COLON158); + adaptor.addChild(root_0, COLON158_tree); } - set152=(CommonToken)input.LT(1); + set159=(CommonToken)input.LT(1); if ( input.LA(1)==STRING||input.LA(1)==STRING_LITERAL ) { input.consume(); - adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set152)); + adaptor.addChild(root_0, (TwigCommonTree)adaptor.create(set159)); state.errorRecovery=false; } else { @@ -4126,137 +4353,192 @@ public final TwigParser.json_argument_return json_argument() throws RecognitionE // Delegated rules - protected DFA7 dfa7 = new DFA7(this); - protected DFA14 dfa14 = new DFA14(this); - protected DFA15 dfa15 = new DFA15(this); + protected DFA5 dfa5 = new DFA5(this); + protected DFA10 dfa10 = new DFA10(this); protected DFA17 dfa17 = new DFA17(this); protected DFA18 dfa18 = new DFA18(this); - protected DFA23 dfa23 = new DFA23(this); + protected DFA20 dfa20 = new DFA20(this); + protected DFA21 dfa21 = new DFA21(this); protected DFA26 dfa26 = new DFA26(this); protected DFA29 dfa29 = new DFA29(this); - protected DFA30 dfa30 = new DFA30(this); - protected DFA31 dfa31 = new DFA31(this); + protected DFA32 dfa32 = new DFA32(this); + protected DFA33 dfa33 = new DFA33(this); protected DFA34 dfa34 = new DFA34(this); - static final String DFA7_eotS = + protected DFA37 dfa37 = new DFA37(this); + static final String DFA5_eotS = + "\6\uffff"; + static final String DFA5_eofS = + "\6\uffff"; + static final String DFA5_minS = + "\1\55\1\7\1\55\2\uffff\1\7"; + static final String DFA5_maxS = + "\1\55\1\57\1\55\2\uffff\1\57"; + static final String DFA5_acceptS = + "\3\uffff\1\1\1\2\1\uffff"; + static final String DFA5_specialS = + "\6\uffff}>"; + static final String[] DFA5_transitionS = { + "\1\1", + "\1\3\1\4\1\uffff\1\3\5\uffff\1\2\34\uffff\1\3\1\uffff\1\3", + "\1\5", + "", + "", + "\1\3\1\4\1\uffff\1\3\5\uffff\1\2\34\uffff\1\3\1\uffff\1\3" + }; + + static final short[] DFA5_eot = DFA.unpackEncodedString(DFA5_eotS); + static final short[] DFA5_eof = DFA.unpackEncodedString(DFA5_eofS); + static final char[] DFA5_min = DFA.unpackEncodedStringToUnsignedChars(DFA5_minS); + static final char[] DFA5_max = DFA.unpackEncodedStringToUnsignedChars(DFA5_maxS); + static final short[] DFA5_accept = DFA.unpackEncodedString(DFA5_acceptS); + static final short[] DFA5_special = DFA.unpackEncodedString(DFA5_specialS); + static final short[][] DFA5_transition; + + static { + int numStates = DFA5_transitionS.length; + DFA5_transition = new short[numStates][]; + for (int i=0; i<numStates; i++) { + DFA5_transition[i] = DFA.unpackEncodedString(DFA5_transitionS[i]); + } + } + + class DFA5 extends DFA { + + public DFA5(BaseRecognizer recognizer) { + this.recognizer = recognizer; + this.decisionNumber = 5; + this.eot = DFA5_eot; + this.eof = DFA5_eof; + this.min = DFA5_min; + this.max = DFA5_max; + this.accept = DFA5_accept; + this.special = DFA5_special; + this.transition = DFA5_transition; + } + public String getDescription() { + return "82:5: ( variable | method )"; + } + } + static final String DFA10_eotS = "\10\uffff"; - static final String DFA7_eofS = + static final String DFA10_eofS = "\10\uffff"; - static final String DFA7_minS = - "\1\24\1\7\2\uffff\1\53\2\uffff\1\7"; - static final String DFA7_maxS = - "\1\55\1\47\2\uffff\1\53\2\uffff\1\47"; - static final String DFA7_acceptS = + static final String DFA10_minS = + "\1\24\1\7\2\uffff\1\55\2\uffff\1\7"; + static final String DFA10_maxS = + "\1\57\1\51\2\uffff\1\55\2\uffff\1\51"; + static final String DFA10_acceptS = "\2\uffff\1\2\1\4\1\uffff\1\1\1\3\1\uffff"; - static final String DFA7_specialS = + static final String DFA10_specialS = "\10\uffff}>"; - static final String[] DFA7_transitionS = { - "\1\3\26\uffff\1\1\1\uffff\1\2", - "\1\5\1\6\7\uffff\1\4\26\uffff\1\5", + static final String[] DFA10_transitionS = { + "\1\3\30\uffff\1\1\1\uffff\1\2", + "\1\5\1\6\7\uffff\1\4\30\uffff\1\5", "", "", "\1\7", "", "", - "\1\5\1\6\7\uffff\1\4\26\uffff\1\5" + "\1\5\1\6\7\uffff\1\4\30\uffff\1\5" }; - static final short[] DFA7_eot = DFA.unpackEncodedString(DFA7_eotS); - static final short[] DFA7_eof = DFA.unpackEncodedString(DFA7_eofS); - static final char[] DFA7_min = DFA.unpackEncodedStringToUnsignedChars(DFA7_minS); - static final char[] DFA7_max = DFA.unpackEncodedStringToUnsignedChars(DFA7_maxS); - static final short[] DFA7_accept = DFA.unpackEncodedString(DFA7_acceptS); - static final short[] DFA7_special = DFA.unpackEncodedString(DFA7_specialS); - static final short[][] DFA7_transition; + static final short[] DFA10_eot = DFA.unpackEncodedString(DFA10_eotS); + static final short[] DFA10_eof = DFA.unpackEncodedString(DFA10_eofS); + static final char[] DFA10_min = DFA.unpackEncodedStringToUnsignedChars(DFA10_minS); + static final char[] DFA10_max = DFA.unpackEncodedStringToUnsignedChars(DFA10_maxS); + static final short[] DFA10_accept = DFA.unpackEncodedString(DFA10_acceptS); + static final short[] DFA10_special = DFA.unpackEncodedString(DFA10_specialS); + static final short[][] DFA10_transition; static { - int numStates = DFA7_transitionS.length; - DFA7_transition = new short[numStates][]; + int numStates = DFA10_transitionS.length; + DFA10_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { - DFA7_transition[i] = DFA.unpackEncodedString(DFA7_transitionS[i]); + DFA10_transition[i] = DFA.unpackEncodedString(DFA10_transitionS[i]); } } - class DFA7 extends DFA { + class DFA10 extends DFA { - public DFA7(BaseRecognizer recognizer) { + public DFA10(BaseRecognizer recognizer) { this.recognizer = recognizer; - this.decisionNumber = 7; - this.eot = DFA7_eot; - this.eof = DFA7_eof; - this.min = DFA7_min; - this.max = DFA7_max; - this.accept = DFA7_accept; - this.special = DFA7_special; - this.transition = DFA7_transition; + this.decisionNumber = 10; + this.eot = DFA10_eot; + this.eof = DFA10_eof; + this.min = DFA10_min; + this.max = DFA10_max; + this.accept = DFA10_accept; + this.special = DFA10_special; + this.transition = DFA10_transition; } public String getDescription() { - return "85:34: ( variable | STRING_LITERAL | method | json )"; + return "94:34: ( variable | STRING_LITERAL | method | json )"; } } - static final String DFA14_eotS = + static final String DFA17_eotS = "\112\uffff"; - static final String DFA14_eofS = + static final String DFA17_eofS = "\112\uffff"; - static final String DFA14_minS = - "\1\12\2\7\1\24\1\25\2\uffff\1\53\1\uffff\1\11\3\13\1\25\1\21\2\7"+ - "\2\11\1\25\1\11\1\7\1\24\1\7\1\21\1\13\1\53\1\uffff\1\24\1\21\1"+ - "\11\1\uffff\3\13\1\25\1\uffff\1\53\1\22\2\11\1\25\1\11\1\53\1\21"+ - "\1\13\1\22\1\53\1\21\1\11\1\22\2\53\1\21\2\53\1\22\1\21\1\53\1\22"+ - "\1\21\2\53\1\22\2\53\1\21\1\22\1\21\1\22\2\53\2\22"; - static final String DFA14_maxS = - "\1\55\2\22\2\55\2\uffff\1\53\1\uffff\1\55\3\22\1\55\1\21\4\22\1"+ - "\55\2\22\1\55\1\22\1\21\1\22\1\55\1\uffff\1\55\1\21\1\22\1\uffff"+ - "\3\22\1\55\1\uffff\1\55\1\25\2\22\1\55\1\22\1\55\1\21\1\22\1\25"+ - "\1\55\1\21\1\22\1\25\2\55\1\21\2\55\1\25\1\21\1\55\1\25\1\21\2\55"+ - "\1\25\2\55\1\21\1\25\1\21\1\25\2\55\2\25"; - static final String DFA14_acceptS = + static final String DFA17_minS = + "\1\12\2\7\1\24\1\25\2\uffff\1\55\1\uffff\1\11\3\13\1\25\1\21\2\7"+ + "\2\11\1\25\1\11\1\7\1\24\1\7\1\21\1\13\1\55\1\uffff\1\24\1\21\1"+ + "\11\1\uffff\3\13\1\25\1\uffff\1\55\1\22\2\11\1\25\1\11\1\55\1\21"+ + "\1\13\1\22\1\55\1\21\1\11\1\22\2\55\1\21\2\55\1\22\1\21\1\55\1\22"+ + "\1\21\2\55\1\22\2\55\1\21\1\22\1\21\1\22\2\55\2\22"; + static final String DFA17_maxS = + "\1\57\2\22\2\57\2\uffff\1\55\1\uffff\1\57\3\22\1\57\1\21\4\22\1"+ + "\57\2\22\1\57\1\22\1\21\1\22\1\57\1\uffff\1\57\1\21\1\22\1\uffff"+ + "\3\22\1\57\1\uffff\1\57\1\25\2\22\1\57\1\22\1\57\1\21\1\22\1\25"+ + "\1\57\1\21\1\22\1\25\2\57\1\21\2\57\1\25\1\21\1\57\1\25\1\21\2\57"+ + "\1\25\2\57\1\21\1\25\1\21\1\25\2\57\2\25"; + static final String DFA17_acceptS = "\5\uffff\1\1\1\6\1\uffff\1\2\22\uffff\1\5\3\uffff\1\3\4\uffff\1"+ "\4\45\uffff"; - static final String DFA14_specialS = + static final String DFA17_specialS = "\112\uffff}>"; - static final String[] DFA14_transitionS = { - "\1\3\11\uffff\1\4\26\uffff\1\2\1\uffff\1\1", + static final String[] DFA17_transitionS = { + "\1\3\11\uffff\1\4\30\uffff\1\2\1\uffff\1\1", "\1\5\5\uffff\1\6\4\uffff\1\5", "\1\10\1\11\4\uffff\1\6\2\uffff\1\7\1\uffff\1\10", - "\1\15\24\uffff\1\14\1\uffff\1\12\1\uffff\1\13", - "\1\17\25\uffff\1\16\1\uffff\1\16", + "\1\15\26\uffff\1\14\1\uffff\1\12\1\uffff\1\13", + "\1\17\27\uffff\1\16\1\uffff\1\16", "", "", "\1\20", "", - "\1\25\12\uffff\1\23\24\uffff\1\24\1\uffff\1\22\1\uffff\1\21", + "\1\25\12\uffff\1\23\26\uffff\1\24\1\uffff\1\22\1\uffff\1\21", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", - "\1\31\25\uffff\1\30\1\uffff\1\30", + "\1\31\27\uffff\1\30\1\uffff\1\30", "\1\32", "\1\33\5\uffff\1\6\4\uffff\1\33", "\1\10\1\11\4\uffff\1\6\2\uffff\1\7\1\uffff\1\10", "\1\25\10\uffff\1\34", "\1\25\10\uffff\1\34", - "\1\36\25\uffff\1\35\1\uffff\1\35", + "\1\36\27\uffff\1\35\1\uffff\1\35", "\1\25\10\uffff\1\34", "\1\37\5\uffff\1\6\4\uffff\1\37", - "\1\43\24\uffff\1\42\1\uffff\1\40\1\uffff\1\41", + "\1\43\26\uffff\1\42\1\uffff\1\40\1\uffff\1\41", "\1\44\5\uffff\1\6\4\uffff\1\44", "\1\45", "\1\27\6\uffff\1\26", "\1\46\1\uffff\1\46", "", - "\1\51\24\uffff\1\52\1\uffff\1\50\1\uffff\1\47", + "\1\51\26\uffff\1\52\1\uffff\1\50\1\uffff\1\47", "\1\53", "\1\25\10\uffff\1\34", "", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", - "\1\55\25\uffff\1\54\1\uffff\1\54", + "\1\55\27\uffff\1\54\1\uffff\1\54", "", "\1\56\1\uffff\1\56", "\1\57\2\uffff\1\17", "\1\25\10\uffff\1\34", "\1\25\10\uffff\1\34", - "\1\61\25\uffff\1\60\1\uffff\1\60", + "\1\61\27\uffff\1\60\1\uffff\1\60", "\1\25\10\uffff\1\34", "\1\62\1\uffff\1\62", "\1\63", @@ -4291,103 +4573,103 @@ public String getDescription() { "\1\100\2\uffff\1\61" }; - static final short[] DFA14_eot = DFA.unpackEncodedString(DFA14_eotS); - static final short[] DFA14_eof = DFA.unpackEncodedString(DFA14_eofS); - static final char[] DFA14_min = DFA.unpackEncodedStringToUnsignedChars(DFA14_minS); - static final char[] DFA14_max = DFA.unpackEncodedStringToUnsignedChars(DFA14_maxS); - static final short[] DFA14_accept = DFA.unpackEncodedString(DFA14_acceptS); - static final short[] DFA14_special = DFA.unpackEncodedString(DFA14_specialS); - static final short[][] DFA14_transition; + static final short[] DFA17_eot = DFA.unpackEncodedString(DFA17_eotS); + static final short[] DFA17_eof = DFA.unpackEncodedString(DFA17_eofS); + static final char[] DFA17_min = DFA.unpackEncodedStringToUnsignedChars(DFA17_minS); + static final char[] DFA17_max = DFA.unpackEncodedStringToUnsignedChars(DFA17_maxS); + static final short[] DFA17_accept = DFA.unpackEncodedString(DFA17_acceptS); + static final short[] DFA17_special = DFA.unpackEncodedString(DFA17_specialS); + static final short[][] DFA17_transition; static { - int numStates = DFA14_transitionS.length; - DFA14_transition = new short[numStates][]; + int numStates = DFA17_transitionS.length; + DFA17_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { - DFA14_transition[i] = DFA.unpackEncodedString(DFA14_transitionS[i]); + DFA17_transition[i] = DFA.unpackEncodedString(DFA17_transitionS[i]); } } - class DFA14 extends DFA { + class DFA17 extends DFA { - public DFA14(BaseRecognizer recognizer) { + public DFA17(BaseRecognizer recognizer) { this.recognizer = recognizer; - this.decisionNumber = 14; - this.eot = DFA14_eot; - this.eof = DFA14_eof; - this.min = DFA14_min; - this.max = DFA14_max; - this.accept = DFA14_accept; - this.special = DFA14_special; - this.transition = DFA14_transition; + this.decisionNumber = 17; + this.eot = DFA17_eot; + this.eof = DFA17_eof; + this.min = DFA17_min; + this.max = DFA17_max; + this.accept = DFA17_accept; + this.special = DFA17_special; + this.transition = DFA17_transition; } public String getDescription() { - return "101:5: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument )"; + return "110:5: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument )"; } } - static final String DFA15_eotS = + static final String DFA18_eotS = "\112\uffff"; - static final String DFA15_eofS = + static final String DFA18_eofS = "\112\uffff"; - static final String DFA15_minS = - "\1\12\2\7\1\24\1\25\2\uffff\1\53\1\uffff\1\11\3\13\1\25\1\21\2\7"+ - "\2\11\1\25\1\11\1\7\1\24\1\7\1\21\1\13\1\53\1\uffff\1\24\1\21\1"+ - "\11\1\uffff\3\13\1\25\1\uffff\1\53\1\22\2\11\1\25\1\11\1\53\1\21"+ - "\1\13\1\22\1\53\1\21\1\11\1\22\2\53\1\21\2\53\1\22\1\21\1\53\1\22"+ - "\1\21\2\53\1\22\2\53\1\21\1\22\1\21\1\22\2\53\2\22"; - static final String DFA15_maxS = - "\1\55\2\22\2\55\2\uffff\1\53\1\uffff\1\55\3\22\1\55\1\21\4\22\1"+ - "\55\2\22\1\55\1\22\1\21\1\22\1\55\1\uffff\1\55\1\21\1\22\1\uffff"+ - "\3\22\1\55\1\uffff\1\55\1\25\2\22\1\55\1\22\1\55\1\21\1\22\1\25"+ - "\1\55\1\21\1\22\1\25\2\55\1\21\2\55\1\25\1\21\1\55\1\25\1\21\2\55"+ - "\1\25\2\55\1\21\1\25\1\21\1\25\2\55\2\25"; - static final String DFA15_acceptS = + static final String DFA18_minS = + "\1\12\2\7\1\24\1\25\2\uffff\1\55\1\uffff\1\11\3\13\1\25\1\21\2\7"+ + "\2\11\1\25\1\11\1\7\1\24\1\7\1\21\1\13\1\55\1\uffff\1\24\1\21\1"+ + "\11\1\uffff\3\13\1\25\1\uffff\1\55\1\22\2\11\1\25\1\11\1\55\1\21"+ + "\1\13\1\22\1\55\1\21\1\11\1\22\2\55\1\21\2\55\1\22\1\21\1\55\1\22"+ + "\1\21\2\55\1\22\2\55\1\21\1\22\1\21\1\22\2\55\2\22"; + static final String DFA18_maxS = + "\1\57\2\22\2\57\2\uffff\1\55\1\uffff\1\57\3\22\1\57\1\21\4\22\1"+ + "\57\2\22\1\57\1\22\1\21\1\22\1\57\1\uffff\1\57\1\21\1\22\1\uffff"+ + "\3\22\1\57\1\uffff\1\57\1\25\2\22\1\57\1\22\1\57\1\21\1\22\1\25"+ + "\1\57\1\21\1\22\1\25\2\57\1\21\2\57\1\25\1\21\1\57\1\25\1\21\2\57"+ + "\1\25\2\57\1\21\1\25\1\21\1\25\2\57\2\25"; + static final String DFA18_acceptS = "\5\uffff\1\1\1\6\1\uffff\1\2\22\uffff\1\5\3\uffff\1\3\4\uffff\1"+ "\4\45\uffff"; - static final String DFA15_specialS = + static final String DFA18_specialS = "\112\uffff}>"; - static final String[] DFA15_transitionS = { - "\1\3\11\uffff\1\4\26\uffff\1\2\1\uffff\1\1", + static final String[] DFA18_transitionS = { + "\1\3\11\uffff\1\4\30\uffff\1\2\1\uffff\1\1", "\1\5\5\uffff\1\6\4\uffff\1\5", "\1\10\1\11\4\uffff\1\6\2\uffff\1\7\1\uffff\1\10", - "\1\15\24\uffff\1\14\1\uffff\1\12\1\uffff\1\13", - "\1\17\25\uffff\1\16\1\uffff\1\16", + "\1\15\26\uffff\1\14\1\uffff\1\12\1\uffff\1\13", + "\1\17\27\uffff\1\16\1\uffff\1\16", "", "", "\1\20", "", - "\1\25\12\uffff\1\23\24\uffff\1\24\1\uffff\1\22\1\uffff\1\21", + "\1\25\12\uffff\1\23\26\uffff\1\24\1\uffff\1\22\1\uffff\1\21", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", - "\1\31\25\uffff\1\30\1\uffff\1\30", + "\1\31\27\uffff\1\30\1\uffff\1\30", "\1\32", "\1\33\5\uffff\1\6\4\uffff\1\33", "\1\10\1\11\4\uffff\1\6\2\uffff\1\7\1\uffff\1\10", "\1\25\10\uffff\1\34", "\1\25\10\uffff\1\34", - "\1\36\25\uffff\1\35\1\uffff\1\35", + "\1\36\27\uffff\1\35\1\uffff\1\35", "\1\25\10\uffff\1\34", "\1\37\5\uffff\1\6\4\uffff\1\37", - "\1\43\24\uffff\1\42\1\uffff\1\40\1\uffff\1\41", + "\1\43\26\uffff\1\42\1\uffff\1\40\1\uffff\1\41", "\1\44\5\uffff\1\6\4\uffff\1\44", "\1\45", "\1\27\6\uffff\1\26", "\1\46\1\uffff\1\46", "", - "\1\51\24\uffff\1\52\1\uffff\1\50\1\uffff\1\47", + "\1\51\26\uffff\1\52\1\uffff\1\50\1\uffff\1\47", "\1\53", "\1\25\10\uffff\1\34", "", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", "\1\27\6\uffff\1\26", - "\1\55\25\uffff\1\54\1\uffff\1\54", + "\1\55\27\uffff\1\54\1\uffff\1\54", "", "\1\56\1\uffff\1\56", "\1\57\2\uffff\1\17", "\1\25\10\uffff\1\34", "\1\25\10\uffff\1\34", - "\1\61\25\uffff\1\60\1\uffff\1\60", + "\1\61\27\uffff\1\60\1\uffff\1\60", "\1\25\10\uffff\1\34", "\1\62\1\uffff\1\62", "\1\63", @@ -4422,53 +4704,53 @@ public String getDescription() { "\1\100\2\uffff\1\61" }; - static final short[] DFA15_eot = DFA.unpackEncodedString(DFA15_eotS); - static final short[] DFA15_eof = DFA.unpackEncodedString(DFA15_eofS); - static final char[] DFA15_min = DFA.unpackEncodedStringToUnsignedChars(DFA15_minS); - static final char[] DFA15_max = DFA.unpackEncodedStringToUnsignedChars(DFA15_maxS); - static final short[] DFA15_accept = DFA.unpackEncodedString(DFA15_acceptS); - static final short[] DFA15_special = DFA.unpackEncodedString(DFA15_specialS); - static final short[][] DFA15_transition; + static final short[] DFA18_eot = DFA.unpackEncodedString(DFA18_eotS); + static final short[] DFA18_eof = DFA.unpackEncodedString(DFA18_eofS); + static final char[] DFA18_min = DFA.unpackEncodedStringToUnsignedChars(DFA18_minS); + static final char[] DFA18_max = DFA.unpackEncodedStringToUnsignedChars(DFA18_maxS); + static final short[] DFA18_accept = DFA.unpackEncodedString(DFA18_acceptS); + static final short[] DFA18_special = DFA.unpackEncodedString(DFA18_specialS); + static final short[][] DFA18_transition; static { - int numStates = DFA15_transitionS.length; - DFA15_transition = new short[numStates][]; + int numStates = DFA18_transitionS.length; + DFA18_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { - DFA15_transition[i] = DFA.unpackEncodedString(DFA15_transitionS[i]); + DFA18_transition[i] = DFA.unpackEncodedString(DFA18_transitionS[i]); } } - class DFA15 extends DFA { + class DFA18 extends DFA { - public DFA15(BaseRecognizer recognizer) { + public DFA18(BaseRecognizer recognizer) { this.recognizer = recognizer; - this.decisionNumber = 15; - this.eot = DFA15_eot; - this.eof = DFA15_eof; - this.min = DFA15_min; - this.max = DFA15_max; - this.accept = DFA15_accept; - this.special = DFA15_special; - this.transition = DFA15_transition; + this.decisionNumber = 18; + this.eot = DFA18_eot; + this.eof = DFA18_eof; + this.min = DFA18_min; + this.max = DFA18_max; + this.accept = DFA18_accept; + this.special = DFA18_special; + this.transition = DFA18_transition; } public String getDescription() { - return "101:86: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument )"; + return "110:86: ( STRING_LITERAL | variable | method | array | json | twig_tilde_argument )"; } } - static final String DFA17_eotS = + static final String DFA20_eotS = "\11\uffff"; - static final String DFA17_eofS = + static final String DFA20_eofS = "\11\uffff"; - static final String DFA17_minS = - "\1\12\1\uffff\1\10\2\uffff\1\53\2\uffff\1\10"; - static final String DFA17_maxS = - "\1\55\1\uffff\1\20\2\uffff\1\53\2\uffff\1\20"; - static final String DFA17_acceptS = + static final String DFA20_minS = + "\1\12\1\uffff\1\10\2\uffff\1\55\2\uffff\1\10"; + static final String DFA20_maxS = + "\1\57\1\uffff\1\20\2\uffff\1\55\2\uffff\1\20"; + static final String DFA20_acceptS = "\1\uffff\1\1\1\uffff\1\4\1\5\1\uffff\1\2\1\3\1\uffff"; - static final String DFA17_specialS = + static final String DFA20_specialS = "\11\uffff}>"; - static final String[] DFA17_transitionS = { - "\1\3\11\uffff\1\4\26\uffff\1\2\1\uffff\1\1", + static final String[] DFA20_transitionS = { + "\1\3\11\uffff\1\4\30\uffff\1\2\1\uffff\1\1", "", "\1\7\4\uffff\1\6\2\uffff\1\5", "", @@ -4479,53 +4761,53 @@ public String getDescription() { "\1\7\4\uffff\1\6\2\uffff\1\5" }; - static final short[] DFA17_eot = DFA.unpackEncodedString(DFA17_eotS); - static final short[] DFA17_eof = DFA.unpackEncodedString(DFA17_eofS); - static final char[] DFA17_min = DFA.unpackEncodedStringToUnsignedChars(DFA17_minS); - static final char[] DFA17_max = DFA.unpackEncodedStringToUnsignedChars(DFA17_maxS); - static final short[] DFA17_accept = DFA.unpackEncodedString(DFA17_acceptS); - static final short[] DFA17_special = DFA.unpackEncodedString(DFA17_specialS); - static final short[][] DFA17_transition; + static final short[] DFA20_eot = DFA.unpackEncodedString(DFA20_eotS); + static final short[] DFA20_eof = DFA.unpackEncodedString(DFA20_eofS); + static final char[] DFA20_min = DFA.unpackEncodedStringToUnsignedChars(DFA20_minS); + static final char[] DFA20_max = DFA.unpackEncodedStringToUnsignedChars(DFA20_maxS); + static final short[] DFA20_accept = DFA.unpackEncodedString(DFA20_acceptS); + static final short[] DFA20_special = DFA.unpackEncodedString(DFA20_specialS); + static final short[][] DFA20_transition; static { - int numStates = DFA17_transitionS.length; - DFA17_transition = new short[numStates][]; + int numStates = DFA20_transitionS.length; + DFA20_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { - DFA17_transition[i] = DFA.unpackEncodedString(DFA17_transitionS[i]); + DFA20_transition[i] = DFA.unpackEncodedString(DFA20_transitionS[i]); } } - class DFA17 extends DFA { + class DFA20 extends DFA { - public DFA17(BaseRecognizer recognizer) { + public DFA20(BaseRecognizer recognizer) { this.recognizer = recognizer; - this.decisionNumber = 17; - this.eot = DFA17_eot; - this.eof = DFA17_eof; - this.min = DFA17_min; - this.max = DFA17_max; - this.accept = DFA17_accept; - this.special = DFA17_special; - this.transition = DFA17_transition; + this.decisionNumber = 20; + this.eot = DFA20_eot; + this.eof = DFA20_eof; + this.min = DFA20_min; + this.max = DFA20_max; + this.accept = DFA20_accept; + this.special = DFA20_special; + this.transition = DFA20_transition; } public String getDescription() { - return "105:5: ( STRING_LITERAL | variable | method | array | json )"; + return "114:5: ( STRING_LITERAL | variable | method | array | json )"; } } - static final String DFA18_eotS = + static final String DFA21_eotS = "\11\uffff"; - static final String DFA18_eofS = + static final String DFA21_eofS = "\11\uffff"; - static final String DFA18_minS = - "\1\12\1\uffff\1\7\2\uffff\1\53\2\uffff\1\7"; - static final String DFA18_maxS = - "\1\55\1\uffff\1\22\2\uffff\1\53\2\uffff\1\22"; - static final String DFA18_acceptS = + static final String DFA21_minS = + "\1\12\1\uffff\1\7\2\uffff\1\55\2\uffff\1\7"; + static final String DFA21_maxS = + "\1\57\1\uffff\1\22\2\uffff\1\55\2\uffff\1\22"; + static final String DFA21_acceptS = "\1\uffff\1\1\1\uffff\1\4\1\5\1\uffff\1\2\1\3\1\uffff"; - static final String DFA18_specialS = + static final String DFA21_specialS = "\11\uffff}>"; - static final String[] DFA18_transitionS = { - "\1\3\11\uffff\1\4\26\uffff\1\2\1\uffff\1\1", + static final String[] DFA21_transitionS = { + "\1\3\11\uffff\1\4\30\uffff\1\2\1\uffff\1\1", "", "\1\6\1\7\7\uffff\1\5\1\uffff\1\6", "", @@ -4536,91 +4818,37 @@ public String getDescription() { "\1\6\1\7\7\uffff\1\5\1\uffff\1\6" }; - static final short[] DFA18_eot = DFA.unpackEncodedString(DFA18_eotS); - static final short[] DFA18_eof = DFA.unpackEncodedString(DFA18_eofS); - static final char[] DFA18_min = DFA.unpackEncodedStringToUnsignedChars(DFA18_minS); - static final char[] DFA18_max = DFA.unpackEncodedStringToUnsignedChars(DFA18_maxS); - static final short[] DFA18_accept = DFA.unpackEncodedString(DFA18_acceptS); - static final short[] DFA18_special = DFA.unpackEncodedString(DFA18_specialS); - static final short[][] DFA18_transition; - - static { - int numStates = DFA18_transitionS.length; - DFA18_transition = new short[numStates][]; - for (int i=0; i<numStates; i++) { - DFA18_transition[i] = DFA.unpackEncodedString(DFA18_transitionS[i]); - } - } - - class DFA18 extends DFA { - - public DFA18(BaseRecognizer recognizer) { - this.recognizer = recognizer; - this.decisionNumber = 18; - this.eot = DFA18_eot; - this.eof = DFA18_eof; - this.min = DFA18_min; - this.max = DFA18_max; - this.accept = DFA18_accept; - this.special = DFA18_special; - this.transition = DFA18_transition; - } - public String getDescription() { - return "105:63: ( STRING_LITERAL | variable | method | array | json )"; - } - } - static final String DFA23_eotS = - "\6\uffff"; - static final String DFA23_eofS = - "\6\uffff"; - static final String DFA23_minS = - "\1\53\1\7\1\53\2\uffff\1\7"; - static final String DFA23_maxS = - "\1\53\1\20\1\53\2\uffff\1\20"; - static final String DFA23_acceptS = - "\3\uffff\1\1\1\2\1\uffff"; - static final String DFA23_specialS = - "\6\uffff}>"; - static final String[] DFA23_transitionS = { - "\1\1", - "\1\3\1\4\7\uffff\1\2", - "\1\5", - "", - "", - "\1\3\1\4\7\uffff\1\2" - }; - - static final short[] DFA23_eot = DFA.unpackEncodedString(DFA23_eotS); - static final short[] DFA23_eof = DFA.unpackEncodedString(DFA23_eofS); - static final char[] DFA23_min = DFA.unpackEncodedStringToUnsignedChars(DFA23_minS); - static final char[] DFA23_max = DFA.unpackEncodedStringToUnsignedChars(DFA23_maxS); - static final short[] DFA23_accept = DFA.unpackEncodedString(DFA23_acceptS); - static final short[] DFA23_special = DFA.unpackEncodedString(DFA23_specialS); - static final short[][] DFA23_transition; + static final short[] DFA21_eot = DFA.unpackEncodedString(DFA21_eotS); + static final short[] DFA21_eof = DFA.unpackEncodedString(DFA21_eofS); + static final char[] DFA21_min = DFA.unpackEncodedStringToUnsignedChars(DFA21_minS); + static final char[] DFA21_max = DFA.unpackEncodedStringToUnsignedChars(DFA21_maxS); + static final short[] DFA21_accept = DFA.unpackEncodedString(DFA21_acceptS); + static final short[] DFA21_special = DFA.unpackEncodedString(DFA21_specialS); + static final short[][] DFA21_transition; static { - int numStates = DFA23_transitionS.length; - DFA23_transition = new short[numStates][]; + int numStates = DFA21_transitionS.length; + DFA21_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { - DFA23_transition[i] = DFA.unpackEncodedString(DFA23_transitionS[i]); + DFA21_transition[i] = DFA.unpackEncodedString(DFA21_transitionS[i]); } } - class DFA23 extends DFA { + class DFA21 extends DFA { - public DFA23(BaseRecognizer recognizer) { + public DFA21(BaseRecognizer recognizer) { this.recognizer = recognizer; - this.decisionNumber = 23; - this.eot = DFA23_eot; - this.eof = DFA23_eof; - this.min = DFA23_min; - this.max = DFA23_max; - this.accept = DFA23_accept; - this.special = DFA23_special; - this.transition = DFA23_transition; + this.decisionNumber = 21; + this.eot = DFA21_eot; + this.eof = DFA21_eof; + this.min = DFA21_min; + this.max = DFA21_max; + this.accept = DFA21_accept; + this.special = DFA21_special; + this.transition = DFA21_transition; } public String getDescription() { - return "113:12: ( variable | method )"; + return "114:63: ( STRING_LITERAL | variable | method | array | json )"; } } static final String DFA26_eotS = @@ -4628,9 +4856,9 @@ public String getDescription() { static final String DFA26_eofS = "\6\uffff"; static final String DFA26_minS = - "\1\53\1\7\1\53\2\uffff\1\7"; + "\1\55\1\7\1\55\2\uffff\1\7"; static final String DFA26_maxS = - "\1\53\1\20\1\53\2\uffff\1\20"; + "\1\55\1\20\1\55\2\uffff\1\20"; static final String DFA26_acceptS = "\3\uffff\1\1\1\2\1\uffff"; static final String DFA26_specialS = @@ -4674,30 +4902,28 @@ public DFA26(BaseRecognizer recognizer) { this.transition = DFA26_transition; } public String getDescription() { - return "121:12: ( variable | method )"; + return "122:12: ( variable | method )"; } } static final String DFA29_eotS = - "\10\uffff"; + "\6\uffff"; static final String DFA29_eofS = - "\10\uffff"; + "\6\uffff"; static final String DFA29_minS = - "\1\51\2\uffff\1\10\1\53\2\uffff\1\10"; + "\1\55\1\7\1\55\2\uffff\1\7"; static final String DFA29_maxS = - "\1\55\2\uffff\1\26\1\53\2\uffff\1\26"; + "\1\55\1\20\1\55\2\uffff\1\20"; static final String DFA29_acceptS = - "\1\uffff\1\1\1\2\2\uffff\1\3\1\4\1\uffff"; + "\3\uffff\1\1\1\2\1\uffff"; static final String DFA29_specialS = - "\10\uffff}>"; + "\6\uffff}>"; static final String[] DFA29_transitionS = { - "\1\2\1\uffff\1\3\1\uffff\1\1", - "", - "", - "\1\6\7\uffff\1\4\5\uffff\1\5", - "\1\7", + "\1\1", + "\1\3\1\4\7\uffff\1\2", + "\1\5", "", "", - "\1\6\7\uffff\1\4\5\uffff\1\5" + "\1\3\1\4\7\uffff\1\2" }; static final short[] DFA29_eot = DFA.unpackEncodedString(DFA29_eotS); @@ -4730,119 +4956,119 @@ public DFA29(BaseRecognizer recognizer) { this.transition = DFA29_transition; } public String getDescription() { - return "141:5: ( STRING_LITERAL | NUMBER | variable | method )"; + return "130:12: ( variable | method )"; } } - static final String DFA30_eotS = + static final String DFA32_eotS = "\10\uffff"; - static final String DFA30_eofS = + static final String DFA32_eofS = "\10\uffff"; - static final String DFA30_minS = - "\1\51\2\uffff\1\10\1\53\2\uffff\1\10"; - static final String DFA30_maxS = - "\1\55\2\uffff\1\21\1\53\2\uffff\1\21"; - static final String DFA30_acceptS = + static final String DFA32_minS = + "\1\53\2\uffff\1\10\1\55\2\uffff\1\10"; + static final String DFA32_maxS = + "\1\57\2\uffff\1\26\1\55\2\uffff\1\26"; + static final String DFA32_acceptS = "\1\uffff\1\1\1\2\2\uffff\1\3\1\4\1\uffff"; - static final String DFA30_specialS = + static final String DFA32_specialS = "\10\uffff}>"; - static final String[] DFA30_transitionS = { + static final String[] DFA32_transitionS = { "\1\2\1\uffff\1\3\1\uffff\1\1", "", "", - "\1\6\7\uffff\1\4\1\5", + "\1\6\7\uffff\1\4\5\uffff\1\5", "\1\7", "", "", - "\1\6\7\uffff\1\4\1\5" + "\1\6\7\uffff\1\4\5\uffff\1\5" }; - static final short[] DFA30_eot = DFA.unpackEncodedString(DFA30_eotS); - static final short[] DFA30_eof = DFA.unpackEncodedString(DFA30_eofS); - static final char[] DFA30_min = DFA.unpackEncodedStringToUnsignedChars(DFA30_minS); - static final char[] DFA30_max = DFA.unpackEncodedStringToUnsignedChars(DFA30_maxS); - static final short[] DFA30_accept = DFA.unpackEncodedString(DFA30_acceptS); - static final short[] DFA30_special = DFA.unpackEncodedString(DFA30_specialS); - static final short[][] DFA30_transition; + static final short[] DFA32_eot = DFA.unpackEncodedString(DFA32_eotS); + static final short[] DFA32_eof = DFA.unpackEncodedString(DFA32_eofS); + static final char[] DFA32_min = DFA.unpackEncodedStringToUnsignedChars(DFA32_minS); + static final char[] DFA32_max = DFA.unpackEncodedStringToUnsignedChars(DFA32_maxS); + static final short[] DFA32_accept = DFA.unpackEncodedString(DFA32_acceptS); + static final short[] DFA32_special = DFA.unpackEncodedString(DFA32_specialS); + static final short[][] DFA32_transition; static { - int numStates = DFA30_transitionS.length; - DFA30_transition = new short[numStates][]; + int numStates = DFA32_transitionS.length; + DFA32_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { - DFA30_transition[i] = DFA.unpackEncodedString(DFA30_transitionS[i]); + DFA32_transition[i] = DFA.unpackEncodedString(DFA32_transitionS[i]); } } - class DFA30 extends DFA { + class DFA32 extends DFA { - public DFA30(BaseRecognizer recognizer) { + public DFA32(BaseRecognizer recognizer) { this.recognizer = recognizer; - this.decisionNumber = 30; - this.eot = DFA30_eot; - this.eof = DFA30_eof; - this.min = DFA30_min; - this.max = DFA30_max; - this.accept = DFA30_accept; - this.special = DFA30_special; - this.transition = DFA30_transition; + this.decisionNumber = 32; + this.eot = DFA32_eot; + this.eof = DFA32_eof; + this.min = DFA32_min; + this.max = DFA32_max; + this.accept = DFA32_accept; + this.special = DFA32_special; + this.transition = DFA32_transition; } public String getDescription() { - return "141:54: ( STRING_LITERAL | NUMBER | variable | method )"; + return "150:5: ( STRING_LITERAL | NUMBER | variable | method )"; } } - static final String DFA31_eotS = + static final String DFA33_eotS = "\10\uffff"; - static final String DFA31_eofS = + static final String DFA33_eofS = "\10\uffff"; - static final String DFA31_minS = - "\1\51\2\uffff\1\7\1\53\2\uffff\1\7"; - static final String DFA31_maxS = - "\1\55\2\uffff\1\47\1\53\2\uffff\1\47"; - static final String DFA31_acceptS = + static final String DFA33_minS = + "\1\53\2\uffff\1\10\1\55\2\uffff\1\10"; + static final String DFA33_maxS = + "\1\57\2\uffff\1\21\1\55\2\uffff\1\21"; + static final String DFA33_acceptS = "\1\uffff\1\1\1\2\2\uffff\1\3\1\4\1\uffff"; - static final String DFA31_specialS = + static final String DFA33_specialS = "\10\uffff}>"; - static final String[] DFA31_transitionS = { + static final String[] DFA33_transitionS = { "\1\2\1\uffff\1\3\1\uffff\1\1", "", "", - "\1\5\1\6\7\uffff\1\4\26\uffff\1\5", + "\1\6\7\uffff\1\4\1\5", "\1\7", "", "", - "\1\5\1\6\7\uffff\1\4\26\uffff\1\5" + "\1\6\7\uffff\1\4\1\5" }; - static final short[] DFA31_eot = DFA.unpackEncodedString(DFA31_eotS); - static final short[] DFA31_eof = DFA.unpackEncodedString(DFA31_eofS); - static final char[] DFA31_min = DFA.unpackEncodedStringToUnsignedChars(DFA31_minS); - static final char[] DFA31_max = DFA.unpackEncodedStringToUnsignedChars(DFA31_maxS); - static final short[] DFA31_accept = DFA.unpackEncodedString(DFA31_acceptS); - static final short[] DFA31_special = DFA.unpackEncodedString(DFA31_specialS); - static final short[][] DFA31_transition; + static final short[] DFA33_eot = DFA.unpackEncodedString(DFA33_eotS); + static final short[] DFA33_eof = DFA.unpackEncodedString(DFA33_eofS); + static final char[] DFA33_min = DFA.unpackEncodedStringToUnsignedChars(DFA33_minS); + static final char[] DFA33_max = DFA.unpackEncodedStringToUnsignedChars(DFA33_maxS); + static final short[] DFA33_accept = DFA.unpackEncodedString(DFA33_acceptS); + static final short[] DFA33_special = DFA.unpackEncodedString(DFA33_specialS); + static final short[][] DFA33_transition; static { - int numStates = DFA31_transitionS.length; - DFA31_transition = new short[numStates][]; + int numStates = DFA33_transitionS.length; + DFA33_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { - DFA31_transition[i] = DFA.unpackEncodedString(DFA31_transitionS[i]); + DFA33_transition[i] = DFA.unpackEncodedString(DFA33_transitionS[i]); } } - class DFA31 extends DFA { + class DFA33 extends DFA { - public DFA31(BaseRecognizer recognizer) { + public DFA33(BaseRecognizer recognizer) { this.recognizer = recognizer; - this.decisionNumber = 31; - this.eot = DFA31_eot; - this.eof = DFA31_eof; - this.min = DFA31_min; - this.max = DFA31_max; - this.accept = DFA31_accept; - this.special = DFA31_special; - this.transition = DFA31_transition; + this.decisionNumber = 33; + this.eot = DFA33_eot; + this.eof = DFA33_eof; + this.min = DFA33_min; + this.max = DFA33_max; + this.accept = DFA33_accept; + this.special = DFA33_special; + this.transition = DFA33_transition; } public String getDescription() { - return "141:106: ( STRING_LITERAL | NUMBER | variable | method )"; + return "150:54: ( STRING_LITERAL | NUMBER | variable | method )"; } } static final String DFA34_eotS = @@ -4850,22 +5076,22 @@ public String getDescription() { static final String DFA34_eofS = "\10\uffff"; static final String DFA34_minS = - "\1\12\1\5\2\uffff\1\53\2\uffff\1\5"; + "\1\53\2\uffff\1\7\1\55\2\uffff\1\7"; static final String DFA34_maxS = - "\1\55\1\20\2\uffff\1\53\2\uffff\1\20"; + "\1\57\2\uffff\1\51\1\55\2\uffff\1\51"; static final String DFA34_acceptS = - "\2\uffff\1\3\1\4\1\uffff\1\1\1\2\1\uffff"; + "\1\uffff\1\1\1\2\2\uffff\1\3\1\4\1\uffff"; static final String DFA34_specialS = "\10\uffff}>"; static final String[] DFA34_transitionS = { - "\1\2\40\uffff\1\1\1\uffff\1\3", - "\1\5\2\uffff\1\6\5\uffff\1\5\1\uffff\1\4", + "\1\2\1\uffff\1\3\1\uffff\1\1", "", "", + "\1\5\1\6\7\uffff\1\4\30\uffff\1\5", "\1\7", "", "", - "\1\5\2\uffff\1\6\5\uffff\1\5\1\uffff\1\4" + "\1\5\1\6\7\uffff\1\4\30\uffff\1\5" }; static final short[] DFA34_eot = DFA.unpackEncodedString(DFA34_eotS); @@ -4898,14 +5124,70 @@ public DFA34(BaseRecognizer recognizer) { this.transition = DFA34_transition; } public String getDescription() { - return "155:1: p_input : ( variable | method | array | STRING_LITERAL );"; + return "150:106: ( STRING_LITERAL | NUMBER | variable | method )"; + } + } + static final String DFA37_eotS = + "\10\uffff"; + static final String DFA37_eofS = + "\10\uffff"; + static final String DFA37_minS = + "\1\12\1\5\2\uffff\1\55\2\uffff\1\5"; + static final String DFA37_maxS = + "\1\57\1\20\2\uffff\1\55\2\uffff\1\20"; + static final String DFA37_acceptS = + "\2\uffff\1\3\1\4\1\uffff\1\1\1\2\1\uffff"; + static final String DFA37_specialS = + "\10\uffff}>"; + static final String[] DFA37_transitionS = { + "\1\2\42\uffff\1\1\1\uffff\1\3", + "\1\5\1\uffff\1\5\1\6\5\uffff\1\5\1\uffff\1\4", + "", + "", + "\1\7", + "", + "", + "\1\5\1\uffff\1\5\1\6\5\uffff\1\5\1\uffff\1\4" + }; + + static final short[] DFA37_eot = DFA.unpackEncodedString(DFA37_eotS); + static final short[] DFA37_eof = DFA.unpackEncodedString(DFA37_eofS); + static final char[] DFA37_min = DFA.unpackEncodedStringToUnsignedChars(DFA37_minS); + static final char[] DFA37_max = DFA.unpackEncodedStringToUnsignedChars(DFA37_maxS); + static final short[] DFA37_accept = DFA.unpackEncodedString(DFA37_acceptS); + static final short[] DFA37_special = DFA.unpackEncodedString(DFA37_specialS); + static final short[][] DFA37_transition; + + static { + int numStates = DFA37_transitionS.length; + DFA37_transition = new short[numStates][]; + for (int i=0; i<numStates; i++) { + DFA37_transition[i] = DFA.unpackEncodedString(DFA37_transitionS[i]); + } + } + + class DFA37 extends DFA { + + public DFA37(BaseRecognizer recognizer) { + this.recognizer = recognizer; + this.decisionNumber = 37; + this.eot = DFA37_eot; + this.eof = DFA37_eof; + this.min = DFA37_min; + this.max = DFA37_max; + this.accept = DFA37_accept; + this.special = DFA37_special; + this.transition = DFA37_transition; + } + public String getDescription() { + return "164:1: p_input : ( variable | method | array | STRING_LITERAL );"; } } public static final BitSet FOLLOW_twig_print_statement_in_twig_source69 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_twig_control_statement_in_twig_source73 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_CTRL_OPEN_in_twig_control_statement89 = new BitSet(new long[]{0x0000083F9F800080L}); + public static final BitSet FOLLOW_CTRL_OPEN_in_twig_control_statement89 = new BitSet(new long[]{0x000020FE7F800080L}); public static final BitSet FOLLOW_twig_control_in_twig_control_statement91 = new BitSet(new long[]{0x0000000000000080L}); public static final BitSet FOLLOW_CTRL_CLOSE_in_twig_control_statement94 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_twig_for_in_twig_control108 = new BitSet(new long[]{0x0000000000000002L}); @@ -4918,144 +5200,151 @@ public String getDescription() { public static final BitSet FOLLOW_twig_import_in_twig_control136 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_twig_set_in_twig_control140 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_twig_include_in_twig_control144 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_INCLUDE_in_twig_include159 = new BitSet(new long[]{0x00002A0004000000L}); - public static final BitSet FOLLOW_include_ternary_in_twig_include162 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_include_statement_in_twig_include166 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_twig_ternary_in_include_ternary182 = new BitSet(new long[]{0x0000008000000002L}); - public static final BitSet FOLLOW_ONLY_in_include_ternary184 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_include_statement201 = new BitSet(new long[]{0x000000C000000002L}); - public static final BitSet FOLLOW_ONLY_in_include_statement204 = new BitSet(new long[]{0x0000004000000002L}); - public static final BitSet FOLLOW_WITH_in_include_statement208 = new BitSet(new long[]{0x0000280004100000L}); - public static final BitSet FOLLOW_variable_in_include_statement211 = new BitSet(new long[]{0x0000008000000002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_include_statement215 = new BitSet(new long[]{0x0000008000000002L}); - public static final BitSet FOLLOW_method_in_include_statement219 = new BitSet(new long[]{0x0000008000000002L}); - public static final BitSet FOLLOW_json_in_include_statement223 = new BitSet(new long[]{0x0000008000000002L}); - public static final BitSet FOLLOW_ONLY_in_include_statement226 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_SET_in_twig_set245 = new BitSet(new long[]{0x0000080004000000L}); - public static final BitSet FOLLOW_twig_assignment_in_twig_set247 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_COMMA_in_twig_set250 = new BitSet(new long[]{0x0000080004000000L}); - public static final BitSet FOLLOW_twig_assignment_in_twig_set252 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_ENDSET_in_twig_set259 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_twig_left_assignment_in_twig_assignment274 = new BitSet(new long[]{0x0000000000001002L}); - public static final BitSet FOLLOW_ASIG_in_twig_assignment277 = new BitSet(new long[]{0x0000280004100400L}); - public static final BitSet FOLLOW_twig_right_assignment_in_twig_assignment279 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_variable_in_twig_left_assignment297 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_COMMA_in_twig_left_assignment300 = new BitSet(new long[]{0x0000080004000000L}); - public static final BitSet FOLLOW_variable_in_twig_left_assignment302 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_right_assignment321 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_variable_in_twig_right_assignment325 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_method_in_twig_right_assignment329 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_array_in_twig_right_assignment333 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_json_in_twig_right_assignment337 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_twig_tilde_argument_in_twig_right_assignment341 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_COMMA_in_twig_right_assignment345 = new BitSet(new long[]{0x0000280004100400L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_right_assignment348 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_variable_in_twig_right_assignment352 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_method_in_twig_right_assignment356 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_array_in_twig_right_assignment360 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_json_in_twig_right_assignment364 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_twig_tilde_argument_in_twig_right_assignment368 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_tilde_argument387 = new BitSet(new long[]{0x0000000000002000L}); - public static final BitSet FOLLOW_variable_in_twig_tilde_argument391 = new BitSet(new long[]{0x0000000000002000L}); - public static final BitSet FOLLOW_method_in_twig_tilde_argument395 = new BitSet(new long[]{0x0000000000002000L}); - public static final BitSet FOLLOW_array_in_twig_tilde_argument399 = new BitSet(new long[]{0x0000000000002000L}); - public static final BitSet FOLLOW_json_in_twig_tilde_argument403 = new BitSet(new long[]{0x0000000000002000L}); - public static final BitSet FOLLOW_TILDE_in_twig_tilde_argument406 = new BitSet(new long[]{0x0000280004100400L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_tilde_argument409 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_variable_in_twig_tilde_argument413 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_method_in_twig_tilde_argument417 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_array_in_twig_tilde_argument421 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_json_in_twig_tilde_argument425 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_FROM_in_twig_import442 = new BitSet(new long[]{0x0000200000000000L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_import445 = new BitSet(new long[]{0x0000000200000000L}); - public static final BitSet FOLLOW_IMPORT_in_twig_import450 = new BitSet(new long[]{0x0000280004000000L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_import453 = new BitSet(new long[]{0x0000000040000002L}); - public static final BitSet FOLLOW_variable_in_twig_import457 = new BitSet(new long[]{0x0000000040000002L}); - public static final BitSet FOLLOW_TWIG_AS_in_twig_import461 = new BitSet(new long[]{0x0000080000000000L}); - public static final BitSet FOLLOW_STRING_in_twig_import464 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_COMMA_in_twig_import467 = new BitSet(new long[]{0x0000080000000000L}); - public static final BitSet FOLLOW_STRING_in_twig_import469 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_MACRO_in_twig_macro491 = new BitSet(new long[]{0x0000080004000000L}); - public static final BitSet FOLLOW_variable_in_twig_macro494 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_method_in_twig_macro498 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_ENDMACRO_in_twig_macro504 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_IF_in_twig_if519 = new BitSet(new long[]{0x0000080004000000L}); - public static final BitSet FOLLOW_variable_in_twig_if521 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_method_in_twig_if525 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_ELSEIF_in_twig_elseif540 = new BitSet(new long[]{0x0000080004000000L}); - public static final BitSet FOLLOW_variable_in_twig_elseif543 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_method_in_twig_elseif547 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_FOR_in_twig_for563 = new BitSet(new long[]{0x0000080000000000L}); - public static final BitSet FOLLOW_STRING_in_twig_for565 = new BitSet(new long[]{0x0000000020000000L}); - public static final BitSet FOLLOW_IN_in_twig_for567 = new BitSet(new long[]{0x00002A0004000000L}); - public static final BitSet FOLLOW_for_arguments_in_twig_for569 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_for_value_in_for_arguments584 = new BitSet(new long[]{0x0000000000004002L}); - public static final BitSet FOLLOW_PIPE_in_for_arguments587 = new BitSet(new long[]{0x00002A0004000000L}); - public static final BitSet FOLLOW_for_value_in_for_arguments589 = new BitSet(new long[]{0x0000000000004002L}); - public static final BitSet FOLLOW_STRING_in_for_value606 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_for_value610 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_method_in_for_value614 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_range_in_for_value618 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_set_in_range633 = new BitSet(new long[]{0x0000000000008000L}); - public static final BitSet FOLLOW_DDOT_in_range645 = new BitSet(new long[]{0x00002A0000000000L}); - public static final BitSet FOLLOW_set_in_range647 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_ternary674 = new BitSet(new long[]{0x0000000000400000L}); - public static final BitSet FOLLOW_NUMBER_in_twig_ternary678 = new BitSet(new long[]{0x0000000000400000L}); - public static final BitSet FOLLOW_variable_in_twig_ternary682 = new BitSet(new long[]{0x0000000000400000L}); - public static final BitSet FOLLOW_method_in_twig_ternary686 = new BitSet(new long[]{0x0000000000400000L}); - public static final BitSet FOLLOW_QM_in_twig_ternary689 = new BitSet(new long[]{0x00002A0004000000L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_ternary692 = new BitSet(new long[]{0x0000000000020000L}); - public static final BitSet FOLLOW_NUMBER_in_twig_ternary696 = new BitSet(new long[]{0x0000000000020000L}); - public static final BitSet FOLLOW_variable_in_twig_ternary700 = new BitSet(new long[]{0x0000000000020000L}); - public static final BitSet FOLLOW_method_in_twig_ternary704 = new BitSet(new long[]{0x0000000000020000L}); - public static final BitSet FOLLOW_COLON_in_twig_ternary707 = new BitSet(new long[]{0x00002A0004000000L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_twig_ternary710 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_NUMBER_in_twig_ternary714 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_variable_in_twig_ternary718 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_method_in_twig_ternary722 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_PRINT_OPEN_in_twig_print_statement740 = new BitSet(new long[]{0x0000280004000420L}); - public static final BitSet FOLLOW_twig_print_in_twig_print_statement742 = new BitSet(new long[]{0x0000000000000020L}); - public static final BitSet FOLLOW_PRINT_CLOSE_in_twig_print_statement745 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_p_input_in_twig_print772 = new BitSet(new long[]{0x0000000000004002L}); - public static final BitSet FOLLOW_PIPE_in_twig_print775 = new BitSet(new long[]{0x0000280004000400L}); - public static final BitSet FOLLOW_p_input_in_twig_print777 = new BitSet(new long[]{0x0000000000004002L}); - public static final BitSet FOLLOW_variable_in_p_input794 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_method_in_p_input798 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_array_in_p_input802 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_p_input806 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_ARRAY_START_in_array824 = new BitSet(new long[]{0x00002A0004100000L}); - public static final BitSet FOLLOW_array_elements_in_array826 = new BitSet(new long[]{0x0000000000000800L}); - public static final BitSet FOLLOW_ARRAY_END_in_array828 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_array_element_in_array_elements843 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_COMMA_in_array_elements846 = new BitSet(new long[]{0x00002A0004100000L}); - public static final BitSet FOLLOW_array_element_in_array_elements848 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_STRING_in_array_element865 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_array_element869 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_NUMBER_in_array_element873 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_json_in_array_element877 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_in_variable894 = new BitSet(new long[]{0x0000000000010002L}); - public static final BitSet FOLLOW_DOT_in_variable897 = new BitSet(new long[]{0x0000080000000000L}); - public static final BitSet FOLLOW_STRING_in_variable900 = new BitSet(new long[]{0x0000000000010002L}); - public static final BitSet FOLLOW_variable_in_method930 = new BitSet(new long[]{0x0000000000000100L}); - public static final BitSet FOLLOW_METHOD_START_in_method932 = new BitSet(new long[]{0x00002A0004100200L}); - public static final BitSet FOLLOW_arguments_in_method934 = new BitSet(new long[]{0x0000000000000200L}); - public static final BitSet FOLLOW_METHOD_END_in_method937 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_argument_in_arguments953 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_COMMA_in_arguments957 = new BitSet(new long[]{0x00002A0004100000L}); - public static final BitSet FOLLOW_argument_in_arguments960 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_literal_argument_in_argument974 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_in_argument978 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_json_in_argument982 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_NUMBER_in_argument986 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_STRING_LITERAL_in_literal_argument999 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_JSON_START_in_json1025 = new BitSet(new long[]{0x0000280000200000L}); - public static final BitSet FOLLOW_json_arguments_in_json1027 = new BitSet(new long[]{0x0000000000200000L}); - public static final BitSet FOLLOW_JSON_END_in_json1030 = new BitSet(new long[]{0x0000000000000002L}); - public static final BitSet FOLLOW_json_argument_in_json_arguments1045 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_COMMA_in_json_arguments1048 = new BitSet(new long[]{0x0000280000000000L}); - public static final BitSet FOLLOW_json_argument_in_json_arguments1051 = new BitSet(new long[]{0x0000000000040002L}); - public static final BitSet FOLLOW_set_in_json_argument1069 = new BitSet(new long[]{0x0000000000020000L}); - public static final BitSet FOLLOW_COLON_in_json_argument1078 = new BitSet(new long[]{0x0000280000000000L}); - public static final BitSet FOLLOW_set_in_json_argument1081 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_twig_block_in_twig_control148 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_BLOCK_in_twig_block167 = new BitSet(new long[]{0x0000200010000000L}); + public static final BitSet FOLLOW_twig_block_param_in_twig_block169 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_ENDBLOCK_in_twig_block175 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_variable_in_twig_block_param192 = new BitSet(new long[]{0x0000A00010000402L}); + public static final BitSet FOLLOW_method_in_twig_block_param196 = new BitSet(new long[]{0x0000A00010000402L}); + public static final BitSet FOLLOW_twig_print_in_twig_block_param199 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_INCLUDE_in_twig_include215 = new BitSet(new long[]{0x0000A80010000000L}); + public static final BitSet FOLLOW_include_ternary_in_twig_include218 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_include_statement_in_twig_include222 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_twig_ternary_in_include_ternary238 = new BitSet(new long[]{0x0000020000000002L}); + public static final BitSet FOLLOW_ONLY_in_include_ternary240 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_include_statement257 = new BitSet(new long[]{0x0000030000000002L}); + public static final BitSet FOLLOW_ONLY_in_include_statement260 = new BitSet(new long[]{0x0000010000000002L}); + public static final BitSet FOLLOW_WITH_in_include_statement264 = new BitSet(new long[]{0x0000A00010100000L}); + public static final BitSet FOLLOW_variable_in_include_statement267 = new BitSet(new long[]{0x0000020000000002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_include_statement271 = new BitSet(new long[]{0x0000020000000002L}); + public static final BitSet FOLLOW_method_in_include_statement275 = new BitSet(new long[]{0x0000020000000002L}); + public static final BitSet FOLLOW_json_in_include_statement279 = new BitSet(new long[]{0x0000020000000002L}); + public static final BitSet FOLLOW_ONLY_in_include_statement282 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_SET_in_twig_set301 = new BitSet(new long[]{0x0000200010000000L}); + public static final BitSet FOLLOW_twig_assignment_in_twig_set303 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_COMMA_in_twig_set306 = new BitSet(new long[]{0x0000200010000000L}); + public static final BitSet FOLLOW_twig_assignment_in_twig_set308 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_ENDSET_in_twig_set315 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_twig_left_assignment_in_twig_assignment330 = new BitSet(new long[]{0x0000000000001002L}); + public static final BitSet FOLLOW_ASIG_in_twig_assignment333 = new BitSet(new long[]{0x0000A00010100400L}); + public static final BitSet FOLLOW_twig_right_assignment_in_twig_assignment335 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_variable_in_twig_left_assignment353 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_COMMA_in_twig_left_assignment356 = new BitSet(new long[]{0x0000200010000000L}); + public static final BitSet FOLLOW_variable_in_twig_left_assignment358 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_right_assignment377 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_variable_in_twig_right_assignment381 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_method_in_twig_right_assignment385 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_array_in_twig_right_assignment389 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_json_in_twig_right_assignment393 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_twig_tilde_argument_in_twig_right_assignment397 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_COMMA_in_twig_right_assignment401 = new BitSet(new long[]{0x0000A00010100400L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_right_assignment404 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_variable_in_twig_right_assignment408 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_method_in_twig_right_assignment412 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_array_in_twig_right_assignment416 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_json_in_twig_right_assignment420 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_twig_tilde_argument_in_twig_right_assignment424 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_tilde_argument443 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_variable_in_twig_tilde_argument447 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_method_in_twig_tilde_argument451 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_array_in_twig_tilde_argument455 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_json_in_twig_tilde_argument459 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_TILDE_in_twig_tilde_argument462 = new BitSet(new long[]{0x0000A00010100400L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_tilde_argument465 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_variable_in_twig_tilde_argument469 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_method_in_twig_tilde_argument473 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_array_in_twig_tilde_argument477 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_json_in_twig_tilde_argument481 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_FROM_in_twig_import498 = new BitSet(new long[]{0x0000800000000000L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_import501 = new BitSet(new long[]{0x0000000800000000L}); + public static final BitSet FOLLOW_IMPORT_in_twig_import506 = new BitSet(new long[]{0x0000A00010000000L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_import509 = new BitSet(new long[]{0x0000000100000002L}); + public static final BitSet FOLLOW_variable_in_twig_import513 = new BitSet(new long[]{0x0000000100000002L}); + public static final BitSet FOLLOW_TWIG_AS_in_twig_import517 = new BitSet(new long[]{0x0000200000000000L}); + public static final BitSet FOLLOW_STRING_in_twig_import520 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_COMMA_in_twig_import523 = new BitSet(new long[]{0x0000200000000000L}); + public static final BitSet FOLLOW_STRING_in_twig_import525 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_MACRO_in_twig_macro547 = new BitSet(new long[]{0x0000200010000000L}); + public static final BitSet FOLLOW_variable_in_twig_macro550 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_method_in_twig_macro554 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_ENDMACRO_in_twig_macro560 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_IF_in_twig_if575 = new BitSet(new long[]{0x0000200010000000L}); + public static final BitSet FOLLOW_variable_in_twig_if577 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_method_in_twig_if581 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_ELSEIF_in_twig_elseif596 = new BitSet(new long[]{0x0000200010000000L}); + public static final BitSet FOLLOW_variable_in_twig_elseif599 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_method_in_twig_elseif603 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_FOR_in_twig_for619 = new BitSet(new long[]{0x0000200000000000L}); + public static final BitSet FOLLOW_STRING_in_twig_for621 = new BitSet(new long[]{0x0000000080000000L}); + public static final BitSet FOLLOW_IN_in_twig_for623 = new BitSet(new long[]{0x0000A80010000000L}); + public static final BitSet FOLLOW_for_arguments_in_twig_for625 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_for_value_in_for_arguments640 = new BitSet(new long[]{0x0000000000004002L}); + public static final BitSet FOLLOW_PIPE_in_for_arguments643 = new BitSet(new long[]{0x0000A80010000000L}); + public static final BitSet FOLLOW_for_value_in_for_arguments645 = new BitSet(new long[]{0x0000000000004002L}); + public static final BitSet FOLLOW_STRING_in_for_value662 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_for_value666 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_method_in_for_value670 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_range_in_for_value674 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_set_in_range689 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_DDOT_in_range701 = new BitSet(new long[]{0x0000A80000000000L}); + public static final BitSet FOLLOW_set_in_range703 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_ternary730 = new BitSet(new long[]{0x0000000000400000L}); + public static final BitSet FOLLOW_NUMBER_in_twig_ternary734 = new BitSet(new long[]{0x0000000000400000L}); + public static final BitSet FOLLOW_variable_in_twig_ternary738 = new BitSet(new long[]{0x0000000000400000L}); + public static final BitSet FOLLOW_method_in_twig_ternary742 = new BitSet(new long[]{0x0000000000400000L}); + public static final BitSet FOLLOW_QM_in_twig_ternary745 = new BitSet(new long[]{0x0000A80010000000L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_ternary748 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_NUMBER_in_twig_ternary752 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_variable_in_twig_ternary756 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_method_in_twig_ternary760 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_COLON_in_twig_ternary763 = new BitSet(new long[]{0x0000A80010000000L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_twig_ternary766 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_NUMBER_in_twig_ternary770 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_variable_in_twig_ternary774 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_method_in_twig_ternary778 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_PRINT_OPEN_in_twig_print_statement796 = new BitSet(new long[]{0x0000A00010000420L}); + public static final BitSet FOLLOW_twig_print_in_twig_print_statement798 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_PRINT_CLOSE_in_twig_print_statement801 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_p_input_in_twig_print828 = new BitSet(new long[]{0x0000000000004002L}); + public static final BitSet FOLLOW_PIPE_in_twig_print831 = new BitSet(new long[]{0x0000A00010000400L}); + public static final BitSet FOLLOW_p_input_in_twig_print833 = new BitSet(new long[]{0x0000000000004002L}); + public static final BitSet FOLLOW_variable_in_p_input850 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_method_in_p_input854 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_array_in_p_input858 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_p_input862 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_ARRAY_START_in_array880 = new BitSet(new long[]{0x0000A80010100000L}); + public static final BitSet FOLLOW_array_elements_in_array882 = new BitSet(new long[]{0x0000000000000800L}); + public static final BitSet FOLLOW_ARRAY_END_in_array884 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_array_element_in_array_elements899 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_COMMA_in_array_elements902 = new BitSet(new long[]{0x0000A80010100000L}); + public static final BitSet FOLLOW_array_element_in_array_elements904 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_STRING_in_array_element921 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_array_element925 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_NUMBER_in_array_element929 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_json_in_array_element933 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_in_variable950 = new BitSet(new long[]{0x0000000000010002L}); + public static final BitSet FOLLOW_DOT_in_variable953 = new BitSet(new long[]{0x0000200000000000L}); + public static final BitSet FOLLOW_STRING_in_variable956 = new BitSet(new long[]{0x0000000000010002L}); + public static final BitSet FOLLOW_variable_in_method986 = new BitSet(new long[]{0x0000000000000100L}); + public static final BitSet FOLLOW_METHOD_START_in_method988 = new BitSet(new long[]{0x0000A80010100200L}); + public static final BitSet FOLLOW_arguments_in_method990 = new BitSet(new long[]{0x0000000000000200L}); + public static final BitSet FOLLOW_METHOD_END_in_method993 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_argument_in_arguments1009 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_COMMA_in_arguments1013 = new BitSet(new long[]{0x0000A80010100000L}); + public static final BitSet FOLLOW_argument_in_arguments1016 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_literal_argument_in_argument1030 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_in_argument1034 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_json_in_argument1038 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_NUMBER_in_argument1042 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STRING_LITERAL_in_literal_argument1055 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_JSON_START_in_json1081 = new BitSet(new long[]{0x0000A00000200000L}); + public static final BitSet FOLLOW_json_arguments_in_json1083 = new BitSet(new long[]{0x0000000000200000L}); + public static final BitSet FOLLOW_JSON_END_in_json1086 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_json_argument_in_json_arguments1101 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_COMMA_in_json_arguments1104 = new BitSet(new long[]{0x0000A00000000000L}); + public static final BitSet FOLLOW_json_argument_in_json_arguments1107 = new BitSet(new long[]{0x0000000000040002L}); + public static final BitSet FOLLOW_set_in_json_argument1125 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_COLON_in_json_argument1134 = new BitSet(new long[]{0x0000A00000000000L}); + public static final BitSet FOLLOW_set_in_json_argument1137 = new BitSet(new long[]{0x0000000000000002L}); } \ No newline at end of file diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.tokens b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.tokens index e26add9..99d5349 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.tokens +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/compiler/ast/parser/TwigParser.tokens @@ -17,35 +17,37 @@ BSLASH=19 JSON_START=20 JSON_END=21 QM=22 -FOR=23 -ENDFOR=24 -ELSE=25 -IF=26 -ELSEIF=27 -ENDIF=28 -IN=29 -TWIG_AS=30 -MACRO=31 -ENDMACRO=32 -IMPORT=33 -FROM=34 -SET=35 -ENDSET=36 -INCLUDE=37 -WITH=38 -ONLY=39 -DIGIT=40 -NUMBER=41 -STRING_CHAR=42 -STRING=43 -NONCONTROL_CHAR=44 -STRING_LITERAL=45 -LOWER=46 -UPPER=47 -UNDER=48 -LETTER=49 -SYMBOL=50 -WHITESPACE=51 -TWIG_PR_STMT=52 -TWIG_VAR=53 -LITERAL_ARG=54 +BLOCK=23 +ENDBLOCK=24 +FOR=25 +ENDFOR=26 +ELSE=27 +IF=28 +ELSEIF=29 +ENDIF=30 +IN=31 +TWIG_AS=32 +MACRO=33 +ENDMACRO=34 +IMPORT=35 +FROM=36 +SET=37 +ENDSET=38 +INCLUDE=39 +WITH=40 +ONLY=41 +DIGIT=42 +NUMBER=43 +STRING_CHAR=44 +STRING=45 +NONCONTROL_CHAR=46 +STRING_LITERAL=47 +LOWER=48 +UPPER=49 +UNDER=50 +LETTER=51 +SYMBOL=52 +WHITESPACE=53 +TWIG_PR_STMT=54 +TWIG_VAR=55 +LITERAL_ARG=56 diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/AbstractTwigLexer.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/AbstractTwigLexer.java index c4ac95e..4573040 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/AbstractTwigLexer.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/AbstractTwigLexer.java @@ -256,7 +256,7 @@ public String getNextToken() throws IOException { yylex = removeFromBuffer(); } - if (yylex == TWIG_CLOSE || yylex == TWIG_STMT_CLOSE) { + if (yylex == TWIG_CLOSETAG || yylex == TWIG_STMT_CLOSE) { pushBack(getLength()); } diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigLexer.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigLexer.java index 2699820..464d327 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigLexer.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigLexer.java @@ -1,4 +1,4 @@ -/* The following code was generated by JFlex 1.4.1 on 6/19/11 11:12 AM */ +/* The following code was generated by JFlex 1.4.1 on 6/21/11 1:46 AM */ /******************************************************************************** * Copyright (c) 2006 Zend Corporation and IBM Corporation. @@ -21,7 +21,7 @@ /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.4.1 - * on 6/19/11 11:12 AM from the specification file + * on 6/21/11 1:46 AM from the specification file * <tt>highlighting_scanner.jflex</tt> */ public class TwigLexer extends org.eclipse.twig.core.documentModel.parser.AbstractTwigLexer { @@ -781,17 +781,24 @@ else if (zzAtEOF) { return TWIG_CONSTANT_ENCAPSED_STRING; } case 45: break; + case 21: + { if(Debug.debugTokenizer) + dump("return TWIG_CLOSETAG " + TWIG_CLOSETAG); + + return TWIG_CLOSETAG; + } + case 46: break; case 4: { if(Debug.debugTokenizer) dump("TWIG NUMBER"); return TWIG_NUMBER; } - case 46: break; + case 47: break; case 13: { return TWIG_NUMBER; } - case 47: break; + case 48: break; case 20: { if(Debug.debugTokenizer) dump("TWIG COMMENT CLOSE"); @@ -799,13 +806,6 @@ else if (zzAtEOF) { yybegin(YYINITIAL); return TWIG_COMMENT_CLOSE; } - case 48: break; - case 21: - { if(Debug.debugTokenizer) - dump("TWIG_CLOSE"); - - return TWIG_CLOSE; - } case 49: break; case 8: { if(Debug.debugTokenizer) diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigRegionContext.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigRegionContext.java index bda8250..2bddc09 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigRegionContext.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigRegionContext.java @@ -18,6 +18,7 @@ public interface TwigRegionContext { public static final String TWIG_OPEN = "TWIG_OPEN"; //$NON-NLS-1$ public static final String TWIG_CLOSE = "TWIG_CLOSE"; //$NON-NLS-1$ + public static final String TWIG_CLOSETAG = "TWIG_CLOSETAG"; //$NON-NLS-1$ public static final String TWIG_STMT_OPEN = "TWIG_STMT_OPEN"; //$NON-NLS-1$ public static final String TWIG_STMT_CLOSE = "TWIG_STMT_CLOSE"; //$NON-NLS-1$ public static final String TWIG_CONTENT = "TWIG_CONTENT"; //$NON-NLS-1$ diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigTokenizer.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigTokenizer.java index a5bd191..ea95506 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigTokenizer.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/TwigTokenizer.java @@ -1,4 +1,4 @@ -/* The following code was generated by JFlex 1.2.2 on 6/21/11 12:01 AM */ +/* The following code was generated by JFlex 1.2.2 on 6/21/11 3:25 AM */ /******************************************************************************* * Copyright (c) 2006 Zend Corporation and IBM Corporation. @@ -44,7 +44,7 @@ /** * This class is a scanner generated by * <a href="http://www.informatik.tu-muenchen.de/~kleing/jflex/">JFlex</a> 1.2.2 - * on 6/21/11 12:01 AM from the specification file + * on 6/21/11 3:25 AM from the specification file * <tt>file:/Volumes/Data/Symfony2Eclipse/workspace/twig/org.eclipse.twig.core/Resources/parserTools/highlighting/TwigTokenizer.jflex</tt> */ public class TwigTokenizer implements BlockTokenizer, PHPRegionContext, DOMRegionContext, TwigRegionContext { @@ -182,43 +182,45 @@ public class TwigTokenizer implements BlockTokenizer, PHPRegionContext, DOMRegio 660, 726, 792, 858, 924, 990, 1056, 1122, 1188, 1254, 1320, 1386, 1452, 1518, 1584, 1650, 1716, 1782, 1848, 1914, 1980, 2046, 2112, 2178, 2244, 2310, 2376, 2442, 2508, 2574, - 2640, 2706, 2772, 2838, 2904, 2970, 3036, 2772, 2640, 3102, - 3102, 3168, 2640, 2640, 3102, 2772, 3234, 3300, 3366, 3432, - 3498, 3564, 3630, 3696, 3762, 3828, 2640, 3102, 3894, 3960, - 4026, 2640, 4092, 4092, 4158, 4224, 4290, 3894, 2640, 4356, - 4422, 2640, 4488, 4554, 4620, 4686, 4752, 2640, 4818, 4884, - 4950, 5016, 5082, 5148, 5214, 2640, 5280, 5346, 5412, 5478, - 5544, 5610, 5676, 2640, 5742, 5808, 5874, 3234, 5940, 6006, - 6072, 6138, 6204, 6204, 6270, 6336, 6402, 6468, 6534, 6534, - 6600, 6666, 6732, 6798, 6864, 6864, 6930, 6996, 7062, 7128, - 7194, 2640, 7260, 7260, 7326, 7392, 7458, 7524, 7590, 2640, - 2640, 3102, 2640, 3102, 7656, 7722, 7788, 2640, 7854, 7920, - 7986, 2640, 8052, 2640, 3102, 8118, 8184, 8250, 2640, 3102, - 8316, 8382, 8448, 2640, 8514, 2640, 2640, 8580, 8646, 8712, - 2640, 2640, 8778, 2640, 8844, 8910, 2772, 3234, 8976, 9042, - 9108, 9174, 2640, 9240, 9306, 9372, 9438, 9504, 9570, 2640, - 9636, 9702, 9768, 9834, 2640, 2640, 4092, 4224, 2640, 4290, - 4356, 4488, 4554, 9900, 4620, 2640, 9966, 4686, 2640, 10032, - 5280, 10098, 5478, 2640, 5544, 10164, 10230, 8844, 10296, 10362, - 10428, 5940, 2640, 10494, 10560, 6204, 10626, 6270, 2640, 10692, - 10758, 10824, 10824, 10890, 10956, 11022, 6468, 6204, 6534, 11088, - 6600, 2640, 11154, 6666, 11220, 6798, 6534, 6864, 11286, 6930, - 2640, 11352, 11418, 11484, 11484, 11550, 11616, 11682, 11748, 7128, - 11814, 7260, 11880, 7326, 2640, 11946, 12012, 12078, 12078, 12144, - 12210, 12276, 12342, 7524, 12408, 2640, 7854, 8052, 2640, 2640, - 2640, 2640, 12474, 8382, 12540, 12606, 12672, 12738, 12804, 12870, - 12936, 13002, 13068, 2640, 13134, 13200, 2640, 2640, 2640, 13266, - 3498, 13332, 3498, 13398, 13464, 13530, 13596, 13662, 10692, 13728, - 13728, 11352, 13794, 13794, 13860, 13926, 11946, 13992, 13992, 14058, - 14124, 14190, 14256, 14322, 14388, 2640, 14454, 14520, 14586, 2640, - 14652, 14718, 14784, 14850, 14916, 14982, 15048, 15114, 10890, 11550, - 15180, 15246, 12144, 15312, 15378, 15444, 15510, 15576, 15642, 15708, - 15774, 15840, 15906, 15972, 16038, 16104, 16170, 16236, 16302, 16368, - 16434, 16500, 16566, 16632, 16698, 2640, 2640, 16764, 16830, 16896, - 3498, 16962, 17028, 17094, 2640, 2640, 17160, 17226, 17292, 17358, - 17424, 2640, 2640, 2640, 17490, 17556, 17622, 17688, 17754, 17820, - 17886, 17952, 2640, 18018, 7128, 7524, 8382, 18084, 18150, 18216, - 18282, 3498 + 2640, 2706, 2772, 2838, 2904, 2970, 3036, 3102, 3168, 3036, + 3102, 3168, 3234, 3036, 3036, 3102, 3300, 3366, 3432, 3498, + 3564, 3630, 3696, 3762, 3828, 3894, 3960, 3036, 3102, 4026, + 3168, 4092, 4158, 3036, 4224, 4224, 4290, 4356, 4422, 4488, + 4026, 3036, 4554, 4620, 3036, 4686, 4752, 4818, 4884, 4950, + 5016, 3036, 5082, 5148, 5214, 5280, 5346, 5412, 5478, 5544, + 3036, 5610, 5676, 5742, 5808, 5874, 5940, 6006, 3036, 6072, + 6138, 6204, 3366, 6270, 6336, 6402, 6468, 6534, 6534, 6600, + 6666, 6732, 6798, 6864, 6864, 6930, 6996, 7062, 7128, 7194, + 7194, 7260, 7326, 7392, 7458, 7524, 3036, 7590, 7656, 7656, + 7722, 7788, 7854, 7920, 7986, 3036, 8052, 3036, 3102, 3168, + 3036, 3102, 8118, 3168, 8184, 8250, 3036, 8316, 8382, 8448, + 3036, 8514, 3300, 3300, 3036, 3102, 3168, 8580, 8646, 8712, + 3036, 3102, 3168, 8778, 8844, 8910, 3036, 8976, 9042, 3036, + 3036, 9108, 9174, 9240, 3036, 3036, 9306, 3036, 9372, 9438, + 9504, 9570, 9636, 9702, 9768, 9834, 9900, 9966, 10032, 3300, + 10098, 10164, 10230, 3036, 10296, 10362, 10428, 10494, 3036, 3036, + 4224, 4356, 3036, 4422, 10560, 4554, 4686, 4752, 10626, 4818, + 3036, 10692, 4884, 10758, 3036, 10824, 10890, 5610, 10956, 5808, + 3036, 5874, 11022, 11088, 11154, 9372, 11220, 11286, 11352, 6270, + 3036, 11418, 11484, 6534, 11550, 6600, 3036, 11616, 11682, 11748, + 11748, 11814, 11880, 11946, 12012, 6798, 6534, 6864, 12078, 6930, + 3036, 12144, 6996, 12210, 12276, 7128, 6864, 7194, 12342, 7260, + 3036, 12408, 12474, 12540, 12540, 12606, 12672, 12738, 12804, 12870, + 7458, 12936, 13002, 7656, 13068, 7722, 3036, 13134, 13200, 13266, + 13266, 13332, 13398, 13464, 13530, 13596, 7920, 13662, 13728, 3036, + 8316, 8514, 3036, 3036, 3036, 3036, 13794, 8844, 13860, 13926, + 13992, 14058, 14124, 14190, 14256, 14322, 14388, 14454, 14520, 3036, + 14586, 14652, 3036, 3036, 3036, 14718, 3630, 14784, 3630, 14850, + 14916, 14982, 15048, 15114, 11616, 15180, 15180, 12408, 15246, 15246, + 15312, 15378, 13134, 15444, 15444, 15510, 15576, 15642, 15708, 15774, + 15840, 3036, 15906, 15972, 16038, 3036, 16104, 16170, 16236, 16302, + 16368, 16434, 16500, 16566, 11814, 12606, 16632, 16698, 13332, 16764, + 16830, 16896, 16962, 17028, 17094, 17160, 17226, 17292, 17358, 17424, + 17490, 17556, 17622, 17688, 17754, 17820, 17886, 17952, 18018, 18084, + 18150, 3036, 3036, 18216, 18282, 18348, 3630, 18414, 18480, 18546, + 3036, 3036, 18612, 18678, 18744, 18810, 18876, 3036, 3036, 3036, + 18942, 19008, 19074, 19140, 19206, 19272, 19338, 19404, 3036, 19470, + 7458, 7920, 8844, 19536, 19602, 19668, 19734, 3630 }; /** @@ -226,337 +228,372 @@ public class TwigTokenizer implements BlockTokenizer, PHPRegionContext, DOMRegio */ final private static String yy_packed = "\1\51\1\52\3\51\1\53\5\51\1\54\1\51\1\55"+ - "\1\53\2\51\1\56\2\51\1\57\1\60\54\51\1\61"+ - "\1\62\100\61\1\51\1\63\20\51\1\64\2\51\1\65"+ - "\54\51\1\66\1\67\3\66\1\70\7\66\1\71\1\70"+ - "\6\66\1\70\54\66\1\51\1\63\5\51\1\72\15\51"+ - "\1\65\55\51\1\63\2\51\1\73\1\74\2\51\2\75"+ - "\4\51\1\74\6\51\1\74\3\51\4\75\1\76\6\75"+ - "\1\77\2\75\1\51\1\75\1\100\5\75\1\101\2\75"+ - "\1\51\3\75\1\51\3\75\1\51\2\75\1\51\1\75"+ - "\4\51\1\63\2\51\1\73\1\102\10\51\1\102\6\51"+ - "\1\102\54\51\1\103\1\104\2\103\1\105\20\103\1\65"+ - "\54\103\1\51\1\63\2\51\1\106\1\74\2\51\2\107"+ - "\4\51\1\74\6\51\1\74\3\51\16\107\1\51\12\107"+ - "\1\51\3\107\1\51\3\107\1\51\2\107\1\51\1\107"+ - "\4\51\1\63\2\51\1\106\1\74\2\51\2\107\4\51"+ - "\1\74\6\51\1\74\3\51\16\107\1\110\12\107\1\51"+ - "\3\107\1\51\3\107\1\51\2\107\1\51\1\107\3\51"+ - "\1\111\1\63\1\51\1\112\1\113\1\74\4\111\1\114"+ - "\1\111\1\115\1\111\1\74\6\111\1\74\54\111\1\51"+ - "\1\63\2\51\1\116\20\51\1\65\55\51\1\63\1\117"+ - "\1\120\4\51\2\121\13\51\1\65\3\51\16\121\1\51"+ - "\12\121\1\51\3\121\1\51\3\121\1\51\2\121\1\51"+ - "\1\121\4\51\1\63\1\117\1\120\4\51\2\121\13\51"+ - "\1\65\3\51\16\121\1\122\12\121\1\51\3\121\1\51"+ - "\3\121\1\51\2\121\1\51\1\121\3\51\1\123\1\63"+ - "\1\117\1\124\1\123\1\51\4\123\1\125\1\123\1\126"+ - "\1\123\1\51\6\123\1\65\54\123\1\51\1\63\23\51"+ - "\1\65\54\51\1\127\1\52\1\130\1\131\1\127\1\132"+ - "\2\127\2\133\4\127\1\132\6\127\1\132\3\127\16\134"+ - "\1\127\12\134\1\127\3\134\1\127\3\134\1\127\2\134"+ - "\1\127\1\134\3\127\1\51\1\135\1\130\1\131\1\51"+ - "\1\136\2\51\2\137\3\51\1\55\1\136\6\51\1\136"+ - "\3\51\16\137\1\51\12\137\1\51\3\137\1\51\3\137"+ - "\1\51\2\137\1\51\1\137\4\51\1\135\1\130\1\131"+ - "\1\51\1\136\2\51\2\137\3\51\1\55\1\136\6\51"+ - "\1\136\3\51\16\137\1\140\12\137\1\51\3\137\1\51"+ - "\3\137\1\51\2\137\1\51\1\137\3\51\1\141\1\142"+ - "\1\130\1\143\1\141\1\136\4\141\1\144\1\141\1\145"+ - "\1\146\1\136\6\141\1\136\54\141\1\51\1\147\1\150"+ - "\2\51\1\136\7\51\1\55\1\136\6\51\1\136\4\51"+ - "\1\151\1\152\5\51\1\153\10\51\1\153\1\51\1\152"+ - "\1\151\25\51\1\63\1\150\2\51\1\136\7\51\1\154"+ - "\1\136\6\51\1\136\2\51\1\155\52\51\1\63\1\150"+ - "\2\51\1\136\2\51\2\156\3\51\1\154\1\136\6\51"+ - "\1\136\2\51\1\155\16\156\1\51\12\156\1\51\3\156"+ - "\1\51\3\156\1\51\2\156\1\51\1\156\4\51\1\63"+ - "\1\150\2\51\1\136\7\51\1\154\1\136\6\51\1\136"+ - "\2\51\1\155\12\51\1\157\5\51\1\160\11\51\1\157"+ - "\16\51\1\161\1\63\1\150\1\162\1\161\1\136\4\161"+ - "\1\163\1\161\1\164\1\165\1\136\6\161\1\136\2\161"+ - "\1\166\51\161\1\167\1\63\1\150\1\170\1\167\1\136"+ - "\4\167\1\171\1\167\1\172\1\173\1\136\6\167\1\136"+ - "\2\167\1\174\51\167\1\175\1\63\1\150\1\176\1\175"+ - "\1\136\4\175\1\177\1\175\1\200\1\201\1\136\6\175"+ - "\1\136\54\175\1\202\1\203\1\204\77\202\1\205\1\63"+ - "\1\150\1\206\1\205\1\136\4\205\1\207\1\205\1\210"+ - "\1\211\1\136\6\205\1\136\54\205\1\212\1\213\1\214"+ - "\77\212\1\215\1\216\100\215\1\217\1\220\2\217\1\221"+ - "\14\217\1\221\60\217\5\222\1\223\6\222\1\224\1\154"+ - "\1\223\6\222\1\223\1\225\51\222\1\225\1\222\5\226"+ - "\1\227\4\226\1\230\2\226\1\154\1\227\6\226\1\227"+ - "\1\231\51\226\1\231\1\226\1\51\1\63\3\51\1\53"+ - "\7\51\1\154\1\53\6\51\1\60\54\51\1\232\1\233"+ - "\17\232\1\234\4\232\1\235\1\236\52\232\1\237\1\240"+ - "\100\237\1\51\1\63\23\51\1\65\1\241\53\51\1\242"+ - "\1\243\10\242\1\244\65\242\1\245\1\246\1\51\1\63"+ - "\1\247\3\51\2\247\1\250\6\51\1\251\3\51\1\247"+ - "\1\51\1\65\3\51\16\250\1\51\12\250\1\51\3\250"+ - "\1\51\2\250\2\51\5\250\1\252\1\253\105\0\1\254"+ - "\1\255\14\0\1\256\2\0\1\257\56\0\1\260\3\0"+ - "\1\261\7\0\1\262\1\261\6\0\1\261\61\0\1\263"+ - "\2\0\2\264\4\0\1\263\6\0\1\263\1\265\2\0"+ - "\16\264\1\0\12\264\1\0\3\264\1\0\3\264\1\0"+ - "\2\264\1\0\1\264\20\0\1\266\3\0\1\267\4\0"+ - "\1\270\60\0\1\263\2\0\2\271\4\0\1\263\6\0"+ - "\1\263\3\0\16\271\1\0\12\271\1\0\3\271\1\0"+ - "\3\271\1\0\2\271\1\0\1\271\20\0\1\272\70\0"+ - "\1\255\14\0\1\256\2\0\1\273\77\0\1\274\74\0"+ - "\1\266\3\0\1\267\67\0\1\275\74\0\1\276\104\0"+ - "\1\74\10\0\1\74\6\0\1\74\62\0\4\75\5\0"+ - "\1\75\11\0\16\75\1\0\12\75\1\0\3\75\1\0"+ - "\6\75\1\0\2\75\10\0\4\75\5\0\1\75\11\0"+ - "\5\75\1\277\10\75\1\0\11\75\1\300\1\0\3\75"+ - "\1\0\6\75\1\0\2\75\10\0\4\75\5\0\1\75"+ - "\11\0\5\75\1\301\10\75\1\0\11\75\1\301\1\0"+ - "\3\75\1\0\6\75\1\0\2\75\10\0\4\75\5\0"+ - "\1\75\11\0\16\75\1\0\12\75\1\0\3\75\1\0"+ - "\4\75\2\302\1\0\2\75\10\0\4\75\5\0\1\75"+ - "\11\0\5\75\1\300\10\75\1\0\11\75\1\300\1\0"+ - "\3\75\1\0\6\75\1\0\2\75\7\0\1\102\10\0"+ - "\1\102\6\0\1\102\56\0\1\303\101\0\1\304\105\0"+ - "\4\107\5\0\1\107\11\0\16\107\1\0\12\107\1\0"+ - "\3\107\1\0\6\107\1\0\2\107\2\0\1\111\2\0"+ - "\1\305\1\111\1\0\4\111\1\0\1\111\1\0\1\111"+ - "\1\0\6\111\1\0\55\111\1\0\1\304\1\305\1\111"+ - "\1\0\4\111\1\0\1\111\1\0\1\111\1\0\6\111"+ - "\1\0\54\111\12\306\1\307\2\306\1\0\64\306\14\310"+ - "\1\307\1\0\64\310\2\0\1\117\1\311\104\0\4\121"+ - "\5\0\1\121\11\0\16\121\1\0\12\121\1\0\3\121"+ - "\1\0\6\121\1\0\2\121\2\0\1\123\2\0\1\312"+ - "\1\123\1\0\4\123\1\0\1\123\1\0\1\123\1\0"+ - "\6\123\1\0\55\123\1\0\1\117\1\313\1\123\1\0"+ - "\4\123\1\0\1\123\1\0\1\123\1\0\6\123\1\0"+ - "\54\123\1\125\2\314\1\315\1\125\1\314\4\125\1\316"+ - "\1\125\1\314\1\123\1\314\6\125\1\314\54\125\1\126"+ - "\2\317\1\320\1\126\1\317\4\126\1\317\1\126\1\316"+ - "\1\123\1\317\6\126\1\317\54\126\1\127\3\0\25\127"+ - "\16\0\1\127\12\0\1\127\3\0\1\127\3\0\1\127"+ - "\2\0\1\127\1\0\3\127\2\0\1\321\77\0\1\127"+ - "\1\260\2\0\1\127\1\132\10\127\1\132\6\127\1\132"+ - "\3\127\16\0\1\127\12\0\1\127\3\0\1\127\3\0"+ - "\1\127\2\0\1\127\1\0\4\127\3\0\2\127\4\133"+ - "\5\127\1\133\11\127\16\134\1\127\12\134\1\127\3\134"+ - "\1\127\3\134\1\133\2\134\1\127\1\134\1\133\2\127"+ - "\6\0\4\134\5\0\1\134\11\0\16\134\1\0\12\134"+ - "\1\0\3\134\1\0\6\134\1\0\2\134\5\0\1\254"+ - "\1\255\3\0\2\322\7\0\1\256\2\0\1\257\4\0"+ - "\16\322\1\0\12\322\1\0\3\322\1\0\3\322\1\0"+ - "\2\322\1\0\1\322\4\0\1\260\3\0\1\136\7\0"+ - "\1\262\1\136\6\0\1\136\62\0\4\137\5\0\1\137"+ - "\11\0\16\137\1\0\12\137\1\0\3\137\1\0\6\137"+ - "\1\0\2\137\2\0\1\141\2\0\1\323\1\141\1\0"+ - "\4\141\1\0\1\141\1\0\1\141\1\0\6\141\1\0"+ - "\54\141\3\0\1\254\1\255\3\0\2\324\7\0\1\256"+ - "\2\0\1\257\4\0\16\324\1\0\12\324\1\0\3\324"+ - "\1\0\3\324\1\0\2\324\1\0\1\324\3\0\1\141"+ - "\1\0\1\321\1\323\1\141\1\0\4\141\1\0\1\141"+ - "\1\0\1\141\1\0\6\141\1\0\54\141\12\325\1\326"+ - "\2\325\1\0\64\325\14\327\1\326\1\0\64\327\1\141"+ - "\2\0\1\323\1\141\1\0\4\141\1\0\1\141\1\0"+ - "\1\330\1\0\6\141\1\0\1\331\53\141\3\0\1\254"+ - "\1\255\14\0\1\256\2\0\1\332\122\0\1\333\70\0"+ - "\1\334\16\0\1\334\65\0\1\335\20\0\1\335\21\0"+ - "\22\336\1\337\57\336\6\0\4\156\5\0\1\156\11\0"+ - "\16\156\1\0\12\156\1\0\3\156\1\0\6\156\1\0"+ - "\2\156\52\0\1\340\5\0\1\340\110\0\1\341\14\0"+ - "\1\161\2\0\1\342\1\161\1\0\4\161\1\0\1\161"+ - "\1\0\1\161\1\0\6\161\1\0\54\161\1\163\2\343"+ - "\1\344\1\163\1\343\4\163\1\345\1\163\1\343\1\161"+ - "\1\343\6\163\1\343\54\163\1\346\2\347\1\350\1\351"+ - "\1\347\4\351\1\347\1\346\1\352\1\161\1\353\3\351"+ - "\1\346\2\351\1\353\1\351\2\346\31\351\1\346\6\351"+ - "\2\346\2\351\3\346\1\351\1\346\1\161\2\0\1\342"+ - "\1\161\1\0\4\161\1\0\1\161\1\0\1\354\1\0"+ - "\6\161\1\0\54\161\1\166\2\336\1\355\1\166\1\336"+ - "\4\166\1\336\1\166\1\336\1\166\1\336\3\166\1\356"+ - "\2\166\1\336\54\166\1\167\2\0\1\357\1\167\1\0"+ - "\4\167\1\0\1\167\1\0\1\167\1\0\6\167\1\0"+ - "\54\167\1\171\2\360\1\361\1\171\1\360\4\171\1\362"+ - "\1\171\1\360\1\171\1\360\6\171\1\360\54\171\1\172"+ - "\2\363\1\364\1\172\1\363\4\172\1\363\1\172\1\362"+ - "\1\172\1\363\6\172\1\363\54\172\1\167\2\0\1\357"+ - "\1\167\1\0\4\167\1\0\1\167\1\0\1\365\1\0"+ - "\6\167\1\0\54\167\1\174\2\336\1\366\1\174\1\336"+ - "\4\174\1\336\1\174\1\336\1\174\1\336\3\174\1\367"+ - "\2\174\1\336\54\174\1\175\2\0\1\370\1\175\1\0"+ - "\4\175\1\0\1\175\1\0\1\175\1\0\6\175\1\0"+ - "\54\175\1\177\2\371\1\372\1\177\1\371\4\177\1\373"+ - "\1\177\1\371\1\175\1\371\6\177\1\371\54\177\1\374"+ - "\2\375\1\376\1\377\1\375\4\377\1\375\1\374\1\u0100"+ - "\1\175\1\u0101\3\377\1\374\2\377\1\u0101\1\377\2\374"+ - "\31\377\1\374\6\377\2\374\2\377\3\374\1\377\1\374"+ - "\1\175\2\0\1\370\1\175\1\0\4\175\1\0\1\175"+ - "\1\0\1\u0102\1\0\6\175\1\0\54\175\2\202\1\0"+ - "\101\202\1\0\1\202\1\u0103\14\202\1\u0104\2\202\1\u0105"+ - "\55\202\1\205\2\0\1\u0106\1\205\1\0\4\205\1\0"+ - "\1\205\1\0\1\205\1\0\6\205\1\0\54\205\1\207"+ - "\2\u0107\1\u0108\1\207\1\u0107\4\207\1\u0109\1\207\1\u0107"+ - "\1\205\1\u0107\6\207\1\u0107\54\207\1\u010a\2\u010b\1\u010c"+ - "\1\u010d\1\u010b\4\u010d\1\u010b\1\u010a\1\u010e\1\205\1\u010f"+ - "\3\u010d\1\u010a\2\u010d\1\u010f\1\u010d\2\u010a\31\u010d\1\u010a"+ - "\6\u010d\2\u010a\2\u010d\3\u010a\1\u010d\1\u010a\1\205\2\0"+ - "\1\u0106\1\205\1\0\4\205\1\0\1\205\1\0\1\u0110"+ - "\1\0\6\205\1\0\54\205\2\212\1\0\101\212\1\0"+ - "\1\212\1\u0111\14\212\1\u0112\2\212\1\u0113\55\212\2\0"+ - "\1\u0114\77\0\14\222\2\0\10\222\1\u0115\51\222\1\u0115"+ - "\6\222\1\223\6\222\1\0\1\262\1\223\6\222\1\223"+ - "\1\u0115\51\222\1\u0115\16\222\1\0\64\222\12\226\1\0"+ - "\2\226\1\0\10\226\1\u0116\51\226\1\u0116\6\226\1\227"+ - "\4\226\1\0\2\226\1\262\1\227\6\226\1\227\1\u0116"+ - "\51\226\1\u0116\16\226\1\0\64\226\27\0\1\u0117\101\0"+ - "\1\u0118\101\0\1\u0119\101\0\1\u011a\52\0\12\242\1\0"+ - "\65\242\2\0\4\242\1\u011b\5\242\1\0\6\242\1\u011c"+ - "\2\242\1\u011d\53\242\12\0\1\u011e\20\0\16\u011e\1\0"+ - "\12\u011e\1\0\3\u011e\1\0\2\u011e\2\0\5\u011e\12\0"+ - "\1\250\6\0\1\250\11\0\16\250\1\0\12\250\1\0"+ - "\3\250\1\0\2\250\2\0\5\250\21\0\1\251\72\0"+ - "\1\u011f\20\0\16\u011f\1\0\12\u011f\1\0\3\u011f\1\0"+ - "\2\u011f\2\0\5\u011f\53\0\1\u0120\37\0\1\u0121\20\0"+ - "\1\u0122\55\0\1\u0123\102\0\1\263\2\0\2\272\4\0"+ - "\1\263\6\0\1\263\3\0\16\272\1\0\12\272\1\0"+ - "\3\272\1\0\3\272\1\0\2\272\1\0\1\272\3\0"+ - "\1\u0124\1\0\3\u0124\1\u0125\4\264\1\u0124\1\0\2\u0124"+ - "\1\u0125\1\264\1\u0124\1\0\3\u0124\1\u0125\3\u0124\16\264"+ - "\1\u0124\12\264\1\u0124\3\264\1\u0126\6\264\1\u0124\2\264"+ - "\2\u0124\17\0\1\u0127\15\0\1\u0128\51\0\1\266\10\0"+ - "\1\266\6\0\1\266\61\0\1\270\10\0\1\270\6\0"+ - "\1\270\54\0\1\u0124\1\0\3\u0124\1\u0125\4\271\1\u0124"+ - "\1\0\2\u0124\1\u0125\1\271\1\u0124\1\0\3\u0124\1\u0125"+ - "\3\u0124\16\271\1\u0124\12\271\1\u0124\3\271\1\u0129\6\271"+ - "\1\u0124\2\271\2\u0124\1\272\1\0\11\272\1\0\5\272"+ - "\1\0\60\272\30\0\1\u0122\53\0\1\u012a\101\0\1\u012b"+ - "\105\0\4\75\5\0\1\75\11\0\6\75\1\u012c\7\75"+ - "\1\0\10\75\1\u012d\1\75\1\0\3\75\1\0\6\75"+ - "\1\0\2\75\10\0\4\75\5\0\1\75\11\0\6\75"+ - "\1\u012d\7\75\1\0\10\75\1\u012d\1\75\1\0\3\75"+ - "\1\0\6\75\1\0\2\75\10\0\4\75\5\0\1\75"+ - "\11\0\16\75\1\0\1\75\1\u012e\10\75\1\0\3\75"+ - "\1\0\6\75\1\0\2\75\10\0\4\75\5\0\1\75"+ - "\11\0\16\75\1\0\1\75\1\u012f\10\75\1\0\3\75"+ - "\1\0\6\75\1\0\2\75\2\0\12\314\1\316\2\314"+ - "\1\0\64\314\14\317\1\316\1\0\64\317\6\0\4\322"+ - "\5\0\1\322\11\0\16\322\1\0\12\322\1\0\3\322"+ - "\1\0\6\322\1\0\2\322\10\0\4\324\5\0\1\324"+ - "\11\0\16\324\1\0\12\324\1\0\3\324\1\0\6\324"+ - "\1\0\2\324\2\0\1\141\2\0\1\323\1\141\1\266"+ - "\4\141\1\0\1\141\1\0\1\141\1\266\6\141\1\266"+ - "\55\141\2\0\1\323\1\141\1\270\4\141\1\0\1\141"+ - "\1\0\1\141\1\270\6\141\1\270\54\141\31\0\1\u0130"+ - "\36\0\1\u0130\45\0\1\u0131\16\0\1\u0131\67\0\1\u0132"+ - "\10\0\1\u0132\72\0\1\u0133\17\0\1\u0133\105\0\1\u0134"+ - "\12\0\12\343\1\345\2\343\1\0\64\343\1\346\2\347"+ - "\1\u0135\1\346\1\347\4\346\1\347\1\346\1\345\1\161"+ - "\1\347\6\346\1\347\54\346\14\347\1\345\1\0\64\347"+ - "\1\346\2\347\1\u0135\1\346\1\347\4\346\1\347\1\346"+ - "\1\u0136\1\161\1\347\6\346\1\347\54\346\14\0\1\u0137"+ - "\65\0\14\347\1\u0136\1\0\64\347\1\161\2\0\1\342"+ - "\1\161\1\266\4\161\1\0\1\161\1\0\1\161\1\266"+ - "\6\161\1\266\54\161\12\360\1\362\67\360\14\363\1\362"+ - "\65\363\1\167\2\0\1\357\1\167\1\266\4\167\1\0"+ - "\1\167\1\0\1\167\1\266\6\167\1\266\54\167\12\371"+ - "\1\373\2\371\1\0\64\371\1\374\2\375\1\u0138\1\374"+ - "\1\375\4\374\1\375\1\374\1\373\1\175\1\375\6\374"+ - "\1\375\54\374\14\375\1\373\1\0\64\375\1\374\2\375"+ - "\1\u0138\1\374\1\375\4\374\1\375\1\374\1\u0139\1\175"+ - "\1\375\6\374\1\375\54\374\14\0\1\u013a\65\0\14\375"+ - "\1\u0139\1\0\64\375\1\175\2\0\1\370\1\175\1\266"+ - "\4\175\1\0\1\175\1\0\1\175\1\266\6\175\1\266"+ - "\54\175\2\202\1\0\46\202\1\u013b\32\202\1\0\25\202"+ - "\1\u013c\51\202\12\u0107\1\u0109\2\u0107\1\0\64\u0107\1\u010a"+ - "\2\u010b\1\u013d\1\u010a\1\u010b\4\u010a\1\u010b\1\u010a\1\u0109"+ - "\1\205\1\u010b\6\u010a\1\u010b\54\u010a\14\u010b\1\u0109\1\0"+ - "\64\u010b\1\u010a\2\u010b\1\u013d\1\u010a\1\u010b\4\u010a\1\u010b"+ - "\1\u010a\1\u013e\1\205\1\u010b\6\u010a\1\u010b\54\u010a\14\0"+ - "\1\u013f\65\0\14\u010b\1\u013e\1\0\64\u010b\1\205\2\0"+ - "\1\u0106\1\205\1\266\4\205\1\0\1\205\1\0\1\205"+ - "\1\266\6\205\1\266\54\205\2\212\1\0\46\212\1\u0140"+ - "\32\212\1\0\25\212\1\u0141\51\212\12\242\1\0\36\242"+ - "\1\u0142\26\242\2\0\12\242\1\0\15\242\1\u0143\47\242"+ - "\12\0\1\u011e\6\0\1\u011e\10\0\1\u0144\16\u011e\1\0"+ - "\12\u011e\1\0\3\u011e\1\0\2\u011e\2\0\5\u011e\12\0"+ - "\1\u011f\6\0\1\u011f\11\0\16\u011f\1\0\12\u011f\1\0"+ - "\3\u011f\1\0\2\u011f\2\0\5\u011f\75\0\2\u0145\14\0"+ - "\1\u0146\123\0\1\u0147\121\0\1\u0148\30\0\1\u0124\1\0"+ - "\11\u0124\1\0\5\u0124\1\0\44\u0124\1\0\14\u0124\1\0"+ - "\3\u0124\1\u0125\5\u0124\1\0\2\u0124\1\u0125\2\u0124\1\0"+ - "\3\u0124\1\u0125\40\u0124\1\u0149\13\u0124\17\0\1\u0127\46\0"+ - "\1\u014a\32\0\1\u014b\11\0\3\u014b\5\0\1\u014b\10\0"+ - "\1\u014b\1\0\2\u014b\6\0\1\u014b\2\0\2\u014b\17\0"+ - "\1\75\1\u014c\2\75\5\0\1\75\11\0\16\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\10\0"+ - "\4\75\5\0\1\75\11\0\14\75\1\u014d\1\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\36\0"+ - "\1\u014e\16\0\1\u014e\65\0\1\u014f\20\0\1\u014f\57\0"+ - "\1\u0150\22\0\1\u0150\54\0\1\u0151\16\0\1\u0151\65\0"+ - "\1\u0152\20\0\1\u0152\24\0\2\u0153\1\0\4\u0153\2\0"+ - "\1\352\1\0\4\u0153\1\0\4\u0153\2\0\31\u0153\1\0"+ - "\6\u0153\2\0\2\u0153\3\0\1\u0153\4\0\2\u0154\1\0"+ - "\4\u0154\2\0\1\u0100\1\0\4\u0154\1\0\4\u0154\2\0"+ - "\31\u0154\1\0\6\u0154\2\0\2\u0154\3\0\1\u0154\1\0"+ - "\2\202\1\0\70\202\2\u0155\7\202\1\0\26\202\1\u0156"+ - "\50\202\3\0\2\u0157\1\0\4\u0157\2\0\1\u010e\1\0"+ - "\4\u0157\1\0\4\u0157\2\0\31\u0157\1\0\6\u0157\2\0"+ - "\2\u0157\3\0\1\u0157\1\0\2\212\1\0\70\212\2\u0158"+ - "\7\212\1\0\26\212\1\u0159\50\212\12\242\1\0\60\242"+ - "\2\u015a\3\242\2\0\12\242\1\0\16\242\1\u015b\46\242"+ - "\12\0\1\u015c\6\0\1\u015d\11\0\16\u015c\1\0\12\u015c"+ - "\1\0\3\u015c\1\0\2\u015c\2\0\5\u015c\53\0\1\u015e"+ - "\10\0\1\u015e\51\0\1\u015f\142\0\2\u0160\73\0\1\u0149"+ - "\32\0\1\u014b\11\0\3\u014b\5\0\1\u014b\10\0\1\u014b"+ - "\1\0\2\u014b\6\0\1\u014b\1\0\1\u014a\2\u014b\17\0"+ - "\4\75\5\0\1\75\11\0\12\75\1\u0161\3\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\10\0"+ - "\4\75\5\0\1\75\11\0\11\75\1\u0162\4\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\52\0"+ - "\1\u0163\5\0\1\u0163\67\0\1\u0164\76\0\1\u0165\10\0"+ - "\1\u0165\70\0\1\u0166\10\0\1\u0166\73\0\1\u0167\35\0"+ - "\2\202\1\0\46\202\1\u0168\10\202\1\u0168\21\202\1\0"+ - "\27\202\1\u0169\47\202\2\212\1\0\46\212\1\u016a\10\212"+ - "\1\u016a\21\212\1\0\27\212\1\u016b\47\212\12\242\1\0"+ - "\36\242\1\u016c\10\242\1\u016c\15\242\2\0\12\242\1\0"+ - "\17\242\1\u016d\45\242\12\0\1\u015c\6\0\1\u015c\2\0"+ - "\1\u016e\6\0\16\u015c\1\0\12\u015c\1\0\3\u015c\1\0"+ - "\2\u015c\2\0\5\u015c\21\0\1\u015d\2\0\1\u016f\64\0"+ - "\1\u015e\10\0\1\u015e\6\0\1\u015e\107\0\1\u0170\117\0"+ - "\1\u0171\10\0\1\u0171\25\0\4\75\5\0\1\75\11\0"+ - "\16\75\1\0\3\75\1\u0172\6\75\1\0\3\75\1\0"+ - "\6\75\1\0\2\75\10\0\4\75\5\0\1\75\11\0"+ - "\3\75\1\u0173\12\75\1\0\3\75\1\u0173\6\75\1\0"+ - "\3\75\1\0\6\75\1\0\2\75\53\0\1\u0174\73\0"+ - "\1\u0175\17\0\1\u0175\64\0\1\u0176\71\0\1\u0177\22\0"+ - "\1\u0177\51\0\1\u0178\36\0\1\u0178\11\0\2\202\1\0"+ - "\2\202\1\u0168\10\202\1\u0168\6\202\1\u0168\56\202\1\0"+ - "\30\202\1\u0179\46\202\2\212\1\0\2\212\1\u016a\10\212"+ - "\1\u016a\6\212\1\u016a\56\212\1\0\30\212\1\u017a\46\212"+ - "\5\242\1\u016c\4\242\1\0\3\242\1\u016c\6\242\1\u016c"+ - "\52\242\2\0\12\242\1\0\20\242\1\u017b\44\242\36\0"+ - "\1\u017c\52\0\1\u0171\10\0\1\u0171\6\0\1\u0171\62\0"+ - "\4\75\5\0\1\75\11\0\16\75\1\0\6\75\1\u017d"+ - "\3\75\1\0\3\75\1\0\6\75\1\0\2\75\43\0"+ - "\1\u017e\10\0\1\u017e\63\0\1\u017f\16\0\1\u017f\62\0"+ - "\1\u0180\16\0\1\u0180\26\0\2\202\1\0\31\202\1\u0181"+ - "\45\202\2\212\1\0\31\212\1\u0182\45\212\12\242\1\0"+ - "\21\242\1\u0183\43\242\35\0\1\u0184\54\0\4\75\5\0"+ - "\1\75\11\0\6\75\1\u0185\7\75\1\0\12\75\1\0"+ - "\3\75\1\0\6\75\1\0\2\75\2\0\2\202\1\0"+ - "\30\202\1\u0186\46\202\2\212\1\0\30\212\1\u0187\46\212"+ - "\12\242\1\0\20\242\1\u0188\44\242\32\0\1\u0189\57\0"+ - "\4\75\5\0\1\75\11\0\10\75\1\u018a\5\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\2\0"+ - "\2\202\1\0\25\202\1\u018b\51\202\2\212\1\0\25\212"+ - "\1\u018c\51\212\12\242\1\0\15\242\1\u018d\47\242\10\0"+ - "\4\75\5\0\1\75\11\0\12\75\1\u018e\3\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\10\0"+ - "\4\75\5\0\1\75\11\0\16\75\1\0\12\75\1\0"+ - "\3\75\1\0\4\75\1\u018f\1\75\1\0\2\75\10\0"+ - "\4\75\5\0\1\75\11\0\10\75\1\u0190\5\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\10\0"+ - "\4\75\5\0\1\75\11\0\10\75\1\u0191\5\75\1\0"+ - "\12\75\1\0\3\75\1\0\6\75\1\0\2\75\10\0"+ - "\4\75\5\0\1\75\11\0\16\75\1\0\3\75\1\u0192"+ - "\6\75\1\0\3\75\1\0\6\75\1\0\2\75\2\0"; + "\1\53\2\51\1\56\3\51\1\53\54\51\1\57\1\60"+ + "\13\57\1\61\64\57\1\62\1\63\13\62\1\64\4\62"+ + "\1\65\2\62\1\66\54\62\1\67\1\70\3\67\1\71"+ + "\7\67\1\72\1\71\6\67\1\71\54\67\1\62\1\63"+ + "\5\62\1\73\5\62\1\64\7\62\1\66\55\62\1\63"+ + "\2\62\1\74\1\75\2\62\2\76\3\62\1\64\1\75"+ + "\6\62\1\75\3\62\4\76\1\77\6\76\1\100\2\76"+ + "\1\62\1\76\1\101\5\76\1\102\2\76\1\62\3\76"+ + "\1\62\3\76\1\62\2\76\1\62\1\76\4\62\1\63"+ + "\2\62\1\74\1\103\7\62\1\64\1\103\6\62\1\103"+ + "\54\62\1\104\1\105\2\104\1\106\10\104\1\107\7\104"+ + "\1\66\54\104\1\62\1\63\2\62\1\110\1\75\2\62"+ + "\2\111\3\62\1\64\1\75\6\62\1\75\3\62\16\111"+ + "\1\62\12\111\1\62\3\111\1\62\3\111\1\62\2\111"+ + "\1\62\1\111\4\62\1\63\2\62\1\110\1\75\2\62"+ + "\2\111\3\62\1\64\1\75\6\62\1\75\3\62\16\111"+ + "\1\112\12\111\1\62\3\111\1\62\3\111\1\62\2\111"+ + "\1\62\1\111\3\62\1\113\1\63\1\62\1\114\1\115"+ + "\1\75\4\113\1\116\1\113\1\117\1\120\1\75\6\113"+ + "\1\75\54\113\1\62\1\63\2\62\1\121\10\62\1\64"+ + "\7\62\1\66\55\62\1\63\1\122\1\123\4\62\2\124"+ + "\3\62\1\64\7\62\1\66\3\62\16\124\1\62\12\124"+ + "\1\62\3\124\1\62\3\124\1\62\2\124\1\62\1\124"+ + "\4\62\1\63\1\122\1\123\4\62\2\124\3\62\1\64"+ + "\7\62\1\66\3\62\16\124\1\125\12\124\1\62\3\124"+ + "\1\62\3\124\1\62\2\124\1\62\1\124\3\62\1\126"+ + "\1\63\1\122\1\127\1\126\1\62\4\126\1\130\1\126"+ + "\1\131\1\132\1\62\6\126\1\66\54\126\1\62\1\63"+ + "\13\62\1\64\7\62\1\66\54\62\1\133\1\52\1\134"+ + "\1\135\1\133\1\136\2\133\2\137\4\133\1\136\6\133"+ + "\1\136\3\133\16\140\1\133\12\140\1\133\3\140\1\133"+ + "\3\140\1\133\2\140\1\133\1\140\3\133\1\62\1\141"+ + "\1\134\1\135\1\62\1\142\2\62\2\143\3\62\1\144"+ + "\1\142\6\62\1\142\3\62\16\143\1\62\12\143\1\62"+ + "\3\143\1\62\3\143\1\62\2\143\1\62\1\143\4\62"+ + "\1\141\1\134\1\135\1\62\1\142\2\62\2\143\3\62"+ + "\1\144\1\142\6\62\1\142\3\62\16\143\1\145\12\143"+ + "\1\62\3\143\1\62\3\143\1\62\2\143\1\62\1\143"+ + "\3\62\1\146\1\147\1\134\1\150\1\146\1\142\4\146"+ + "\1\151\1\146\1\152\1\153\1\142\6\146\1\142\54\146"+ + "\1\62\1\154\1\155\2\62\1\142\7\62\1\144\1\142"+ + "\6\62\1\142\4\62\1\156\1\157\5\62\1\160\10\62"+ + "\1\160\1\62\1\157\1\156\25\62\1\63\1\155\2\62"+ + "\1\142\7\62\1\161\1\142\6\62\1\142\2\62\1\162"+ + "\52\62\1\63\1\155\2\62\1\142\2\62\2\163\3\62"+ + "\1\161\1\142\6\62\1\142\2\62\1\162\16\163\1\62"+ + "\12\163\1\62\3\163\1\62\3\163\1\62\2\163\1\62"+ + "\1\163\4\62\1\63\1\155\2\62\1\142\7\62\1\161"+ + "\1\142\6\62\1\142\2\62\1\162\12\62\1\164\5\62"+ + "\1\165\11\62\1\164\16\62\1\166\1\63\1\155\1\167"+ + "\1\166\1\142\4\166\1\170\1\166\1\171\1\172\1\142"+ + "\6\166\1\142\2\166\1\173\51\166\1\174\1\63\1\155"+ + "\1\175\1\174\1\142\4\174\1\176\1\174\1\177\1\200"+ + "\1\142\6\174\1\142\2\174\1\201\51\174\1\202\1\63"+ + "\1\155\1\203\1\202\1\142\4\202\1\204\1\202\1\205"+ + "\1\206\1\142\6\202\1\142\54\202\1\207\1\210\1\211"+ + "\12\207\1\212\64\207\1\213\1\63\1\155\1\214\1\213"+ + "\1\142\4\213\1\215\1\213\1\216\1\217\1\142\6\213"+ + "\1\142\54\213\1\220\1\221\1\222\12\220\1\223\64\220"+ + "\1\224\1\225\13\224\1\226\64\224\1\227\1\230\2\227"+ + "\1\231\10\227\1\232\3\227\1\231\60\227\5\233\1\234"+ + "\6\233\1\235\1\161\1\234\6\233\1\234\1\236\51\233"+ + "\1\236\1\233\5\237\1\240\4\237\1\241\2\237\1\161"+ + "\1\240\6\237\1\240\1\242\51\237\1\242\1\237\1\62"+ + "\1\63\3\62\1\243\7\62\1\161\1\243\6\62\1\244"+ + "\54\62\1\245\1\246\13\245\1\247\3\245\1\250\4\245"+ + "\1\251\1\252\52\245\1\253\1\254\13\253\1\255\64\253"+ + "\1\62\1\63\13\62\1\64\7\62\1\66\1\256\53\62"+ + "\1\257\1\260\10\257\1\261\2\257\1\262\62\257\1\263"+ + "\1\264\1\62\1\63\1\265\3\62\2\265\1\266\4\62"+ + "\1\64\1\62\1\267\3\62\1\265\1\62\1\66\3\62"+ + "\16\266\1\62\12\266\1\62\3\266\1\62\2\266\2\62"+ + "\5\266\1\270\1\271\1\51\1\0\11\51\1\0\5\51"+ + "\1\0\60\51\3\0\1\272\1\273\14\0\1\274\2\0"+ + "\1\275\55\0\1\51\1\276\3\51\1\53\5\51\1\0"+ + "\1\51\1\277\1\53\2\51\1\0\3\51\1\53\54\51"+ + "\5\0\1\300\2\0\2\301\4\0\1\300\6\0\1\300"+ + "\1\302\2\0\16\301\1\0\12\301\1\0\3\301\1\0"+ + "\3\301\1\0\2\301\1\0\1\301\3\0\1\51\1\0"+ + "\11\51\1\0\5\51\1\303\4\51\1\304\53\51\5\0"+ + "\1\300\2\0\2\305\4\0\1\300\6\0\1\300\3\0"+ + "\16\305\1\0\12\305\1\0\3\305\1\0\3\305\1\0"+ + "\2\305\1\0\1\305\111\0\1\273\14\0\1\274\2\0"+ + "\1\306\76\0\1\303\102\0\1\307\60\0\1\276\3\0"+ + "\1\310\7\0\1\311\1\310\6\0\1\310\71\0\1\312"+ + "\3\0\1\303\67\0\1\313\74\0\1\314\104\0\1\75"+ + "\10\0\1\75\6\0\1\75\62\0\4\76\5\0\1\76"+ + "\11\0\16\76\1\0\12\76\1\0\3\76\1\0\6\76"+ + "\1\0\2\76\10\0\4\76\5\0\1\76\11\0\5\76"+ + "\1\315\10\76\1\0\11\76\1\316\1\0\3\76\1\0"+ + "\6\76\1\0\2\76\10\0\4\76\5\0\1\76\11\0"+ + "\5\76\1\317\10\76\1\0\11\76\1\317\1\0\3\76"+ + "\1\0\6\76\1\0\2\76\10\0\4\76\5\0\1\76"+ + "\11\0\16\76\1\0\12\76\1\0\3\76\1\0\4\76"+ + "\2\320\1\0\2\76\10\0\4\76\5\0\1\76\11\0"+ + "\5\76\1\316\10\76\1\0\11\76\1\316\1\0\3\76"+ + "\1\0\6\76\1\0\2\76\7\0\1\103\10\0\1\103"+ + "\6\0\1\103\56\0\1\321\101\0\1\322\105\0\4\111"+ + "\5\0\1\111\11\0\16\111\1\0\12\111\1\0\3\111"+ + "\1\0\6\111\1\0\2\111\2\0\1\113\2\0\1\323"+ + "\1\113\1\0\4\113\1\0\1\113\1\0\1\113\1\0"+ + "\6\113\1\0\55\113\1\0\1\322\1\323\1\113\1\0"+ + "\4\113\1\0\1\113\1\0\1\113\1\0\6\113\1\0"+ + "\54\113\12\324\1\325\2\324\1\0\64\324\14\326\1\325"+ + "\1\0\64\326\1\113\2\0\1\323\1\113\1\0\4\113"+ + "\1\0\1\113\1\0\1\113\1\0\2\113\1\327\3\113"+ + "\1\0\54\113\2\0\1\122\1\330\104\0\4\124\5\0"+ + "\1\124\11\0\16\124\1\0\12\124\1\0\3\124\1\0"+ + "\6\124\1\0\2\124\2\0\1\126\2\0\1\331\1\126"+ + "\1\0\4\126\1\0\1\126\1\0\1\126\1\0\6\126"+ + "\1\0\55\126\1\0\1\122\1\332\1\126\1\0\4\126"+ + "\1\0\1\126\1\0\1\126\1\0\6\126\1\0\54\126"+ + "\1\130\2\333\1\334\1\130\1\333\4\130\1\335\1\130"+ + "\1\333\1\126\1\333\6\130\1\333\54\130\1\131\2\336"+ + "\1\337\1\131\1\336\4\131\1\336\1\131\1\335\1\126"+ + "\1\336\6\131\1\336\54\131\1\126\2\0\1\331\1\126"+ + "\1\0\4\126\1\0\1\126\1\0\1\126\1\0\2\126"+ + "\1\340\3\126\1\0\54\126\1\133\3\0\25\133\16\0"+ + "\1\133\12\0\1\133\3\0\1\133\3\0\1\133\2\0"+ + "\1\133\1\0\3\133\2\0\1\341\77\0\1\133\1\276"+ + "\2\0\1\133\1\136\10\133\1\136\6\133\1\136\3\133"+ + "\16\0\1\133\12\0\1\133\3\0\1\133\3\0\1\133"+ + "\2\0\1\133\1\0\4\133\3\0\2\133\4\137\5\133"+ + "\1\137\11\133\16\140\1\133\12\140\1\133\3\140\1\133"+ + "\3\140\1\137\2\140\1\133\1\140\1\137\2\133\6\0"+ + "\4\140\5\0\1\140\11\0\16\140\1\0\12\140\1\0"+ + "\3\140\1\0\6\140\1\0\2\140\5\0\1\272\1\273"+ + "\3\0\2\342\7\0\1\274\2\0\1\275\4\0\16\342"+ + "\1\0\12\342\1\0\3\342\1\0\3\342\1\0\2\342"+ + "\1\0\1\342\4\0\1\276\3\0\1\142\7\0\1\311"+ + "\1\142\6\0\1\142\62\0\4\143\5\0\1\143\11\0"+ + "\16\143\1\0\12\143\1\0\3\143\1\0\6\143\1\0"+ + "\2\143\17\0\1\312\3\0\1\303\4\0\1\343\53\0"+ + "\1\146\2\0\1\344\1\146\1\0\4\146\1\0\1\146"+ + "\1\0\1\146\1\0\6\146\1\0\54\146\3\0\1\272"+ + "\1\273\3\0\2\345\7\0\1\274\2\0\1\275\4\0"+ + "\16\345\1\0\12\345\1\0\3\345\1\0\3\345\1\0"+ + "\2\345\1\0\1\345\3\0\1\146\1\0\1\341\1\344"+ + "\1\146\1\0\4\146\1\0\1\146\1\0\1\146\1\0"+ + "\6\146\1\0\54\146\12\346\1\347\2\346\1\0\64\346"+ + "\14\350\1\347\1\0\64\350\1\146\2\0\1\344\1\146"+ + "\1\0\4\146\1\0\1\146\1\0\1\351\1\0\2\146"+ + "\1\352\3\146\1\0\1\353\53\146\3\0\1\272\1\273"+ + "\14\0\1\274\2\0\1\354\122\0\1\355\70\0\1\356"+ + "\16\0\1\356\65\0\1\357\20\0\1\357\21\0\22\360"+ + "\1\361\57\360\6\0\4\163\5\0\1\163\11\0\16\163"+ + "\1\0\12\163\1\0\3\163\1\0\6\163\1\0\2\163"+ + "\52\0\1\362\5\0\1\362\110\0\1\363\14\0\1\166"+ + "\2\0\1\364\1\166\1\0\4\166\1\0\1\166\1\0"+ + "\1\166\1\0\6\166\1\0\54\166\1\170\2\365\1\366"+ + "\1\170\1\365\4\170\1\367\1\170\1\365\1\166\1\365"+ + "\6\170\1\365\54\170\1\370\2\371\1\372\1\373\1\371"+ + "\4\373\1\371\1\370\1\374\1\166\1\375\3\373\1\370"+ + "\2\373\1\375\1\373\2\370\31\373\1\370\6\373\2\370"+ + "\2\373\3\370\1\373\1\370\1\166\2\0\1\364\1\166"+ + "\1\0\4\166\1\0\1\166\1\0\1\376\1\0\2\166"+ + "\1\377\3\166\1\0\54\166\1\173\2\360\1\u0100\1\173"+ + "\1\360\4\173\1\360\1\173\1\360\1\173\1\360\3\173"+ + "\1\u0101\2\173\1\360\54\173\1\174\2\0\1\u0102\1\174"+ + "\1\0\4\174\1\0\1\174\1\0\1\174\1\0\6\174"+ + "\1\0\54\174\1\176\2\u0103\1\u0104\1\176\1\u0103\4\176"+ + "\1\u0105\1\176\1\u0103\1\176\1\u0103\6\176\1\u0103\54\176"+ + "\1\177\2\u0106\1\u0107\1\177\1\u0106\4\177\1\u0106\1\177"+ + "\1\u0105\1\177\1\u0106\6\177\1\u0106\54\177\1\174\2\0"+ + "\1\u0102\1\174\1\0\4\174\1\0\1\174\1\0\1\u0108"+ + "\1\0\2\174\1\u0109\3\174\1\0\54\174\1\201\2\360"+ + "\1\u010a\1\201\1\360\4\201\1\360\1\201\1\360\1\201"+ + "\1\360\3\201\1\u010b\2\201\1\360\54\201\1\202\2\0"+ + "\1\u010c\1\202\1\0\4\202\1\0\1\202\1\0\1\202"+ + "\1\0\6\202\1\0\54\202\1\204\2\u010d\1\u010e\1\204"+ + "\1\u010d\4\204\1\u010f\1\204\1\u010d\1\202\1\u010d\6\204"+ + "\1\u010d\54\204\1\u0110\2\u0111\1\u0112\1\u0113\1\u0111\4\u0113"+ + "\1\u0111\1\u0110\1\u0114\1\202\1\u0115\3\u0113\1\u0110\2\u0113"+ + "\1\u0115\1\u0113\2\u0110\31\u0113\1\u0110\6\u0113\2\u0110\2\u0113"+ + "\3\u0110\1\u0113\1\u0110\1\202\2\0\1\u010c\1\202\1\0"+ + "\4\202\1\0\1\202\1\0\1\u0116\1\0\2\202\1\u0117"+ + "\3\202\1\0\54\202\2\207\1\0\101\207\1\0\1\207"+ + "\1\u0118\14\207\1\u0119\2\207\1\u011a\57\207\1\0\16\207"+ + "\1\u011b\60\207\1\213\2\0\1\u011c\1\213\1\0\4\213"+ + "\1\0\1\213\1\0\1\213\1\0\6\213\1\0\54\213"+ + "\1\215\2\u011d\1\u011e\1\215\1\u011d\4\215\1\u011f\1\215"+ + "\1\u011d\1\213\1\u011d\6\215\1\u011d\54\215\1\u0120\2\u0121"+ + "\1\u0122\1\u0123\1\u0121\4\u0123\1\u0121\1\u0120\1\u0124\1\213"+ + "\1\u0125\3\u0123\1\u0120\2\u0123\1\u0125\1\u0123\2\u0120\31\u0123"+ + "\1\u0120\6\u0123\2\u0120\2\u0123\3\u0120\1\u0123\1\u0120\1\213"+ + "\2\0\1\u011c\1\213\1\0\4\213\1\0\1\213\1\0"+ + "\1\u0126\1\0\2\213\1\u0127\3\213\1\0\54\213\2\220"+ + "\1\0\101\220\1\0\1\220\1\u0128\14\220\1\u0129\2\220"+ + "\1\u012a\57\220\1\0\16\220\1\u012b\60\220\2\0\1\u012c"+ + "\77\0\14\233\2\0\10\233\1\u012d\51\233\1\u012d\6\233"+ + "\1\234\6\233\1\0\1\311\1\234\6\233\1\234\1\u012d"+ + "\51\233\1\u012d\16\233\1\0\64\233\12\237\1\0\2\237"+ + "\1\0\10\237\1\u012e\51\237\1\u012e\6\237\1\240\4\237"+ + "\1\0\2\237\1\311\1\240\6\237\1\240\1\u012e\51\237"+ + "\1\u012e\16\237\1\0\64\237\27\0\1\u012f\101\0\1\u0130"+ + "\101\0\1\u0131\101\0\1\u0132\52\0\12\257\1\0\65\257"+ + "\2\0\4\257\1\u0133\5\257\1\0\6\257\1\u0134\2\257"+ + "\1\u0135\53\257\2\0\12\257\1\0\6\257\1\u0136\56\257"+ + "\12\0\1\u0137\20\0\16\u0137\1\0\12\u0137\1\0\3\u0137"+ + "\1\0\2\u0137\2\0\5\u0137\12\0\1\266\6\0\1\266"+ + "\11\0\16\266\1\0\12\266\1\0\3\266\1\0\2\266"+ + "\2\0\5\266\21\0\1\267\72\0\1\u0138\20\0\16\u0138"+ + "\1\0\12\u0138\1\0\3\u0138\1\0\2\u0138\2\0\5\u0138"+ + "\53\0\1\u0139\37\0\1\u013a\20\0\1\u013b\55\0\1\u013c"+ + "\75\0\1\51\1\0\11\51\1\0\5\51\1\u013d\60\51"+ + "\5\0\1\300\2\0\2\51\4\0\1\300\6\0\1\300"+ + "\3\0\16\51\1\0\12\51\1\0\3\51\1\0\3\51"+ + "\1\0\2\51\1\0\1\51\3\0\1\u013e\1\0\3\u013e"+ + "\1\u013f\4\301\1\u013e\1\0\2\u013e\1\u013f\1\301\1\u013e"+ + "\1\0\3\u013e\1\u013f\3\u013e\16\301\1\u013e\12\301\1\u013e"+ + "\3\301\1\u0140\6\301\1\u013e\2\301\2\u013e\17\0\1\u0141"+ + "\15\0\1\u0142\51\0\1\303\10\0\1\303\6\0\1\303"+ + "\54\0\1\51\1\0\3\51\1\304\5\51\1\0\2\51"+ + "\1\304\2\51\1\0\3\51\1\304\54\51\1\u013e\1\0"+ + "\3\u013e\1\u013f\4\305\1\u013e\1\0\2\u013e\1\u013f\1\305"+ + "\1\u013e\1\0\3\u013e\1\u013f\3\u013e\16\305\1\u013e\12\305"+ + "\1\u013e\3\305\1\u0143\6\305\1\u013e\2\305\2\u013e\30\0"+ + "\1\u013b\53\0\1\u0144\114\0\1\312\3\0\1\u013d\65\0"+ + "\1\312\10\0\1\312\6\0\1\312\56\0\1\u0145\105\0"+ + "\4\76\5\0\1\76\11\0\6\76\1\u0146\7\76\1\0"+ + "\10\76\1\u0147\1\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\10\0\4\76\5\0\1\76\11\0\6\76\1\u0147"+ + "\7\76\1\0\10\76\1\u0147\1\76\1\0\3\76\1\0"+ + "\6\76\1\0\2\76\10\0\4\76\5\0\1\76\11\0"+ + "\16\76\1\0\1\76\1\u0148\10\76\1\0\3\76\1\0"+ + "\6\76\1\0\2\76\10\0\4\76\5\0\1\76\11\0"+ + "\16\76\1\0\1\76\1\u0149\10\76\1\0\3\76\1\0"+ + "\6\76\1\0\2\76\2\0\1\113\2\0\1\323\1\113"+ + "\1\303\4\113\1\0\1\113\1\0\1\113\1\303\6\113"+ + "\1\303\54\113\12\333\1\335\2\333\1\0\64\333\14\336"+ + "\1\335\1\0\64\336\1\126\2\0\1\331\1\126\1\303"+ + "\4\126\1\0\1\126\1\0\1\126\1\303\6\126\1\303"+ + "\54\126\6\0\4\342\5\0\1\342\11\0\16\342\1\0"+ + "\12\342\1\0\3\342\1\0\6\342\1\0\2\342\7\0"+ + "\1\343\10\0\1\343\6\0\1\343\62\0\4\345\5\0"+ + "\1\345\11\0\16\345\1\0\12\345\1\0\3\345\1\0"+ + "\6\345\1\0\2\345\2\0\1\146\2\0\1\344\1\146"+ + "\1\312\4\146\1\0\1\146\1\0\1\146\1\312\6\146"+ + "\1\312\55\146\2\0\1\344\1\146\1\303\4\146\1\0"+ + "\1\146\1\0\1\146\1\303\6\146\1\303\55\146\2\0"+ + "\1\344\1\146\1\343\4\146\1\0\1\146\1\0\1\146"+ + "\1\343\6\146\1\343\54\146\31\0\1\u014a\36\0\1\u014a"+ + "\45\0\1\u014b\16\0\1\u014b\67\0\1\u014c\10\0\1\u014c"+ + "\72\0\1\u014d\17\0\1\u014d\105\0\1\u014e\12\0\12\365"+ + "\1\367\2\365\1\0\64\365\1\370\2\371\1\u014f\1\370"+ + "\1\371\4\370\1\371\1\370\1\367\1\166\1\371\6\370"+ + "\1\371\54\370\14\371\1\367\1\0\64\371\1\370\2\371"+ + "\1\u014f\1\370\1\371\4\370\1\371\1\370\1\u0150\1\166"+ + "\1\371\6\370\1\371\54\370\14\0\1\u0151\65\0\14\371"+ + "\1\u0150\1\0\64\371\1\166\2\0\1\364\1\166\1\312"+ + "\4\166\1\0\1\166\1\0\1\166\1\312\6\166\1\312"+ + "\55\166\2\0\1\364\1\166\1\303\4\166\1\0\1\166"+ + "\1\0\1\166\1\303\6\166\1\303\54\166\12\u0103\1\u0105"+ + "\67\u0103\14\u0106\1\u0105\65\u0106\1\174\2\0\1\u0102\1\174"+ + "\1\312\4\174\1\0\1\174\1\0\1\174\1\312\6\174"+ + "\1\312\55\174\2\0\1\u0102\1\174\1\303\4\174\1\0"+ + "\1\174\1\0\1\174\1\303\6\174\1\303\54\174\12\u010d"+ + "\1\u010f\2\u010d\1\0\64\u010d\1\u0110\2\u0111\1\u0152\1\u0110"+ + "\1\u0111\4\u0110\1\u0111\1\u0110\1\u010f\1\202\1\u0111\6\u0110"+ + "\1\u0111\54\u0110\14\u0111\1\u010f\1\0\64\u0111\1\u0110\2\u0111"+ + "\1\u0152\1\u0110\1\u0111\4\u0110\1\u0111\1\u0110\1\u0153\1\202"+ + "\1\u0111\6\u0110\1\u0111\54\u0110\14\0\1\u0154\65\0\14\u0111"+ + "\1\u0153\1\0\64\u0111\1\202\2\0\1\u010c\1\202\1\312"+ + "\4\202\1\0\1\202\1\0\1\202\1\312\6\202\1\312"+ + "\55\202\2\0\1\u010c\1\202\1\303\4\202\1\0\1\202"+ + "\1\0\1\202\1\303\6\202\1\303\54\202\2\207\1\0"+ + "\46\207\1\u0155\32\207\1\0\25\207\1\u0156\53\207\1\0"+ + "\2\207\1\u011b\10\207\1\u011b\6\207\1\u011b\54\207\12\u011d"+ + "\1\u011f\2\u011d\1\0\64\u011d\1\u0120\2\u0121\1\u0157\1\u0120"+ + "\1\u0121\4\u0120\1\u0121\1\u0120\1\u011f\1\213\1\u0121\6\u0120"+ + "\1\u0121\54\u0120\14\u0121\1\u011f\1\0\64\u0121\1\u0120\2\u0121"+ + "\1\u0157\1\u0120\1\u0121\4\u0120\1\u0121\1\u0120\1\u0158\1\213"+ + "\1\u0121\6\u0120\1\u0121\54\u0120\14\0\1\u0159\65\0\14\u0121"+ + "\1\u0158\1\0\64\u0121\1\213\2\0\1\u011c\1\213\1\312"+ + "\4\213\1\0\1\213\1\0\1\213\1\312\6\213\1\312"+ + "\55\213\2\0\1\u011c\1\213\1\303\4\213\1\0\1\213"+ + "\1\0\1\213\1\303\6\213\1\303\54\213\2\220\1\0"+ + "\46\220\1\u015a\32\220\1\0\25\220\1\u015b\53\220\1\0"+ + "\2\220\1\u012b\10\220\1\u012b\6\220\1\u012b\54\220\12\257"+ + "\1\0\36\257\1\u015c\26\257\2\0\12\257\1\0\15\257"+ + "\1\u015d\47\257\2\0\5\257\1\u0136\4\257\1\0\3\257"+ + "\1\u0136\6\257\1\u0136\52\257\12\0\1\u0137\6\0\1\u0137"+ + "\10\0\1\u015e\16\u0137\1\0\12\u0137\1\0\3\u0137\1\0"+ + "\2\u0137\2\0\5\u0137\12\0\1\u0138\6\0\1\u0138\11\0"+ + "\16\u0138\1\0\12\u0138\1\0\3\u0138\1\0\2\u0138\2\0"+ + "\5\u0138\75\0\2\u015f\14\0\1\u0160\123\0\1\u0161\121\0"+ + "\1\u0162\35\0\1\u013d\10\0\1\u013d\6\0\1\u013d\54\0"+ + "\1\u013e\1\0\11\u013e\1\0\5\u013e\1\0\44\u013e\1\0"+ + "\14\u013e\1\0\3\u013e\1\u013f\5\u013e\1\0\2\u013e\1\u013f"+ + "\2\u013e\1\0\3\u013e\1\u013f\40\u013e\1\u0163\13\u013e\17\0"+ + "\1\u0141\46\0\1\u0164\32\0\1\u0165\11\0\3\u0165\5\0"+ + "\1\u0165\10\0\1\u0165\1\0\2\u0165\6\0\1\u0165\2\0"+ + "\2\u0165\17\0\1\76\1\u0166\2\76\5\0\1\76\11\0"+ + "\16\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\10\0\4\76\5\0\1\76\11\0\14\76\1\u0167"+ + "\1\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\36\0\1\u0168\16\0\1\u0168\65\0\1\u0169\20\0"+ + "\1\u0169\57\0\1\u016a\22\0\1\u016a\54\0\1\u016b\16\0"+ + "\1\u016b\65\0\1\u016c\20\0\1\u016c\24\0\2\u016d\1\0"+ + "\4\u016d\2\0\1\374\1\0\4\u016d\1\0\4\u016d\2\0"+ + "\31\u016d\1\0\6\u016d\2\0\2\u016d\3\0\1\u016d\4\0"+ + "\2\u016e\1\0\4\u016e\2\0\1\u0114\1\0\4\u016e\1\0"+ + "\4\u016e\2\0\31\u016e\1\0\6\u016e\2\0\2\u016e\3\0"+ + "\1\u016e\1\0\2\207\1\0\70\207\2\u016f\7\207\1\0"+ + "\26\207\1\u0170\50\207\3\0\2\u0171\1\0\4\u0171\2\0"+ + "\1\u0124\1\0\4\u0171\1\0\4\u0171\2\0\31\u0171\1\0"+ + "\6\u0171\2\0\2\u0171\3\0\1\u0171\1\0\2\220\1\0"+ + "\70\220\2\u0172\7\220\1\0\26\220\1\u0173\50\220\12\257"+ + "\1\0\60\257\2\u0174\3\257\2\0\12\257\1\0\16\257"+ + "\1\u0175\46\257\12\0\1\u0176\6\0\1\u0177\11\0\16\u0176"+ + "\1\0\12\u0176\1\0\3\u0176\1\0\2\u0176\2\0\5\u0176"+ + "\53\0\1\u0178\10\0\1\u0178\51\0\1\u0179\142\0\2\u017a"+ + "\73\0\1\u0163\32\0\1\u0165\11\0\3\u0165\5\0\1\u0165"+ + "\10\0\1\u0165\1\0\2\u0165\6\0\1\u0165\1\0\1\u0164"+ + "\2\u0165\17\0\4\76\5\0\1\76\11\0\12\76\1\u017b"+ + "\3\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\10\0\4\76\5\0\1\76\11\0\11\76\1\u017c"+ + "\4\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\52\0\1\u017d\5\0\1\u017d\67\0\1\u017e\76\0"+ + "\1\u017f\10\0\1\u017f\70\0\1\u0180\10\0\1\u0180\73\0"+ + "\1\u0181\35\0\2\207\1\0\46\207\1\u0182\10\207\1\u0182"+ + "\21\207\1\0\27\207\1\u0183\47\207\2\220\1\0\46\220"+ + "\1\u0184\10\220\1\u0184\21\220\1\0\27\220\1\u0185\47\220"+ + "\12\257\1\0\36\257\1\u0186\10\257\1\u0186\15\257\2\0"+ + "\12\257\1\0\17\257\1\u0187\45\257\12\0\1\u0176\6\0"+ + "\1\u0176\2\0\1\u0188\6\0\16\u0176\1\0\12\u0176\1\0"+ + "\3\u0176\1\0\2\u0176\2\0\5\u0176\21\0\1\u0177\2\0"+ + "\1\u0189\64\0\1\u0178\10\0\1\u0178\6\0\1\u0178\107\0"+ + "\1\u018a\117\0\1\u018b\10\0\1\u018b\25\0\4\76\5\0"+ + "\1\76\11\0\16\76\1\0\3\76\1\u018c\6\76\1\0"+ + "\3\76\1\0\6\76\1\0\2\76\10\0\4\76\5\0"+ + "\1\76\11\0\3\76\1\u018d\12\76\1\0\3\76\1\u018d"+ + "\6\76\1\0\3\76\1\0\6\76\1\0\2\76\53\0"+ + "\1\u018e\73\0\1\u018f\17\0\1\u018f\64\0\1\u0190\71\0"+ + "\1\u0191\22\0\1\u0191\51\0\1\u0192\36\0\1\u0192\11\0"+ + "\2\207\1\0\2\207\1\u0182\10\207\1\u0182\6\207\1\u0182"+ + "\56\207\1\0\30\207\1\u0193\46\207\2\220\1\0\2\220"+ + "\1\u0184\10\220\1\u0184\6\220\1\u0184\56\220\1\0\30\220"+ + "\1\u0194\46\220\5\257\1\u0186\4\257\1\0\3\257\1\u0186"+ + "\6\257\1\u0186\52\257\2\0\12\257\1\0\20\257\1\u0195"+ + "\44\257\36\0\1\u0196\52\0\1\u018b\10\0\1\u018b\6\0"+ + "\1\u018b\62\0\4\76\5\0\1\76\11\0\16\76\1\0"+ + "\6\76\1\u0197\3\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\43\0\1\u0198\10\0\1\u0198\63\0\1\u0199\16\0"+ + "\1\u0199\62\0\1\u019a\16\0\1\u019a\26\0\2\207\1\0"+ + "\31\207\1\u019b\45\207\2\220\1\0\31\220\1\u019c\45\220"+ + "\12\257\1\0\21\257\1\u019d\43\257\35\0\1\u019e\54\0"+ + "\4\76\5\0\1\76\11\0\6\76\1\u019f\7\76\1\0"+ + "\12\76\1\0\3\76\1\0\6\76\1\0\2\76\2\0"+ + "\2\207\1\0\30\207\1\u01a0\46\207\2\220\1\0\30\220"+ + "\1\u01a1\46\220\12\257\1\0\20\257\1\u01a2\44\257\32\0"+ + "\1\u01a3\57\0\4\76\5\0\1\76\11\0\10\76\1\u01a4"+ + "\5\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\2\0\2\207\1\0\25\207\1\u01a5\51\207\2\220"+ + "\1\0\25\220\1\u01a6\51\220\12\257\1\0\15\257\1\u01a7"+ + "\47\257\10\0\4\76\5\0\1\76\11\0\12\76\1\u01a8"+ + "\3\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\10\0\4\76\5\0\1\76\11\0\16\76\1\0"+ + "\12\76\1\0\3\76\1\0\4\76\1\u01a9\1\76\1\0"+ + "\2\76\10\0\4\76\5\0\1\76\11\0\10\76\1\u01aa"+ + "\5\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\10\0\4\76\5\0\1\76\11\0\10\76\1\u01ab"+ + "\5\76\1\0\12\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\10\0\4\76\5\0\1\76\11\0\16\76\1\0"+ + "\3\76\1\u01ac\6\76\1\0\3\76\1\0\6\76\1\0"+ + "\2\76\2\0"; /** * The transition table of the DFA @@ -582,32 +619,33 @@ public class TwigTokenizer implements BlockTokenizer, PHPRegionContext, DOMRegio * YY_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private final static byte YY_ATTRIBUTE[] = { - 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, + 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 9, 1, 1, 1, 1, 1, 1, 1, - 9, 1, 1, 1, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 9, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 9, 1, - 1, 9, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, 9, - 1, 1, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 9, 1, + 1, 9, 1, 1, 1, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 9, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, + 1, 9, 1, 1, 9, 1, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, + 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, 9, 9, 1, 9, 1, - 1, 1, 1, 9, 1, 1, 1, 9, 1, 9, 1, 1, 1, 1, 9, 1, - 1, 1, 1, 9, 1, 9, 9, 1, 1, 1, 9, 9, 1, 9, 1, 0, - 0, 0, 0, 1, 0, 1, 9, 1, 1, 1, 0, 0, 0, 9, 1, 1, - 1, 1, 9, 9, 0, 0, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, - 9, 1, 0, 1, 0, 9, 0, 1, 1, 0, 0, 0, 0, 0, 9, 0, - 0, 0, 0, 0, 9, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, - 0, 9, 0, 0, 1, 0, 1, 0, 0, 0, 9, 1, 0, 0, 1, 1, - 0, 1, 1, 1, 1, 0, 0, 0, 9, 1, 0, 0, 1, 1, 0, 1, - 1, 1, 1, 9, 0, 0, 9, 9, 9, 9, 1, 1, 1, 1, 1, 0, - 0, 0, 0, 1, 1, 9, 0, 0, 9, 9, 9, 1, 1, 1, 1, 0, - 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, - 1, 1, 1, 0, 0, 9, 0, 0, 1, 9, 0, 1, 1, 0, 0, 0, - 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, - 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 9, 9, 0, - 1, 1, 1, 0, 0, 0, 9, 9, 1, 1, 1, 0, 1, 9, 9, 9, - 1, 1, 1, 0, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, - 1, 1 + 1, 1, 1, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, + 1, 9, 1, 9, 1, 1, 9, 1, 1, 1, 1, 1, 9, 1, 1, 1, + 9, 1, 1, 1, 9, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, + 9, 1, 1, 9, 9, 1, 1, 1, 9, 9, 1, 9, 1, 0, 1, 0, + 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 9, 1, 1, 1, 1, + 9, 9, 0, 0, 9, 0, 1, 0, 0, 0, 0, 0, 9, 0, 0, 1, + 9, 1, 1, 0, 1, 0, 9, 0, 1, 1, 1, 0, 0, 0, 0, 0, + 9, 0, 0, 0, 0, 0, 9, 1, 0, 0, 1, 1, 0, 1, 1, 0, + 1, 0, 0, 0, 9, 0, 0, 1, 1, 0, 1, 0, 0, 0, 9, 1, + 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 9, 1, + 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 9, 0, 0, 9, 9, + 9, 9, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 9, + 0, 0, 9, 9, 9, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, + 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 9, + 0, 0, 1, 9, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, + 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 9, 9, 0, 1, 1, 1, 0, 0, 0, + 9, 9, 1, 1, 1, 0, 1, 9, 9, 9, 1, 1, 1, 0, 1, 1, + 1, 1, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; /** the input device */ @@ -1423,14 +1461,14 @@ else if (fBufferedContext == XML_END_TAG_OPEN) { // if it is twig content we create a twig script region if ((context == TWIG_CONTENT)) { - if (Debug.debugTokenizer) - System.err.println("create twig region " + context); +// if (Debug.debugTokenizer) +// System.err.println("create twig region " + context); return bufferedTextRegion; } else { - if (Debug.debugTokenizer) - System.err.println("create standard region " + context); +// if (Debug.debugTokenizer) +// System.err.println("create standard region " + context); return fRegionFactory.createToken(context, start, textLength, length, null, fCurrentTagName); } @@ -1605,10 +1643,10 @@ public TwigTokenizer(java.io.InputStream in) { * @return the unpacked transition table */ private static int [] yy_unpack(String packed) { - int [] trans = new int[18348]; + int [] trans = new int[19800]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ - while (i < 5312) { + while (i < 5860) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; @@ -2003,7 +2041,31 @@ public String primGetNextToken() throws java.io.IOException { switch (yy_action) { - case 401: + case 0: + case 40: + case 42: + case 44: + case 190: + case 192: + case 196: + case 317: + case 318: + case 354: + { +//<YYINITIAL> [^<&%]*|[&%]{S}+{Name}[^&%<]*|[&%]{Name}([^;&%<]*|{S}+;*) { + + if(Debug.debugTokenizer) + dump("\nXML content");//$NON-NLS-1$ + + final String text = yytext(); + assert text != null; + + // checks the smarty case + return findTwigDelimiter(text, XML_CONTENT, twigLeftDelim, TWIG_OPEN, ST_TWIG_CONTENT); + + } + case 429: break; + case 427: { if(Debug.debugTokenizer) dump("XSL processing instruction target");//$NON-NLS-1$ @@ -2011,11 +2073,11 @@ public String primGetNextToken() throws java.io.IOException { yybegin(ST_XML_PI_ATTRIBUTE_NAME); return XML_TAG_NAME; } - case 403: break; - case 392: - case 394: - case 395: - case 396: + case 430: break; + case 418: + case 420: + case 421: + case 422: { if(Debug.debugTokenizer) dump("\nCDATA start");//$NON-NLS-1$ @@ -2023,48 +2085,48 @@ public String primGetNextToken() throws java.io.IOException { yybegin(ST_CDATA_TEXT); return XML_CDATA_OPEN; } - case 404: break; - case 383: + case 431: break; + case 409: { if(Debug.debugTokenizer) dump("element");//$NON-NLS-1$ yybegin(ST_XML_ELEMENT_DECLARATION); return XML_ELEMENT_DECLARATION; } - case 405: break; - case 382: + case 432: break; + case 408: { if(Debug.debugTokenizer) dump("attlist");//$NON-NLS-1$ yybegin(ST_XML_ATTLIST_DECLARATION); return XML_ATTLIST_DECLARATION; } - case 406: break; - case 381: + case 433: break; + case 407: { if(Debug.debugTokenizer) dump("doctype");//$NON-NLS-1$ yybegin(ST_XML_DOCTYPE_DECLARATION); return XML_DOCTYPE_DECLARATION; } - case 407: break; - case 375: + case 434: break; + case 401: { if(Debug.debugTokenizer) dump("doctype external id");//$NON-NLS-1$ yybegin(ST_XML_DOCTYPE_ID_PUBLIC); return XML_DOCTYPE_EXTERNAL_ID_PUBLIC; } - case 408: break; - case 374: + case 435: break; + case 400: { if(Debug.debugTokenizer) dump("doctype external id");//$NON-NLS-1$ yybegin(ST_XML_DOCTYPE_ID_SYSTEM); return XML_DOCTYPE_EXTERNAL_ID_SYSTEM; } - case 409: break; - case 370: + case 436: break; + case 396: { if(Debug.debugTokenizer) dump("DHTML processing instruction target");//$NON-NLS-1$ @@ -2073,8 +2135,8 @@ public String primGetNextToken() throws java.io.IOException { yybegin(ST_DHTML_ATTRIBUTE_NAME); return XML_TAG_NAME; } - case 410: break; - case 368: + case 437: break; + case 394: { if (Debug.debugTokenizer) { @@ -2130,8 +2192,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } - case 411: break; - case 366: + case 438: break; + case 392: { if (Debug.debugTokenizer) @@ -2139,8 +2201,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return TWIG_VARIABLE; } - case 412: break; - case 365: + case 439: break; + case 391: { if (Debug.debugTokenizer) @@ -2148,15 +2210,15 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return TWIG_VARIABLE; } - case 413: break; - case 329: + case 440: break; + case 355: { if(Debug.debugTokenizer) dump("\nCharRef");//$NON-NLS-1$ return XML_CHAR_REFERENCE; } - case 414: break; - case 325: + case 441: break; + case 351: { if(Debug.debugTokenizer) dump("\ncomment start");//$NON-NLS-1$ @@ -2165,8 +2227,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_XML_COMMENT); return XML_COMMENT_OPEN; } - case 415: break; - case 302: + case 442: break; + case 328: { if(Debug.debugTokenizer) dump("PHP processing instruction target");//$NON-NLS-1$ @@ -2177,9 +2239,9 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_PHP_CONTENT); return PHP_OPEN; } - case 416: break; - case 299: - case 300: + case 443: break; + case 325: + case 326: { if(Debug.debugTokenizer) dump("XML processing instruction target");//$NON-NLS-1$ @@ -2188,8 +2250,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_XML_PI_ATTRIBUTE_NAME); return XML_TAG_NAME; } - case 417: break; - case 298: + case 444: break; + case 324: { if(Debug.debugTokenizer) dump("comment end");//$NON-NLS-1$ @@ -2197,23 +2259,30 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(YYINITIAL); return XML_COMMENT_CLOSE; } - case 418: break; - case 297: + case 445: break; + case 323: { if(Debug.debugTokenizer) dump("CDATA end");//$NON-NLS-1$ yybegin(fStateStack.pop()); return XML_CDATA_CLOSE; } - case 419: break; - case 296: + case 446: break; + case 322: { if(Debug.debugTokenizer) dump("\nPEReference");//$NON-NLS-1$ return XML_PE_REFERENCE; } - case 420: break; - case 139: + case 447: break; + case 319: + { + if(Debug.debugTokenizer) + dump("\nEntityRef");//$NON-NLS-1$ + return XML_ENTITY_REFERENCE; + } + case 448: break; + case 145: { if(Debug.debugTokenizer) dump("attlist close");//$NON-NLS-1$ @@ -2224,25 +2293,25 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } - case 421: break; - case 132: - case 134: - case 135: - case 136: - case 264: - case 265: - case 268: - case 269: - case 271: - case 317: + case 449: break; + case 138: + case 140: + case 141: + case 142: + case 286: + case 287: + case 290: + case 291: + case 293: + case 343: { if(Debug.debugTokenizer) dump("attlist name");//$NON-NLS-1$ yybegin(ST_XML_ATTLIST_DECLARATION_CONTENT); return XML_ATTLIST_DECL_NAME; } - case 422: break; - case 131: + case 450: break; + case 136: { if(Debug.debugTokenizer) dump("elementdecl close");//$NON-NLS-1$ @@ -2253,65 +2322,65 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } - case 423: break; - case 124: - case 126: - case 127: - case 128: - case 250: - case 251: - case 254: - case 255: - case 257: - case 312: + case 451: break; + case 129: + case 131: + case 132: + case 133: + case 270: + case 271: + case 274: + case 275: + case 277: + case 338: { if(Debug.debugTokenizer) dump("elementdecl name");//$NON-NLS-1$ yybegin(ST_XML_ELEMENT_DECLARATION_CONTENT); return XML_ELEMENT_DECL_NAME; } - case 424: break; - case 118: - case 120: - case 121: - case 122: + case 452: break; case 123: - case 241: - case 244: + case 125: + case 126: + case 127: + case 128: + case 260: + case 263: { if(Debug.debugTokenizer) dump("doctype system reference");//$NON-NLS-1$ yybegin(ST_XML_DECLARATION_CLOSE); return XML_DOCTYPE_EXTERNAL_ID_SYSREF; } - case 425: break; - case 112: - case 114: - case 115: - case 116: + case 453: break; case 117: - case 228: - case 229: - case 232: - case 233: - case 235: - case 309: + case 119: + case 120: + case 121: + case 122: + case 246: + case 247: + case 250: + case 251: + case 253: + case 335: { if(Debug.debugTokenizer) dump("doctype public reference");//$NON-NLS-1$ yybegin(ST_XML_DOCTYPE_ID_SYSTEM); return XML_DOCTYPE_EXTERNAL_ID_PUBREF; } - case 426: break; - case 109: + case 454: break; + case 114: { if(Debug.debugTokenizer) dump("doctype type");//$NON-NLS-1$ yybegin(ST_XML_DOCTYPE_EXTERNAL_ID); return XML_DOCTYPE_NAME; } - case 427: break; - case 103: + case 455: break; + case 108: { if(Debug.debugTokenizer) dump("declaration end");//$NON-NLS-1$ @@ -2322,8 +2391,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } - case 428: break; - case 100: + case 456: break; + case 105: { // begin embedded region: " + fEmbeddedHint fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; @@ -2343,8 +2412,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return PROXY_CONTEXT; } - case 429: break; - case 99: + case 457: break; + case 104: { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; @@ -2363,12 +2432,13 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return PROXY_CONTEXT; } - case 430: break; - case 96: + case 458: break; case 101: - case 213: - case 215: - case 216: + case 106: + case 230: + case 232: + case 233: + case 234: { // attr value @@ -2383,8 +2453,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_ATTRIBUTE_VALUE; } - case 431: break; - case 95: + case 459: break; + case 100: { // equals fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; @@ -2397,8 +2467,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_ATTRIBUTE_EQUALS; } - case 432: break; - case 94: + case 460: break; + case 98: { // attr name fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; @@ -2412,9 +2482,9 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_ATTRIBUTE_NAME; } - case 433: break; - case 90: - case 91: + case 461: break; + case 94: + case 95: { if(Debug.debugTokenizer) dump("TAG NAME");//$NON-NLS-1$ @@ -2428,8 +2498,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_NAME; } - case 434: break; - case 87: + case 462: break; + case 91: { // tag close fEmbeddedHint = UNDEFINED; @@ -2446,8 +2516,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_CLOSE; } - case 435: break; - case 81: + case 463: break; + case 84: { if(Debug.debugTokenizer) dump("DHTML processing instruction '='");//$NON-NLS-1$ @@ -2456,117 +2526,123 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_DHTML_ATTRIBUTE_VALUE); return XML_TAG_ATTRIBUTE_EQUALS; } - case 436: break; - case 80: + case 464: break; + case 83: { if(Debug.debugTokenizer) dump("DHTML processing instruction attribute name");//$NON-NLS-1$ yybegin(ST_DHTML_EQUALS); return XML_TAG_ATTRIBUTE_NAME; } - case 437: break; - case 47: - case 52: - { - if(Debug.debugTokenizer) - dump("LINE FEED");//$NON-NLS-1$ - return WHITE_SPACE; - } - case 438: break; - case 41: - case 92: - case 97: - case 102: + case 465: break; + case 81: { if(Debug.debugTokenizer) - dump("\nstart tag open");//$NON-NLS-1$ - fEmbeddedHint = XML_TAG_NAME; - fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; - yybegin(ST_XML_TAG_NAME); - return XML_TAG_OPEN; + dump("DHTML processing instruction end");//$NON-NLS-1$ + fEmbeddedHint = UNDEFINED; + yybegin(YYINITIAL); + return XML_PI_CLOSE; } - case 439: break; - case 40: - case 42: + case 466: break; case 43: - case 44: case 45: - case 46: + case 49: case 50: case 51: - case 57: + case 52: case 58: - case 69: - case 73: + case 59: + case 71: case 75: - case 76: case 77: - case 79: - case 83: - case 88: - case 98: - case 104: - case 105: - case 106: - case 107: - case 108: + case 78: + case 80: + case 82: + case 86: + case 92: + case 99: + case 103: + case 109: case 110: case 111: + case 112: case 113: - case 119: - case 125: - case 133: - case 148: - case 152: - case 160: - case 164: - case 169: + case 115: + case 116: + case 118: + case 124: + case 130: + case 139: + case 157: + case 161: + case 162: + case 173: + case 178: + case 183: { - if (Debug.debugTokenizer) + if (Debug.debugTokenizer) { + System.out.println("current state " + yy_state); System.out.println("!!!unexpected!!!: \"" + yytext() + "\":" + //$NON-NLS-2$//$NON-NLS-1$ + yychar + "-" + (yychar + yylength()));//$NON-NLS-1$ + } return UNDEFINED; } - case 440: break; + case 467: break; + case 41: + case 96: + case 102: + case 107: + { + if(Debug.debugTokenizer) + dump("\nstart tag open");//$NON-NLS-1$ + fEmbeddedHint = XML_TAG_NAME; + fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; + yybegin(ST_XML_TAG_NAME); + return XML_TAG_OPEN; + } + case 468: break; case 29: - case 137: - case 138: - case 274: - case 319: - case 320: - case 343: - case 344: - case 362: - case 377: - case 385: - case 390: + case 143: + case 144: + case 146: + case 297: + case 345: + case 346: + case 369: + case 370: + case 388: + case 403: + case 411: + case 416: { if(Debug.debugTokenizer) dump("attlist contentspec");//$NON-NLS-1$ return XML_ATTLIST_DECL_CONTENT; } - case 441: break; + case 469: break; case 27: - case 129: - case 130: - case 260: - case 314: - case 315: + case 134: + case 135: + case 137: + case 281: case 340: case 341: - case 360: - case 376: - case 384: - case 389: + case 366: + case 367: + case 386: + case 402: + case 410: + case 415: { if(Debug.debugTokenizer) dump("elementdecl contentspec");//$NON-NLS-1$ return XML_ELEMENT_DECL_CONTENT; } - case 442: break; + case 470: break; case 16: - case 86: - case 89: + case 90: + case 93: { // inappropriate tag name if(!fStateStack.empty() && (fStateStack.peek()==ST_XML_ATTRIBUTE_VALUE_SQUOTED||fStateStack.peek()==ST_XML_ATTRIBUTE_VALUE_DQUOTED)) { @@ -2583,12 +2659,13 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_CONTENT; } - case 443: break; + case 471: break; case 14: - case 82: - case 84: case 85: - case 205: + case 87: + case 88: + case 89: + case 220: { if(Debug.debugTokenizer) dump("DHTML processing instruction attribute value");//$NON-NLS-1$ @@ -2597,7 +2674,7 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_DHTML_ATTRIBUTE_NAME); return XML_TAG_ATTRIBUTE_VALUE; } - case 444: break; + case 472: break; case 5: case 8: case 9: @@ -2613,16 +2690,17 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { case 25: case 26: case 28: - case 59: - case 93: + case 60: + case 97: { if(Debug.debugTokenizer) dump("WHITE SPACE");//$NON-NLS-1$ return WHITE_SPACE; } - case 445: break; + case 473: break; + case 46: + case 47: case 48: - case 49: { if(Debug.debugTokenizer) dump("CDATA text");//$NON-NLS-1$ @@ -2633,39 +2711,47 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_CDATA_END); return blockContext; } - case 446: break; + case 474: break; case 53: + case 163: + { + if(Debug.debugTokenizer) + dump("LINE FEED");//$NON-NLS-1$ + return WHITE_SPACE; + } + case 475: break; case 54: case 55: case 56: + case 57: { if(Debug.debugTokenizer) dump("comment content");//$NON-NLS-1$ return scanXMLCommentText(); } - case 447: break; - case 60: + case 476: break; case 61: case 62: case 63: case 64: - case 190: - case 191: - case 192: - case 193: - case 301: - case 331: - case 332: - case 352: - case 353: - case 369: - case 380: - case 388: - case 393: - case 397: - case 398: - case 399: - case 400: + case 65: + case 204: + case 205: + case 206: + case 207: + case 327: + case 357: + case 358: + case 378: + case 379: + case 395: + case 406: + case 414: + case 419: + case 423: + case 424: + case 425: + case 426: { if(Debug.debugTokenizer) dump("processing instruction target");//$NON-NLS-1$ @@ -2673,8 +2759,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_PI_WS); return XML_TAG_NAME; } - case 448: break; - case 65: + case 477: break; + case 66: { if (Debug.debugTokenizer) { @@ -2684,10 +2770,11 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_PI_CONTENT); return WHITE_SPACE; } - case 449: break; - case 66: + case 478: break; case 67: case 68: + case 69: + case 70: { // block scan until close is found @@ -2697,16 +2784,16 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return doScan("?>", false, false, XML_PI_CONTENT, ST_XML_PI_TAG_CLOSE, ST_XML_PI_TAG_CLOSE); } - case 450: break; - case 70: + case 479: break; + case 72: { if(Debug.debugTokenizer) dump("XML processing instruction attribute name");//$NON-NLS-1$ yybegin(ST_XML_PI_EQUALS); return XML_TAG_ATTRIBUTE_NAME; } - case 451: break; - case 71: + case 480: break; + case 73: { if(Debug.debugTokenizer) dump("XML processing instruction '='");//$NON-NLS-1$ @@ -2715,10 +2802,11 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_XML_PI_ATTRIBUTE_VALUE); return XML_TAG_ATTRIBUTE_EQUALS; } - case 452: break; - case 72: + case 481: break; case 74: - case 198: + case 76: + case 79: + case 212: { if(Debug.debugTokenizer) dump("XML processing instruction attribute value");//$NON-NLS-1$ @@ -2727,19 +2815,11 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_XML_PI_ATTRIBUTE_NAME); return XML_TAG_ATTRIBUTE_VALUE; } - case 453: break; - case 78: - { - if(Debug.debugTokenizer) - dump("DHTML processing instruction end");//$NON-NLS-1$ - fEmbeddedHint = UNDEFINED; - yybegin(YYINITIAL); - return XML_PI_CLOSE; - } - case 454: break; - case 142: - case 143: - case 144: + case 482: break; + case 150: + case 151: + case 152: + case 153: { if (Debug.debugTokenizer) { @@ -2748,9 +2828,9 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return doScanEndPhp(ProjectOptions.isSupportingAspTags(project), PHP_CONTENT, ST_PHP_CONTENT, ST_PHP_CONTENT); } - case 455: break; - case 145: - case 146: + case 483: break; + case 154: + case 155: { if (Debug.debugTokenizer) { @@ -2759,8 +2839,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_ATTRIBUTE_VALUE; } - case 456: break; - case 147: + case 484: break; + case 156: { if (Debug.debugTokenizer) { @@ -2769,9 +2849,9 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_ATTRIBUTE_VALUE_SQUOTE; } - case 457: break; - case 149: - case 150: + case 485: break; + case 158: + case 159: { if (Debug.debugTokenizer) { @@ -2780,8 +2860,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_ATTRIBUTE_VALUE; } - case 458: break; - case 151: + case 486: break; + case 160: { if (Debug.debugTokenizer) { @@ -2790,20 +2870,22 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_TAG_ATTRIBUTE_VALUE_DQUOTE; } - case 459: break; - case 153: - case 154: - case 155: - case 156: - case 157: + case 487: break; + case 164: + case 165: + case 166: + case 167: + case 168: + case 169: { return doScanEndTwig(TWIG_CONTENT, ST_TWIG_CONTENT, ST_TWIG_CONTENT); } - case 460: break; - case 158: - case 159: + case 488: break; + case 170: + case 171: + case 172: { if(Debug.debugTokenizer) @@ -2812,18 +2894,19 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { String ret = scanTwigCommentText(); return ret; } - case 461: break; - case 161: - case 162: - case 284: - case 321: - case 322: - case 345: - case 346: - case 364: - case 378: - case 386: - case 391: + case 489: break; + case 174: + case 175: + case 177: + case 308: + case 347: + case 348: + case 371: + case 372: + case 390: + case 404: + case 412: + case 417: { if(Debug.debugTokenizer) @@ -2831,8 +2914,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return TWIG_DOUBLE_QUOTES_CONTENT; } - case 462: break; - case 163: + case 490: break; + case 176: { if(Debug.debugTokenizer) @@ -2841,40 +2924,40 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_TWIG_CONTENT); return TWIG_DOUBLE_QUOTES_END; } - case 463: break; - case 165: + case 491: break; + case 179: { yybegin(ST_TWIG_DOUBLE_QUOTES_SPECIAL); return TWIG_BACKTICK_START; } - case 464: break; - case 166: + case 492: break; + case 180: { return TWIG_DELIMITER; } - case 465: break; - case 167: + case 493: break; + case 181: { return TWIG_LABEL; } - case 466: break; - case 168: + case 494: break; + case 182: { return TWIG_NUMBER; } - case 467: break; - case 170: + case 495: break; + case 184: { yybegin(ST_TWIG_DOUBLE_QUOTES); return TWIG_BACKTICK_END; } - case 468: break; - case 171: + case 496: break; + case 185: { // end tag open fEmbeddedHint = XML_TAG_NAME; @@ -2887,19 +2970,19 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_END_TAG_OPEN; } - case 469: break; - case 172: - case 173: - case 258: - case 259: - case 272: - case 273: - case 282: - case 283: - case 349: - case 359: - case 361: - case 363: + case 497: break; + case 186: + case 187: + case 279: + case 280: + case 295: + case 296: + case 306: + case 307: + case 375: + case 385: + case 387: + case 389: { if(Debug.debugTokenizer) dump("\nprocessing instruction start");//$NON-NLS-1$ @@ -2953,8 +3036,8 @@ else if (yystate() == ST_CDATA_TEXT) { } } - case 470: break; - case 174: + case 498: break; + case 188: { fStateStack.push(yystate()); if(Debug.debugTokenizer) @@ -2962,23 +3045,40 @@ else if (yystate() == ST_CDATA_TEXT) { yybegin(ST_XML_DECLARATION); return XML_DECLARATION_OPEN; } - case 471: break; - case 179: - case 184: - case 185: - case 291: - case 292: - case 328: + case 499: break; + case 194: + case 214: + case 223: + case 254: + case 264: + case 278: + case 282: + case 294: + case 298: + case 309: { - if(Debug.debugTokenizer) - dump("\nXML content");//$NON-NLS-1$ - + if (Debug.debugTokenizer) { + dump("############# tw stmt 2"); + } return XML_CONTENT; } - case 472: break; - case 181: + case 500: break; + case 195: + case 226: + { + + if(Debug.debugTokenizer) + dump("twig comment start");//$NON-NLS-1$ + fEmbeddedHint = TWIG_COMMENT_TEXT; + fEmbeddedPostState = ST_TWIG_COMMENT; + yybegin(ST_TWIG_COMMENT); + return TWIG_COMMENT_OPEN; + + } + case 501: break; + case 201: { if (Debug.debugTokenizer) { @@ -3029,33 +3129,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return PROXY_CONTEXT; } } - case 473: break; - case 182: - { - - yybegin(ST_TWIG_CONTENT); - - if (Debug.debugTokenizer) { - dump("ST_TWIG_CONTENT"); - } - - return TWIG_STMT_OPEN; - - } - case 474: break; - case 183: - { - - if(Debug.debugTokenizer) - dump("twig comment start");//$NON-NLS-1$ - fEmbeddedHint = TWIG_COMMENT_TEXT; - fEmbeddedPostState = ST_TWIG_COMMENT; - yybegin(ST_TWIG_COMMENT); - return TWIG_COMMENT_OPEN; - - } - case 475: break; - case 189: + case 502: break; + case 203: { if(Debug.debugTokenizer) dump("processing instruction end");//$NON-NLS-1$ @@ -3063,8 +3138,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(YYINITIAL); return XML_PI_CLOSE; } - case 476: break; - case 194: + case 503: break; + case 208: { // ended with nothing inside fEmbeddedHint = UNDEFINED; @@ -3077,8 +3152,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return XML_PI_CLOSE; } - case 477: break; - case 195: + case 504: break; + case 209: { if(Debug.debugTokenizer) dump("XML processing instruction end");//$NON-NLS-1$ @@ -3086,8 +3161,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(YYINITIAL); return XML_PI_CLOSE; } - case 478: break; - case 208: + case 505: break; + case 224: { yybegin(YYINITIAL); fEmbeddedHint = UNDEFINED; @@ -3099,8 +3174,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { // empty tag close return XML_EMPTY_TAG_CLOSE; } - case 479: break; - case 209: + case 506: break; + case 225: { String tagName = yytext().substring(1); // pushback to just after the opening bracket @@ -3125,8 +3200,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_XML_EQUALS); return PROXY_CONTEXT; } - case 480: break; - case 211: + case 507: break; + case 228: { String tagName = yytext().substring(1); // pushback to just after the opening bracket @@ -3151,15 +3226,15 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(ST_XML_ATTRIBUTE_NAME); return PROXY_CONTEXT; } - case 481: break; - case 222: - case 237: - case 246: + case 508: break; + case 240: + case 256: + case 266: { return XML_DOCTYPE_INTERNAL_SUBSET; } - case 482: break; - case 275: + case 509: break; + case 299: { yybegin(fStateStack.pop()); @@ -3170,8 +3245,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return PHP_CLOSE; } - case 483: break; - case 278: + case 510: break; + case 302: { if(Debug.debugTokenizer) @@ -3180,8 +3255,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(YYINITIAL); return TWIG_STMT_CLOSE; } - case 484: break; - case 279: + case 511: break; + case 303: { @@ -3191,18 +3266,19 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(YYINITIAL); return TWIG_COMMENT_CLOSE; } - case 485: break; - case 280: + case 512: break; + case 304: { if(Debug.debugTokenizer) dump("TWIG CLOSE"); + //yybegin(fStateStack.pop()); yybegin(YYINITIAL); return TWIG_CLOSE; } - case 486: break; - case 281: + case 513: break; + case 305: { if(Debug.debugTokenizer) @@ -3211,8 +3287,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { yybegin(YYINITIAL); return TWIG_COMMENT_CLOSE; } - case 487: break; - case 285: + case 514: break; + case 310: { if (Debug.debugTokenizer) @@ -3220,8 +3296,8 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return TWIG_VARIABLE; } - case 488: break; - case 286: + case 515: break; + case 311: { if (Debug.debugTokenizer) @@ -3229,20 +3305,27 @@ else if(yystate() == ST_XML_ATTRIBUTE_VALUE) { return TWIG_VARIABLE; } - case 489: break; - case 293: + case 516: break; + case 316: { - if(Debug.debugTokenizer) - dump("\nEntityRef");//$NON-NLS-1$ - return XML_ENTITY_REFERENCE; + + yybegin(ST_TWIG_CONTENT); + + if (Debug.debugTokenizer) { + dump("ST_TWIG_CONTENT"); + } + + return TWIG_STMT_OPEN; + } - case 490: break; - case 140: - case 141: + case 517: break; + case 147: + case 148: + case 149: { return doBlockTagScan(); } - case 491: break; + case 518: break; default: if (yy_input == YYEOF && yy_startRead == yy_currentPos) { yy_atEOF = true; diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigRegionTypes.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigRegionTypes.java index c5b6342..6d1b37a 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigRegionTypes.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigRegionTypes.java @@ -4,7 +4,7 @@ public interface TwigRegionTypes { public static final String TWIG_OPEN = "TWIG_OPEN"; //$NON-NLS-1$ - public static final String TWIG_CLOSE = "TWIG_CLOSE"; //$NON-NLS-1$ + public static final String TWIG_CLOSETAG = "TWIG_CLOSETAG"; //$NON-NLS-1$ public static final String TWIG_STMT_OPEN = "TWIG_STMT_OPEN"; //$NON-NLS-1$ public static final String TWIG_STMT_CLOSE = "TWIG_STMT_CLOSE"; //$NON-NLS-1$ public static final String TWIG_CONTENT = "TWIG_CONTENT"; //$NON-NLS-1$ @@ -31,12 +31,6 @@ public interface TwigRegionTypes { static final String PHP_KEYWORD = "PHP_KEYWORD"; //$NON-NLS-1$ - static final String PHP_OPENTAG = "PHP_OPENTAG"; //$NON-NLS-1$ - - static final String PHP_CLOSETAG = "PHP_CLOSETAG"; //$NON-NLS-1$ - - static final String PHP_CONTENT = "PHP_CONTENT"; //$NON-NLS-1$ - static final String PHP_OBJECT_OPERATOR = "PHP_OBJECT_OPERATOR"; //$//$NON-NLS-N$ static final String PHP_SEMICOLON = "PHP_SEMICOLON"; //$NON-NLS-1$ diff --git a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigScriptRegion.java b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigScriptRegion.java index efcfffb..fdc89d1 100644 --- a/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigScriptRegion.java +++ b/org.eclipse.twig.core/src/org/eclipse/twig/core/documentModel/parser/regions/TwigScriptRegion.java @@ -160,30 +160,30 @@ public StructuredDocumentEvent updateRegion(Object requester, .getEnd() + 1); final TwigTokenContainer newContainer = new TwigTokenContainer(); - final TwigLexer phpLexer = getTwigLexer(new DocumentReader( + final TwigLexer twigLexer = getTwigLexer(new DocumentReader( flatnode, changes, requestStart, lengthToReplace, newTokenOffset), startState); Object state = startState; try { - String yylex = phpLexer.getNextToken(); + String yylex = twigLexer.getNextToken(); if (shouldDeprecatedKeyword && TwigTokenContainer.isKeyword(yylex)) { yylex = TwigRegionTypes.PHP_STRING; } int yylength; final int toOffset = offset + length; - while (yylex != null && newTokenOffset <= toOffset - && yylex != TwigRegionTypes.TWIG_CLOSE) { - yylength = phpLexer.getLength(); + while (yylex != null && newTokenOffset <= toOffset && (yylex != TwigRegionTypes.TWIG_CLOSETAG && yylex != TwigRegionTypes.TWIG_STMT_CLOSE)) { + + yylength = twigLexer.getLength(); newContainer.addLast(yylex, newTokenOffset, yylength, yylength, state); newTokenOffset += yylength; - state = phpLexer.createLexicalStateMemento(); - yylex = phpLexer.getNextToken(); + state = twigLexer.createLexicalStateMemento(); + yylex = twigLexer.getNextToken(); } if (yylex == TwigRegionTypes.WHITESPACE) { - yylength = phpLexer.getLength(); + yylength = twigLexer.getLength(); newContainer.adjustWhitespace(yylex, newTokenOffset, yylength, yylength, state); } @@ -269,13 +269,14 @@ private void setTwigtokens(AbstractTwigLexer lexer) { Object state = lexer.createLexicalStateMemento(); String yylex = lexer.getNextToken(); int yylength = 0; - while (yylex != null && (yylex != TwigRegionTypes.TWIG_CLOSE && yylex != TwigRegionTypes.TWIG_STMT_CLOSE)) { + while (yylex != null && (yylex != TwigRegionTypes.TWIG_CLOSETAG && yylex != TwigRegionTypes.TWIG_STMT_CLOSE)) { + yylength = lexer.getLength(); this.tokensContainer.addLast(yylex, start, yylength, yylength, state); start += yylength; state = lexer.createLexicalStateMemento(); yylex = lexer.getNextToken(); -// System.err.println("size: " + ++s); + } diff --git a/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TokenizerTest.java b/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TokenizerTest.java index f413295..03ed4d0 100644 --- a/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TokenizerTest.java +++ b/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TokenizerTest.java @@ -47,6 +47,34 @@ protected void tearDown() throws Exception { } + @Test + public void testMultipleStatementsOnSingleLine() { + + + try { + + tokens = "Welcome {% endblock %}"; + //tokens = "Welcome <?php 'foo'; ?>"; + tokenizer = new TwigTokenizer(tokens.toCharArray()); + textRegions = new Stack<ITextRegion>(); + assertTrue(textRegions.size() == 0); + + while(!tokenizer.isEOF()) { + ITextRegion region = tokenizer.getNextToken(); + textRegions.push(region); + System.err.println(region.getType() + " " + region.getStart() + " " + region.getEnd()); + } + + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + + } + + @Test public void testEmbeddedRegion() { diff --git a/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TwigParserTest.java b/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TwigParserTest.java index 272682d..38c4104 100644 --- a/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TwigParserTest.java +++ b/org.eclipse.twig.test/src/org/eclipse/twig/test/testcases/TwigParserTest.java @@ -47,6 +47,23 @@ public void testEmptyPrint() { } + @Test + public void testPrintPipe() { + + assertValidTokenstream("{{ kenny | gun }}"); + + } + + @Test + public void testBlock() { + + assertValidTokenstream("{% block sidebar %}"); + assertValidTokenstream("{% endblock %}"); + assertValidTokenstream("{% block title pagetitle|title %}"); + + } + + @Test public void testForStatement() { diff --git a/org.eclipse.twig.ui/src/org/eclipse/twig/ui/editor/LineStyleProviderForTwig.java b/org.eclipse.twig.ui/src/org/eclipse/twig/ui/editor/LineStyleProviderForTwig.java index e0ae03b..3357691 100644 --- a/org.eclipse.twig.ui/src/org/eclipse/twig/ui/editor/LineStyleProviderForTwig.java +++ b/org.eclipse.twig.ui/src/org/eclipse/twig/ui/editor/LineStyleProviderForTwig.java @@ -33,6 +33,7 @@ public class LineStyleProviderForTwig extends LineStyleProviderForPhp { static { fColorTypes.put(TwigRegionContext.TWIG_OPEN, PreferenceConstants.EDITOR_BOUNDARYMARKER_COLOR); fColorTypes.put(TwigRegionContext.TWIG_CLOSE, PreferenceConstants.EDITOR_BOUNDARYMARKER_COLOR); + fColorTypes.put(TwigRegionContext.TWIG_CLOSETAG, PreferenceConstants.EDITOR_BOUNDARYMARKER_COLOR); fColorTypes.put(TwigRegionContext.TWIG_STMT_OPEN, PreferenceConstants.EDITOR_STRING_COLOR); fColorTypes.put(TwigRegionContext.TWIG_STMT_CLOSE, PreferenceConstants.EDITOR_STRING_COLOR);
d2931d33147aeb6c1e96d55a8fd1b252ff66b7f2
chrisvest$stormpot
Config now contains the Allocator and is generic. The same functionality has been moved out of the PoolFixtures.
p
https://github.com/chrisvest/stormpot
diff --git a/src/main/java/stormpot/Config.java b/src/main/java/stormpot/Config.java index 149f5c05..a6d6fb3f 100644 --- a/src/main/java/stormpot/Config.java +++ b/src/main/java/stormpot/Config.java @@ -2,20 +2,23 @@ import java.util.concurrent.TimeUnit; -public class Config { +public class Config<T extends Poolable> { private int size = 10; private boolean sane = true; private long ttl = 10; private TimeUnit ttlUnit = TimeUnit.MINUTES; + private Allocator allocator; - public synchronized Config copy() { + public synchronized Config<T> copy() { Config config = new Config(); config.setSize(size); + config.setAllocator(allocator); + config.setTTL(ttl, ttlUnit); return config; } - public synchronized Config setSize(int size) { + public synchronized Config<T> setSize(int size) { if (sane && size < 1) { throw new IllegalArgumentException( "size must be at least 1 but was " + size); @@ -28,12 +31,12 @@ public synchronized int getSize() { return size; } - synchronized Config goInsane() { + synchronized Config<T> goInsane() { sane = false; return this; } - public synchronized Config setTTL(long ttl, TimeUnit unit) { + public synchronized Config<T> setTTL(long ttl, TimeUnit unit) { if (sane && unit == null) { throw new IllegalArgumentException("unit cannot be null"); } @@ -49,4 +52,13 @@ public synchronized long getTTL() { public synchronized TimeUnit getTTLUnit() { return ttlUnit; } + + public <X extends Poolable> Config<X> setAllocator(Allocator<X> allocator) { + this.allocator = allocator; + return (Config<X>) this; + } + + public Allocator<T> getAllocator() { + return allocator; + } } diff --git a/src/test/java/stormpot/CountingAllocator.java b/src/test/java/stormpot/CountingAllocator.java new file mode 100644 index 00000000..6c79d31e --- /dev/null +++ b/src/test/java/stormpot/CountingAllocator.java @@ -0,0 +1,30 @@ +package stormpot; + +import java.util.concurrent.atomic.AtomicInteger; + +public class CountingAllocator implements Allocator { + private final AtomicInteger allocations = new AtomicInteger(); + private final AtomicInteger deallocations = new AtomicInteger(); + + public Poolable allocate(Slot slot) { + allocations.incrementAndGet(); + return new GenericPoolable(slot); + } + + public void deallocate(Poolable poolable) { + deallocations.incrementAndGet(); + } + + public void reset() { + allocations.set(0); + deallocations.set(0); + } + + public int allocations() { + return allocations.get(); + } + + public int deallocations() { + return deallocations.get(); + } +} diff --git a/src/test/java/stormpot/CountingAllocatorWrapper.java b/src/test/java/stormpot/CountingAllocatorWrapper.java deleted file mode 100644 index 491e22d7..00000000 --- a/src/test/java/stormpot/CountingAllocatorWrapper.java +++ /dev/null @@ -1,34 +0,0 @@ -package stormpot; - -import java.util.concurrent.atomic.AtomicInteger; - -public class CountingAllocatorWrapper implements Allocator { - - private final Allocator delegate; - private final AtomicInteger allocations; - private final AtomicInteger deallocations; - - public CountingAllocatorWrapper(Allocator delegate) { - this.delegate = delegate; - allocations = new AtomicInteger(); - deallocations = new AtomicInteger(); - } - - public Poolable allocate(Slot lease) { - allocations.incrementAndGet(); - return delegate.allocate(lease); - } - - public int countAllocations() { - return allocations.get(); - } - - public int countDeallocations() { - return deallocations.get(); - } - - public void deallocate(Poolable poolable) { - deallocations.incrementAndGet(); - delegate.deallocate(poolable); - } -} diff --git a/src/test/java/stormpot/GenericAllocator.java b/src/test/java/stormpot/GenericAllocator.java deleted file mode 100644 index 7eead58c..00000000 --- a/src/test/java/stormpot/GenericAllocator.java +++ /dev/null @@ -1,11 +0,0 @@ -package stormpot; - -public class GenericAllocator implements Allocator { - - public Poolable allocate(Slot slot) { - return new GenericPoolable(slot); - } - - public void deallocate(Poolable poolable) { - } -} diff --git a/src/test/java/stormpot/PoolFixture.java b/src/test/java/stormpot/PoolFixture.java index 07d21b59..977f0c4d 100644 --- a/src/test/java/stormpot/PoolFixture.java +++ b/src/test/java/stormpot/PoolFixture.java @@ -5,8 +5,4 @@ public interface PoolFixture { Pool initPool(); Pool initPool(Config config); - - int allocations(); - - int deallocations(); } diff --git a/src/test/java/stormpot/PoolTest.java b/src/test/java/stormpot/PoolTest.java index 49ab6d84..ae56ac2a 100644 --- a/src/test/java/stormpot/PoolTest.java +++ b/src/test/java/stormpot/PoolTest.java @@ -8,7 +8,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Assume; +import org.junit.Before; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; @@ -31,9 +31,7 @@ * <p> * The test case uses theories to apply to the set of possible Pool * implementations. Each implementation must have a PoolFixture, which is - * used to construct and initialise the pool, based on a Config, and to - * provide information on how the implementation interacts with its - * Allocator. + * used to construct and initialise the pool, based on a Config. * <p> * The only assumptions used in this test, is whether the Pool is a * LifecycledPool or not. And most interesting pools are life-cycled. @@ -46,12 +44,20 @@ */ @RunWith(Theories.class) public class PoolTest { - private static final Config config = new Config().setSize(1); + private static final CountingAllocator allocator = + new CountingAllocator(); + private static final Config config = + new Config().setSize(1).setAllocator(allocator); @DataPoints public static PoolFixture[] pools() { return PoolFixtures.poolFixtures(config); } + + @Before public void + setUp() { + allocator.reset(); + } /** * The pool mustn't return null when we claim an object. The Allocator @@ -81,7 +87,7 @@ public static PoolFixture[] pools() { mustGetPooledObjectsFromObjectSource(PoolFixture fixture) { Pool pool = fixture.initPool(); pool.claim(); - assertThat(fixture.allocations(), is(greaterThan(0))); + assertThat(allocator.allocations(), is(greaterThan(0))); } /** @@ -139,7 +145,7 @@ public static PoolFixture[] pools() { Pool pool = fixture.initPool(); pool.claim().release(); pool.claim().release(); - assertThat(fixture.allocations(), is(1)); + assertThat(allocator.allocations(), is(1)); } /** @@ -196,7 +202,7 @@ public static PoolFixture[] pools() { config.copy().goInsane().setTTL(-1L, TimeUnit.MILLISECONDS)); pool.claim().release(); pool.claim().release(); - assertThat(fixture.allocations(), is(2)); + assertThat(allocator.allocations(), is(2)); } /** @@ -218,7 +224,7 @@ public static PoolFixture[] pools() { config.copy().goInsane().setTTL(-1L, TimeUnit.MILLISECONDS)); pool.claim().release(); pool.claim().release(); - assertThat(fixture.deallocations(), is(greaterThanOrEqualTo(1))); + assertThat(allocator.deallocations(), is(greaterThanOrEqualTo(1))); // We use greaterThanOrEqualTo because we cannot say whether the second // release() will deallocate as well - deallocation might be done // asynchronously. However, because the pool is not allowed to be larger @@ -251,7 +257,7 @@ public static PoolFixture[] pools() { p1.release(); p2.release(); shutdown(pool).await(); - assertThat(fixture.deallocations(), is(2)); + assertThat(allocator.deallocations(), is(2)); } /** @@ -296,7 +302,7 @@ public static PoolFixture[] pools() { Pool pool = fixture.initPool(); pool.claim(); shutdown(pool).await(10, TimeUnit.MILLISECONDS); - assertThat(fixture.deallocations(), is(0)); + assertThat(allocator.deallocations(), is(0)); } /** @@ -426,8 +432,16 @@ public static PoolFixture[] pools() { * Clients might hold on to objects after they have been released. This is * a user error, but pools must still maintain a coherent allocation and * deallocation pattern toward the Allocator. + * We test this by configuring a pool with a negative TTL so that the objects + * will be deallocated as soon as possible. Then we claim an object and + * release it twice. Then we claim and release another object to guarantee + * that the deallocation of the first object have taken place when we check + * the count. Either one or two deallocations must have taken place at this + * point. We can't say for sure which it is because we might be racy with + * the deallocation of the last object. * @param fixture */ + @Test(timeout = 300) @Theory public void mustNotDeallocateTheSameObjectMoreThanOnce(PoolFixture fixture) { Pool pool = fixture.initPool( @@ -436,11 +450,12 @@ public static PoolFixture[] pools() { obj.release(); try { obj.release(); - } catch (Exception e) { - Assume.assumeNoException(e); + } catch (Exception _) { + // we don't really care if the pool is able to detect this or not + // we are still going to check with the Allocator. } pool.claim().release(); - assertThat(fixture.deallocations(), is(2)); + assertThat(allocator.deallocations(), isOneOf(1, 2)); } // TODO pools must never deallocate the same object more than once (Allocator javadoc) // TODO what to do if a thread releases the same claim twice? (Allocator javadoc) diff --git a/src/test/java/stormpot/basicpool/BasicPool.java b/src/test/java/stormpot/basicpool/BasicPool.java index 5c098358..6c9f94d9 100644 --- a/src/test/java/stormpot/basicpool/BasicPool.java +++ b/src/test/java/stormpot/basicpool/BasicPool.java @@ -35,7 +35,7 @@ public class BasicPool<T extends Poolable> implements LifecycledPool<T> { private final long ttlMillis; private boolean shutdown; - public BasicPool(Config config, Allocator<T> objectSource) { + public BasicPool(Config<T> config) { synchronized (config) { int size = config.getSize(); if (size < 1) { @@ -45,8 +45,8 @@ public BasicPool(Config config, Allocator<T> objectSource) { this.pool = new Poolable[size]; this.slots = new BasicSlot[size]; this.ttlMillis = config.getTTLUnit().toMillis(config.getTTL()); + this.allocator = config.getAllocator(); } - this.allocator = objectSource; this.count = new AtomicInteger(); this.lock = new ReentrantLock(); this.released = lock.newCondition(); diff --git a/src/test/java/stormpot/basicpool/BasicPoolFixture.java b/src/test/java/stormpot/basicpool/BasicPoolFixture.java index 5749b224..c1452108 100644 --- a/src/test/java/stormpot/basicpool/BasicPoolFixture.java +++ b/src/test/java/stormpot/basicpool/BasicPoolFixture.java @@ -1,19 +1,15 @@ package stormpot.basicpool; import stormpot.Config; -import stormpot.CountingAllocatorWrapper; -import stormpot.GenericAllocator; import stormpot.Pool; import stormpot.PoolFixture; public class BasicPoolFixture implements PoolFixture { - private CountingAllocatorWrapper allocator; private Config config; public BasicPoolFixture(Config config) { this.config = config.copy(); - this.allocator = new CountingAllocatorWrapper(new GenericAllocator()); } public Pool initPool() { @@ -21,15 +17,7 @@ public Pool initPool() { } public Pool initPool(Config config) { - BasicPool pool = new BasicPool(config, allocator); + BasicPool pool = new BasicPool(config); return pool; } - - public int allocations() { - return allocator.countAllocations(); - } - - public int deallocations() { - return allocator.countDeallocations(); - } }
28696f9d6030a11da29b47c760026b7568002df8
kotlin
Try keyword--
a
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/lexer/_JetLexer.java b/idea/src/org/jetbrains/jet/lexer/_JetLexer.java index c905dc614d55c..928cafa6a5194 100644 --- a/idea/src/org/jetbrains/jet/lexer/_JetLexer.java +++ b/idea/src/org/jetbrains/jet/lexer/_JetLexer.java @@ -1,4 +1,4 @@ -/* The following code was generated by JFlex 1.4.3 on 12/27/10 6:49 PM */ +/* The following code was generated by JFlex 1.4.3 on 12/27/10 7:06 PM */ /* It's an automatically generated code. Do not modify it. */ package org.jetbrains.jet.lexer; @@ -13,7 +13,7 @@ /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.4.3 - * on 12/27/10 6:49 PM from the specification file + * on 12/27/10 7:06 PM from the specification file * <tt>/home/user/work/jet/idea/src/org/jetbrains/jet/lexer/Jet.flex</tt> */ class _JetLexer implements FlexLexer { @@ -148,17 +148,17 @@ class _JetLexer implements FlexLexer { "\10\3\1\47\1\50\1\51\6\3\1\52\4\3\1\53"+ "\1\54\1\55\1\56\1\57\1\60\1\61\1\62\1\63"+ "\1\64\1\65\1\66\1\34\1\36\1\67\1\0\1\33"+ - "\3\0\1\12\1\70\1\3\1\71\13\3\1\72\1\73"+ - "\1\3\1\74\1\3\1\75\1\76\1\3\1\77\3\3"+ - "\1\100\1\0\2\67\1\0\1\34\2\0\1\3\1\101"+ - "\1\3\1\102\3\3\1\103\1\104\1\3\1\105\7\3"+ - "\1\36\1\0\1\34\1\0\1\3\1\106\1\3\1\107"+ - "\2\3\1\110\1\111\1\3\1\112\2\3\1\113\1\114"+ - "\1\70\3\3\1\115\1\116\1\3\1\117\6\3\1\120"+ - "\1\3\1\121\1\122\1\3\1\123"; + "\3\0\1\12\1\70\1\3\1\71\11\3\1\72\2\3"+ + "\1\73\1\74\1\3\1\75\1\3\1\76\1\77\1\3"+ + "\1\100\3\3\1\101\1\0\2\67\1\0\1\34\2\0"+ + "\1\3\1\102\1\3\1\103\3\3\1\104\1\105\1\3"+ + "\1\106\7\3\1\36\1\0\1\34\1\0\1\3\1\107"+ + "\1\3\1\110\2\3\1\111\1\112\1\3\1\113\2\3"+ + "\1\114\1\115\1\70\3\3\1\116\1\117\1\3\1\120"+ + "\6\3\1\121\1\3\1\122\1\123\1\3\1\124"; private static int [] zzUnpackAction() { - int [] result = new int[203]; + int [] result = new int[204]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; @@ -198,20 +198,20 @@ private static int zzUnpackAction(String packed, int offset, int [] result) { "\0\76\0\76\0\u10b6\0\76\0\76\0\76\0\76\0\76"+ "\0\u10f4\0\u1132\0\u1170\0\u11ae\0\u11ae\0\u11ec\0\u122a\0\u1268"+ "\0\76\0\u12a6\0\u12e4\0\272\0\u1322\0\u1360\0\u139e\0\u13dc"+ - "\0\u141a\0\u1458\0\u1496\0\u14d4\0\u1512\0\u1550\0\u158e\0\272"+ - "\0\272\0\u15cc\0\272\0\u160a\0\272\0\272\0\u1648\0\272"+ - "\0\u1686\0\u16c4\0\u1702\0\76\0\u1740\0\u177e\0\76\0\u17bc"+ - "\0\u17fa\0\u1838\0\u1876\0\u18b4\0\272\0\u18f2\0\272\0\u1930"+ - "\0\u196e\0\u19ac\0\u19ea\0\272\0\u1a28\0\272\0\u1a66\0\u1aa4"+ - "\0\u1ae2\0\u1b20\0\u1b5e\0\u1b9c\0\u1bda\0\76\0\u1c18\0\u11ae"+ - "\0\u1c56\0\u1c94\0\272\0\u1cd2\0\272\0\u1d10\0\u1d4e\0\272"+ - "\0\272\0\u1d8c\0\272\0\u1dca\0\u1e08\0\272\0\272\0\76"+ - "\0\u1e46\0\u1e84\0\u1ec2\0\272\0\272\0\u1f00\0\272\0\u1f3e"+ - "\0\u1f7c\0\u1fba\0\u1ff8\0\u2036\0\u2074\0\272\0\u20b2\0\272"+ - "\0\272\0\u20f0\0\272"; + "\0\u141a\0\u1458\0\u1496\0\u14d4\0\u1512\0\272\0\u1550\0\u158e"+ + "\0\272\0\272\0\u15cc\0\272\0\u160a\0\272\0\272\0\u1648"+ + "\0\272\0\u1686\0\u16c4\0\u1702\0\76\0\u1740\0\u177e\0\76"+ + "\0\u17bc\0\u17fa\0\u1838\0\u1876\0\u18b4\0\272\0\u18f2\0\272"+ + "\0\u1930\0\u196e\0\u19ac\0\u19ea\0\272\0\u1a28\0\272\0\u1a66"+ + "\0\u1aa4\0\u1ae2\0\u1b20\0\u1b5e\0\u1b9c\0\u1bda\0\76\0\u1c18"+ + "\0\u11ae\0\u1c56\0\u1c94\0\272\0\u1cd2\0\272\0\u1d10\0\u1d4e"+ + "\0\272\0\272\0\u1d8c\0\272\0\u1dca\0\u1e08\0\272\0\272"+ + "\0\76\0\u1e46\0\u1e84\0\u1ec2\0\272\0\272\0\u1f00\0\272"+ + "\0\u1f3e\0\u1f7c\0\u1fba\0\u1ff8\0\u2036\0\u2074\0\272\0\u20b2"+ + "\0\272\0\272\0\u20f0\0\272"; private static int [] zzUnpackRowMap() { - int [] result = new int[203]; + int [] result = new int[204]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; @@ -315,136 +315,136 @@ private static int zzUnpackRowMap(String packed, int offset, int [] result) { "\5\4\1\173\21\4\23\0\2\4\1\0\2\4\3\0"+ "\5\4\1\0\1\4\1\0\1\4\3\0\13\4\1\174"+ "\1\4\1\175\11\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\17\4\1\176"+ - "\7\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\1\177\26\4\23\0\2\4"+ - "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\11\4\1\200\3\4\1\201\11\4\23\0\2\4"+ - "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\7\4\1\202\6\4\1\203\10\4\23\0\2\4"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\10\4\1\176"+ + "\6\4\1\177\7\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\1\200\26\4"+ + "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ + "\1\0\1\4\3\0\11\4\1\201\3\4\1\202\11\4"+ + "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ + "\1\0\1\4\3\0\7\4\1\203\6\4\1\204\10\4"+ + "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ + "\1\0\1\4\3\0\11\4\1\205\15\4\23\0\2\4"+ "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\11\4\1\204\15\4\23\0\2\4\1\0\2\4"+ - "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\1\205"+ - "\26\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\15\4\1\206\11\4\23\0"+ + "\3\0\1\206\26\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\15\4\1\207"+ + "\11\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ + "\1\4\1\0\1\4\3\0\6\4\1\210\20\4\23\0"+ "\2\4\1\0\2\4\3\0\5\4\1\0\1\4\1\0"+ - "\1\4\3\0\6\4\1\207\20\4\23\0\2\4\1\0"+ + "\1\4\3\0\7\4\1\211\17\4\23\0\2\4\1\0"+ "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ - "\7\4\1\210\17\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\26\4\1\211"+ - "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ - "\1\0\1\4\3\0\13\4\1\212\13\4\23\0\2\4"+ - "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\3\4\1\213\23\4\111\0\1\214\7\0\1\151"+ - "\7\0\1\151\3\0\1\56\25\0\1\56\1\0\1\56"+ - "\30\0\7\152\1\215\66\152\6\216\1\217\1\153\66\216"+ - "\1\0\2\154\6\0\1\154\1\0\1\154\1\0\1\154"+ - "\1\0\1\154\1\0\1\220\4\0\1\154\1\0\1\154"+ - "\1\0\1\220\1\154\7\0\1\154\1\0\1\154\3\0"+ - "\1\154\25\0\2\154\6\0\1\154\1\0\1\154\1\0"+ - "\1\154\1\150\1\154\1\0\1\220\4\0\1\154\1\0"+ - "\1\154\1\0\1\220\1\154\7\0\1\154\1\0\1\154"+ - "\3\0\1\154\25\0\1\221\1\154\6\0\1\221\1\0"+ - "\1\154\1\0\1\154\1\0\1\154\1\222\1\220\4\0"+ - "\1\154\1\0\1\154\1\0\1\220\1\154\7\0\1\154"+ - "\1\0\1\154\3\0\1\154\10\0\1\222\31\0\1\150"+ - "\57\0\24\162\1\223\51\162\1\0\2\4\1\0\2\4"+ - "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\3\4"+ - "\1\224\23\4\23\0\2\4\1\0\2\4\3\0\5\4"+ - "\1\0\1\4\1\0\1\4\3\0\11\4\1\225\15\4"+ + "\26\4\1\212\23\0\2\4\1\0\2\4\3\0\5\4"+ + "\1\0\1\4\1\0\1\4\3\0\13\4\1\213\13\4"+ "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ - "\1\0\1\4\3\0\6\4\1\226\20\4\23\0\2\4"+ + "\1\0\1\4\3\0\3\4\1\214\23\4\111\0\1\215"+ + "\7\0\1\151\7\0\1\151\3\0\1\56\25\0\1\56"+ + "\1\0\1\56\30\0\7\152\1\216\66\152\6\217\1\220"+ + "\1\153\66\217\1\0\2\154\6\0\1\154\1\0\1\154"+ + "\1\0\1\154\1\0\1\154\1\0\1\221\4\0\1\154"+ + "\1\0\1\154\1\0\1\221\1\154\7\0\1\154\1\0"+ + "\1\154\3\0\1\154\25\0\2\154\6\0\1\154\1\0"+ + "\1\154\1\0\1\154\1\150\1\154\1\0\1\221\4\0"+ + "\1\154\1\0\1\154\1\0\1\221\1\154\7\0\1\154"+ + "\1\0\1\154\3\0\1\154\25\0\1\222\1\154\6\0"+ + "\1\222\1\0\1\154\1\0\1\154\1\0\1\154\1\223"+ + "\1\221\4\0\1\154\1\0\1\154\1\0\1\221\1\154"+ + "\7\0\1\154\1\0\1\154\3\0\1\154\10\0\1\223"+ + "\31\0\1\150\57\0\24\162\1\224\51\162\1\0\2\4"+ "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\3\4\1\227\23\4\23\0\2\4\1\0\2\4"+ - "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\3\4"+ - "\1\230\23\4\23\0\2\4\1\0\2\4\3\0\5\4"+ - "\1\0\1\4\1\0\1\4\3\0\4\4\1\231\22\4"+ + "\3\0\3\4\1\225\23\4\23\0\2\4\1\0\2\4"+ + "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\11\4"+ + "\1\226\15\4\23\0\2\4\1\0\2\4\3\0\5\4"+ + "\1\0\1\4\1\0\1\4\3\0\6\4\1\227\20\4"+ "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ - "\1\0\1\4\3\0\7\4\1\232\17\4\23\0\2\4"+ + "\1\0\1\4\3\0\3\4\1\230\23\4\23\0\2\4"+ "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\3\4\1\233\23\4\23\0\2\4\1\0\2\4"+ + "\3\0\3\4\1\231\23\4\23\0\2\4\1\0\2\4"+ "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\4\4"+ - "\1\234\22\4\23\0\2\4\1\0\2\4\3\0\5\4"+ - "\1\0\1\4\1\0\1\4\3\0\21\4\1\235\5\4"+ + "\1\232\22\4\23\0\2\4\1\0\2\4\3\0\5\4"+ + "\1\0\1\4\1\0\1\4\3\0\7\4\1\233\17\4"+ "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ - "\1\0\1\4\3\0\3\4\1\236\23\4\23\0\2\4"+ + "\1\0\1\4\3\0\3\4\1\234\23\4\23\0\2\4"+ "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\21\4\1\237\5\4\23\0\2\4\1\0\2\4"+ - "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\17\4"+ - "\1\240\7\4\23\0\2\4\1\0\2\4\3\0\5\4"+ - "\1\0\1\4\1\0\1\4\3\0\4\4\1\241\22\4"+ + "\3\0\4\4\1\235\22\4\23\0\2\4\1\0\2\4"+ + "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\21\4"+ + "\1\236\5\4\23\0\2\4\1\0\2\4\3\0\5\4"+ + "\1\0\1\4\1\0\1\4\3\0\3\4\1\237\23\4"+ "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ - "\1\0\1\4\3\0\21\4\1\242\5\4\23\0\2\4"+ + "\1\0\1\4\3\0\21\4\1\240\5\4\23\0\2\4"+ "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\3\4\1\243\23\4\23\0\2\4\1\0\2\4"+ - "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\11\4"+ - "\1\244\15\4\23\0\2\4\1\0\2\4\3\0\5\4"+ - "\1\0\1\4\1\0\1\4\3\0\1\4\1\245\25\4"+ - "\22\0\6\152\1\246\1\215\66\152\7\216\1\247\66\216"+ - "\1\0\1\151\7\0\1\151\6\0\1\222\41\0\1\222"+ - "\14\0\1\221\1\154\6\0\1\221\1\0\1\154\1\0"+ - "\1\250\1\0\1\154\1\0\1\220\4\0\1\154\1\0"+ - "\1\154\1\0\1\220\1\154\7\0\1\250\1\0\1\250"+ - "\3\0\1\154\25\0\1\151\7\0\1\151\64\0\24\162"+ - "\1\251\51\162\1\0\2\4\1\0\2\4\3\0\5\4"+ - "\1\0\1\4\1\0\1\4\3\0\4\4\1\252\22\4"+ + "\3\0\17\4\1\241\7\4\23\0\2\4\1\0\2\4"+ + "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\4\4"+ + "\1\242\22\4\23\0\2\4\1\0\2\4\3\0\5\4"+ + "\1\0\1\4\1\0\1\4\3\0\21\4\1\243\5\4"+ "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ - "\1\0\1\4\3\0\12\4\1\253\14\4\23\0\2\4"+ + "\1\0\1\4\3\0\3\4\1\244\23\4\23\0\2\4"+ "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\1\254\26\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\4\4\1\255"+ - "\22\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\13\4\1\256\13\4\23\0"+ + "\3\0\11\4\1\245\15\4\23\0\2\4\1\0\2\4"+ + "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\1\4"+ + "\1\246\25\4\22\0\6\152\1\247\1\216\66\152\7\217"+ + "\1\250\66\217\1\0\1\151\7\0\1\151\6\0\1\223"+ + "\41\0\1\223\14\0\1\222\1\154\6\0\1\222\1\0"+ + "\1\154\1\0\1\251\1\0\1\154\1\0\1\221\4\0"+ + "\1\154\1\0\1\154\1\0\1\221\1\154\7\0\1\251"+ + "\1\0\1\251\3\0\1\154\25\0\1\151\7\0\1\151"+ + "\64\0\24\162\1\252\51\162\1\0\2\4\1\0\2\4"+ + "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\4\4"+ + "\1\253\22\4\23\0\2\4\1\0\2\4\3\0\5\4"+ + "\1\0\1\4\1\0\1\4\3\0\12\4\1\254\14\4"+ + "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ + "\1\0\1\4\3\0\1\255\26\4\23\0\2\4\1\0"+ + "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ + "\4\4\1\256\22\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\13\4\1\257"+ + "\13\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ + "\1\4\1\0\1\4\3\0\21\4\1\260\5\4\23\0"+ "\2\4\1\0\2\4\3\0\5\4\1\0\1\4\1\0"+ - "\1\4\3\0\21\4\1\257\5\4\23\0\2\4\1\0"+ + "\1\4\3\0\23\4\1\261\3\4\23\0\2\4\1\0"+ "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ - "\23\4\1\260\3\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\7\4\1\261"+ - "\17\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\15\4\1\262\11\4\23\0"+ + "\7\4\1\262\17\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\15\4\1\263"+ + "\11\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ + "\1\4\1\0\1\4\3\0\3\4\1\264\23\4\23\0"+ "\2\4\1\0\2\4\3\0\5\4\1\0\1\4\1\0"+ - "\1\4\3\0\3\4\1\263\23\4\23\0\2\4\1\0"+ + "\1\4\3\0\2\4\1\265\24\4\23\0\2\4\1\0"+ "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ - "\2\4\1\264\24\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\6\4\1\265"+ - "\20\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\3\4\1\266\23\4\23\0"+ + "\6\4\1\266\20\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\3\4\1\267"+ + "\23\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ + "\1\4\1\0\1\4\3\0\25\4\1\270\1\4\22\0"+ + "\6\217\1\220\1\250\66\217\24\162\1\271\51\162\1\0"+ "\2\4\1\0\2\4\3\0\5\4\1\0\1\4\1\0"+ - "\1\4\3\0\25\4\1\267\1\4\22\0\6\216\1\217"+ - "\1\247\66\216\24\162\1\270\51\162\1\0\2\4\1\0"+ + "\1\4\3\0\5\4\1\272\21\4\23\0\2\4\1\0"+ "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ - "\5\4\1\271\21\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\4\4\1\272"+ - "\22\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\1\273\26\4\23\0\2\4"+ + "\4\4\1\273\22\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\1\274\26\4"+ + "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ + "\1\0\1\4\3\0\16\4\1\275\10\4\23\0\2\4"+ "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\16\4\1\274\10\4\23\0\2\4\1\0\2\4"+ - "\3\0\5\4\1\0\1\4\1\0\1\4\3\0\1\275"+ - "\26\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\5\4\1\276\21\4\23\0"+ + "\3\0\1\276\26\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\5\4\1\277"+ + "\21\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ + "\1\4\1\0\1\4\3\0\7\4\1\300\17\4\23\0"+ "\2\4\1\0\2\4\3\0\5\4\1\0\1\4\1\0"+ - "\1\4\3\0\7\4\1\277\17\4\23\0\2\4\1\0"+ + "\1\4\3\0\1\4\1\301\25\4\23\0\2\4\1\0"+ "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ - "\1\4\1\300\25\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\13\4\1\301"+ - "\13\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\17\4\1\302\7\4\23\0"+ + "\13\4\1\302\13\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\17\4\1\303"+ + "\7\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ + "\1\4\1\0\1\4\3\0\21\4\1\304\5\4\23\0"+ "\2\4\1\0\2\4\3\0\5\4\1\0\1\4\1\0"+ - "\1\4\3\0\21\4\1\303\5\4\23\0\2\4\1\0"+ + "\1\4\3\0\6\4\1\305\20\4\23\0\2\4\1\0"+ "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ - "\6\4\1\304\20\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\21\4\1\305"+ - "\5\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ - "\1\4\1\0\1\4\3\0\3\4\1\306\23\4\23\0"+ + "\21\4\1\306\5\4\23\0\2\4\1\0\2\4\3\0"+ + "\5\4\1\0\1\4\1\0\1\4\3\0\3\4\1\307"+ + "\23\4\23\0\2\4\1\0\2\4\3\0\5\4\1\0"+ + "\1\4\1\0\1\4\3\0\4\4\1\310\22\4\23\0"+ "\2\4\1\0\2\4\3\0\5\4\1\0\1\4\1\0"+ - "\1\4\3\0\4\4\1\307\22\4\23\0\2\4\1\0"+ + "\1\4\3\0\3\4\1\311\23\4\23\0\2\4\1\0"+ "\2\4\3\0\5\4\1\0\1\4\1\0\1\4\3\0"+ - "\3\4\1\310\23\4\23\0\2\4\1\0\2\4\3\0"+ - "\5\4\1\0\1\4\1\0\1\4\3\0\1\311\26\4"+ + "\1\312\26\4\23\0\2\4\1\0\2\4\3\0\5\4"+ + "\1\0\1\4\1\0\1\4\3\0\3\4\1\313\23\4"+ "\23\0\2\4\1\0\2\4\3\0\5\4\1\0\1\4"+ - "\1\0\1\4\3\0\3\4\1\312\23\4\23\0\2\4"+ - "\1\0\2\4\3\0\5\4\1\0\1\4\1\0\1\4"+ - "\3\0\15\4\1\313\11\4\22\0"; + "\1\0\1\4\3\0\15\4\1\314\11\4\22\0"; private static int [] zzUnpackTrans() { int [] result = new int[8494]; @@ -490,12 +490,12 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\1\11\30\1\6\11\11\1\5\11\4\1\2\11"+ "\1\0\3\1\6\11\36\1\6\11\1\1\5\11\3\1"+ - "\1\0\1\1\3\0\1\11\32\1\1\11\1\0\1\1"+ + "\1\0\1\1\3\0\1\11\33\1\1\11\1\0\1\1"+ "\1\11\1\0\1\1\2\0\22\1\1\11\1\0\1\1"+ "\1\0\16\1\1\11\23\1"; private static int [] zzUnpackAttribute() { - int [] result = new int[203]; + int [] result = new int[204]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; @@ -803,335 +803,339 @@ else if (zzAtEOF) { case 3: { return JetTokens.IDENTIFIER; } - case 84: break; - case 62: - { return JetTokens.FOR_KEYWORD ; - } case 85: break; case 63: - { return JetTokens.OUT_KEYWORD ; + { return JetTokens.FOR_KEYWORD ; } case 86: break; - case 78: - { return JetTokens.RETURN_KEYWORD ; + case 64: + { return JetTokens.OUT_KEYWORD ; } case 87: break; - case 65: - { return JetTokens.NULL_KEYWORD ; + case 79: + { return JetTokens.RETURN_KEYWORD ; } case 88: break; + case 66: + { return JetTokens.NULL_KEYWORD ; + } + case 89: break; case 20: { return JetTokens.LT ; } - case 89: break; + case 90: break; case 42: { return JetTokens.DO_KEYWORD ; } - case 90: break; + case 91: break; case 17: { return JetTokens.PLUS ; } - case 91: break; + case 92: break; case 27: { return JetTokens.LONG_LITERAL; } - case 92: break; + case 93: break; case 56: { return JetTokens.RAW_STRING_LITERAL; } - case 93: break; + case 94: break; case 44: { return JetTokens.PLUSEQ ; } - case 94: break; + case 95: break; case 26: { return JetTokens.COMMA ; } - case 95: break; - case 70: + case 96: break; + case 71: { return JetTokens.MATCH_KEYWORD ; } - case 96: break; + case 97: break; case 21: { return JetTokens.GT ; } - case 97: break; + case 98: break; case 4: { return JetTokens.WHITE_SPACE; } - case 98: break; - case 77: + case 99: break; + case 78: { return JetTokens.TYPEOF_KEYWORD ; } - case 99: break; + case 100: break; case 16: { return JetTokens.RPAR ; } - case 100: break; - case 69: + case 101: break; + case 70: { return JetTokens.TRUE_KEYWORD ; } - case 101: break; + case 102: break; case 50: { return JetTokens.ANDAND ; } - case 102: break; + case 103: break; case 55: { return JetTokens.DOC_COMMENT; } - case 103: break; + case 104: break; case 28: { return JetTokens.FLOAT_LITERAL; } - case 104: break; + case 105: break; case 29: { return JetTokens.EOL_COMMENT; } - case 105: break; + case 106: break; case 24: { return JetTokens.COLON ; } - case 106: break; + case 107: break; case 47: { return JetTokens.LTEQ ; } - case 107: break; + case 108: break; case 11: { return JetTokens.LBRACKET ; } - case 108: break; + case 109: break; case 54: { yypushback(2); return JetTokens.INTEGER_LITERAL; } - case 109: break; + case 110: break; case 9: { return JetTokens.CHARACTER_LITERAL; } - case 110: break; - case 59: + case 111: break; + case 60: { return JetTokens.VAR_KEYWORD ; } - case 111: break; + case 112: break; case 48: { return JetTokens.GTEQ ; } - case 112: break; + case 113: break; case 2: { return JetTokens.INTEGER_LITERAL; } - case 113: break; + case 114: break; case 14: { return JetTokens.RBRACE ; } - case 114: break; - case 71: + case 115: break; + case 72: { return JetTokens.CLASS_KEYWORD ; } - case 115: break; + case 116: break; case 18: { return JetTokens.EXCL ; } - case 116: break; + case 117: break; + case 58: + { return JetTokens.TRY_KEYWORD ; + } + case 118: break; case 45: { return JetTokens.EXCLEQ ; } - case 117: break; + case 119: break; case 37: { return JetTokens.MINUSEQ ; } - case 118: break; - case 72: + case 120: break; + case 73: { return JetTokens.THROW_KEYWORD ; } - case 119: break; - case 75: + case 121: break; + case 76: { return JetTokens.WHILE_KEYWORD ; } - case 120: break; + case 122: break; case 36: { return JetTokens.MINUSMINUS; } - case 121: break; - case 80: + case 123: break; + case 81: { return JetTokens.CONTINUE_KEYWORD ; } - case 122: break; + case 124: break; case 5: { return JetTokens.DIV ; } - case 123: break; + case 125: break; case 53: { return JetTokens.ELVIS ; } - case 124: break; + case 126: break; case 23: { return JetTokens.QUEST ; } - case 125: break; + case 127: break; case 51: { return JetTokens.OROR ; } - case 126: break; + case 128: break; case 19: { return JetTokens.PERC ; } - case 127: break; + case 129: break; case 46: { return JetTokens.PERCEQ ; } - case 128: break; + case 130: break; case 34: { return JetTokens.RANGE ; } - case 129: break; + case 131: break; case 1: { return TokenType.BAD_CHARACTER; } - case 130: break; + case 132: break; case 52: { return JetTokens.SAFE_ACCESS; } - case 131: break; - case 81: + case 133: break; + case 82: { return JetTokens.NAMESPACE_KEYWORD ; } - case 132: break; - case 83: + case 134: break; + case 84: { return JetTokens.DECOMPOSER_KEYWORD ; } - case 133: break; + case 135: break; case 6: { return JetTokens.MUL ; } - case 134: break; + case 136: break; case 12: { return JetTokens.RBRACKET ; } - case 135: break; + case 137: break; case 43: { return JetTokens.PLUSPLUS ; } - case 136: break; - case 68: + case 138: break; + case 69: { return JetTokens.THIS_KEYWORD ; } - case 137: break; + case 139: break; case 7: { return JetTokens.DOT ; } - case 138: break; + case 140: break; case 25: { return JetTokens.SEMICOLON ; } - case 139: break; + case 141: break; case 41: { return JetTokens.IF_KEYWORD ; } - case 140: break; + case 142: break; case 22: { return JetTokens.EQ ; } - case 141: break; + case 143: break; case 15: { return JetTokens.LPAR ; } - case 142: break; + case 144: break; case 8: { return JetTokens.MINUS ; } - case 143: break; - case 74: + case 145: break; + case 75: { return JetTokens.FALSE_KEYWORD ; } - case 144: break; - case 67: + case 146: break; + case 68: { return JetTokens.TYPE_KEYWORD ; } - case 145: break; - case 60: + case 147: break; + case 61: { return JetTokens.REF_KEYWORD ; } - case 146: break; - case 61: + case 148: break; + case 62: { return JetTokens.FUN_KEYWORD ; } - case 147: break; + case 149: break; case 40: { return JetTokens.IS_KEYWORD ; } - case 148: break; + case 150: break; case 31: { return JetTokens.DIVEQ ; } - case 149: break; - case 82: + case 151: break; + case 83: { return JetTokens.EXTENSION_KEYWORD ; } - case 150: break; + case 152: break; case 38: { return JetTokens.AS_KEYWORD ; } - case 151: break; - case 66: + case 153: break; + case 67: { return JetTokens.ELSE_KEYWORD ; } - case 152: break; + case 154: break; case 39: { return JetTokens.IN_KEYWORD ; } - case 153: break; + case 155: break; case 49: { return JetTokens.EQEQ ; } - case 154: break; - case 58: + case 156: break; + case 59: { return JetTokens.VAL_KEYWORD ; } - case 155: break; - case 64: + case 157: break; + case 65: { return JetTokens.EQEQEQ ; } - case 156: break; + case 158: break; case 57: { return JetTokens.NEW_KEYWORD ; } - case 157: break; + case 159: break; case 32: { return JetTokens.MULTEQ ; } - case 158: break; + case 160: break; case 10: { return JetTokens.STRING_LITERAL; } - case 159: break; + case 161: break; case 13: { return JetTokens.LBRACE ; } - case 160: break; - case 73: + case 162: break; + case 74: { return JetTokens.ISNOT_KEYWORD ; } - case 161: break; - case 79: + case 163: break; + case 80: { return JetTokens.OBJECT_KEYWORD ; } - case 162: break; - case 76: + case 164: break; + case 77: { return JetTokens.BREAK_KEYWORD ; } - case 163: break; + case 165: break; case 30: { return JetTokens.BLOCK_COMMENT; } - case 164: break; + case 166: break; case 35: { return JetTokens.FILTER ; } - case 165: break; + case 167: break; case 33: { return JetTokens.MAP ; } - case 166: break; + case 168: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true;
cf7bf0118558d283a54592a7eb4beb37ac4233a3
tapiji
Massive whitespace replacement (kill trailing spaces & spaces instead of tabs)
p
https://github.com/tapiji/tapiji
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 7fad91e2..628f04cb 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 @@ -22,120 +22,124 @@ 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> + * 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 */ public class ConfigurationManager { - private static ConfigurationManager INSTANCE; - - private IConfiguration config; - - private IPropertiesSerializerConfig serializerConfig; - - private IPropertiesDeserializerConfig deserializerConfig; - - private final static IConfiguration DEFAULT_CONFIG = new IConfiguration() { - @Override - public String getNonRbPattern() { - return "^(.)*/build\\.properties:true;^(.)*/config\\.properties:true;^(.)*/targetplatform/(.)*:true"; - } - - @Override - public boolean getAuditSameValue() { - return false; - } - - @Override - public boolean getAuditResource() { - return false; - } - - @Override - public boolean getAuditRb() { - return false; - } - - @Override - public boolean getAuditMissingValue() { - return false; - } - - @Override - public boolean getAuditMissingLanguage() { - return false; - } - }; - - private ConfigurationManager() { - config = getConfig(); - } - - private IConfiguration getConfig() { - - IExtensionPoint extp = Platform.getExtensionRegistry().getExtensionPoint( - "org.eclipse.babel.core" + ".babelConfiguration"); + private static ConfigurationManager INSTANCE; + + private IConfiguration config; + + private IPropertiesSerializerConfig serializerConfig; + + private IPropertiesDeserializerConfig deserializerConfig; + + private final static IConfiguration DEFAULT_CONFIG = new IConfiguration() { + @Override + public String getNonRbPattern() { + return "^(.)*/build\\.properties:true;^(.)*/config\\.properties:true;^(.)*/targetplatform/(.)*:true"; + } + + @Override + public boolean getAuditSameValue() { + return false; + } + + @Override + public boolean getAuditResource() { + return false; + } + + @Override + public boolean getAuditRb() { + return false; + } + + @Override + public boolean getAuditMissingValue() { + return false; + } + + @Override + public boolean getAuditMissingLanguage() { + return false; + } + }; + + 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 DEFAULT_CONFIG; - } - - /** - * @return The singleton instance - */ - public static ConfigurationManager getInstance() { - if (INSTANCE == null) { - INSTANCE = new ConfigurationManager(); - } - 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; - } - + try { + return (IConfiguration) elements[0] + .createExecutableExtension("class"); + } catch (CoreException e) { + e.printStackTrace(); + } + } + return DEFAULT_CONFIG; + } + + /** + * @return The singleton instance + */ + public static ConfigurationManager getInstance() { + if (INSTANCE == null) { + INSTANCE = new ConfigurationManager(); + } + 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 c4c37a4c..b45d117d 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 @@ -14,37 +14,41 @@ 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> + * 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 AbstractMessageModel - - private static boolean editorModificationEnabled = true; // no setText in EclipsePropertiesEditorResource - // set this, if you serialize! + private static boolean fireEnabled = true; // no property-fire calls in + // AbstractMessageModel - public static boolean isFireEnabled() { - return fireEnabled; - } + private static boolean editorModificationEnabled = true; // no setText in + // EclipsePropertiesEditorResource - public static void setFireEnabled(boolean fireEnabled) { - DirtyHack.fireEnabled = fireEnabled; - } + // set this, if you serialize! - public static boolean isEditorModificationEnabled() { - return editorModificationEnabled; - } + 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; + } - public static void setEditorModificationEnabled( - boolean editorModificationEnabled) { - DirtyHack.editorModificationEnabled = editorModificationEnabled; - } - } 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 5fdef1f3..a629827c 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 @@ -18,16 +18,16 @@ */ public interface IConfiguration { - boolean getAuditSameValue(); + boolean getAuditSameValue(); - boolean getAuditMissingValue(); + boolean getAuditMissingValue(); - boolean getAuditMissingLanguage(); + boolean getAuditMissingLanguage(); - boolean getAuditRb(); + boolean getAuditRb(); - boolean getAuditResource(); + boolean getAuditResource(); - String getNonRbPattern(); + String getNonRbPattern(); } diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java index 5ab62fa0..308feddf 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java @@ -25,18 +25,21 @@ */ public class MessageFactory { - static Logger logger = Logger.getLogger(MessageFactory.class.getSimpleName()); - + static Logger logger = Logger.getLogger(MessageFactory.class + .getSimpleName()); + /** - * @param key The key of the message - * @param locale The {@link Locale} + * @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 bafc1fc4..e2b05884 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 @@ -20,20 +20,21 @@ import org.eclipse.core.resources.IResource; /** - * 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> + * 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) { - - File ioFile = new File(resource.getRawLocation().toFile().getPath()); - - return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile, - ConfigurationManager.getInstance().getSerializerConfig(), - ConfigurationManager.getInstance().getDeserializerConfig())); + + File ioFile = new File(resource.getRawLocation().toFile().getPath()); + + return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile, + ConfigurationManager.getInstance().getSerializerConfig(), + ConfigurationManager.getInstance().getDeserializerConfig())); } } diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java index 85dae2ef..88aaa525 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java @@ -17,8 +17,8 @@ /** * 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> + * key-value pair, which can be found in resource bundles (1 row). <br> + * <br> * * @author Martin Reiterer, Alexej Strelzow */ @@ -26,60 +26,71 @@ public interface IMessage { /** * Gets the message key attribute. + * * @return Returns the key. */ - String getKey(); + String getKey(); /** * Gets the message text. + * * @return Returns the text. */ - String getValue(); + String getValue(); /** * Gets the message locale. + * * @return Returns the locale */ - Locale getLocale(); + Locale getLocale(); /** - * Gets the comment associated with this message (<code>null</code> if - * no comments). + * Gets the comment associated with this message (<code>null</code> if no + * comments). + * * @return Returns the comment. */ - String getComment(); + String getComment(); /** * Gets whether this message is active or not. + * * @return <code>true</code> if this message is active. */ - boolean isActive(); + boolean isActive(); - /** - * @return The toString representation - */ - String toString(); + /** + * @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. + * 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); + void setActive(boolean active); /** * Sets the message comment. - * @param comment The comment to set. + * + * @param comment + * The comment to set. */ - void setComment(String comment); + void setComment(String comment); /** * Sets the actual message text. - * @param text The text to set. + * + * @param text + * The text to set. */ - void setText(String test); + 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 index ef843f56..273a438c 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java @@ -19,9 +19,9 @@ 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> + * 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 */ @@ -30,97 +30,125 @@ public interface IMessagesBundle { /** * Called before this object will be discarded. */ - void dispose(); + 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 + * + * @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); + void renameMessageKey(String sourceKey, String targetKey); /** * Removes a message from this messages bundle. - * @param messageKey the key of the message to remove + * + * @param messageKey + * the key of the message to remove */ - void removeMessage(String messageKey); + 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 + * + * @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); + void duplicateMessage(String sourceKey, String targetKey); /** - * Gets the locale for the messages bundle (<code>null</code> assumes - * the default system locale). + * Gets the locale for the messages bundle (<code>null</code> assumes the + * default system locale). + * * @return Returns the locale. */ - Locale getLocale(); + Locale getLocale(); /** * Gets all message keys making up this messages bundle. + * * @return message keys */ - String[] getKeys(); + String[] getKeys(); /** * Returns the value to the given key, if the key exists. - * @param key, the key of a message. + * + * @param key + * , the key of a message. * @return The value to the given key. */ - String getValue(String 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(); + Collection<IMessage> getMessages(); /** * Gets a message. - * @param key a message key + * + * @param key + * a message key * @return a message */ - IMessage getMessage(String key); + IMessage getMessage(String key); /** * Adds an empty message. - * @param key the new message key + * + * @param key + * the new message key */ - void addMessage(IMessage message); + void addMessage(IMessage message); /** * Removes messages from this messages bundle. - * @param messageKeys the keys of the messages to remove + * + * @param messageKeys + * the keys of the messages to remove */ - void removeMessages(String[] messageKeys); + void removeMessages(String[] messageKeys); /** * Sets the comment for this messages bundle. - * @param comment The comment to set. + * + * @param comment + * The comment to set. */ - void setComment(String comment); + void setComment(String comment); /** * Gets the overall comment, or description, for this messages bundle.. + * * @return Returns the comment. */ - String getComment(); + String getComment(); /** * Gets the underlying messages resource implementation. + * * @return */ - IMessagesResource getResource(); + 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 + * 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); + 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 index b4803e13..446a0d40 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java @@ -27,140 +27,174 @@ */ 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); + /** + * 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 + * + * @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); + IMessage getMessage(String key, Locale locale); /** * Gets the messages bundle matching given locale. - * @param locale The locale of bundle to retreive + * + * @param locale + * The locale of bundle to retreive * @return a bundle */ - IMessagesBundle getMessagesBundle(Locale locale); + IMessagesBundle getMessagesBundle(Locale locale); /** * Removes messages matching the given key from all messages bundle. - * @param key The key of messages to remove + * + * @param key + * The key of messages to remove */ - void removeMessages(String messageKey); + void removeMessages(String messageKey); /** * Is the given key found in this bundle group. - * @param key The key to find + * + * @param key + * The key to find * @return <code>true</code> if the key exists in this bundle group. */ - boolean isKey(String key); + 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. + * + * @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); + void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle); /** * Gets all keys from all messages bundles. + * * @return all keys from all messages bundles */ - String[] getMessageKeys(); + String[] getMessageKeys(); /** * Adds an empty message to every messages bundle of this group with the * given. - * @param key The message key + * + * @param key + * The message key */ - void addMessages(String 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(); + int getMessagesBundleCount(); /** - * Gets this messages bundle group name. That is the name, which is used - * for the tab of the MultiPageEditorPart. + * 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); - - /** - * Renames a key in all messages bundles forming this group. - * - * @param sourceKey the message key to rename - * @param targetKey the new message name - */ - void renameMessageKeys(String sourceKey, String targetKey); + 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); + + /** + * Renames a key in all messages bundles forming this group. + * + * @param sourceKey + * the message key to rename + * @param targetKey + * the new message name + */ + void renameMessageKeys(String sourceKey, String targetKey); } 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 index 70f8650d..172e2550 100644 --- 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 @@ -20,11 +20,11 @@ */ public interface IMessagesResourceChangeListener { - /** - * Method called when the messages resource has changed. - * - * @param resource - * the resource that changed - */ - void resourceChanged(IMessagesResource resource); + /** + * 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/checks/IMessageCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java index 39aa54bc..41fc1d8d 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 @@ -16,18 +16,22 @@ import org.eclipse.babel.core.message.internal.MessagesBundleGroup; /** - * All purpose {@link Message} testing. Use this interface to establish - * whether a message within a {@link MessagesBundleGroup} is answering - * successfully to any condition. + * 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 - */ + /** + * 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.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 index e6860aa3..7ef4cd1c 100644 --- 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 @@ -21,36 +21,37 @@ /** * 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; + duplicateKeys = null; } - public boolean checkKey( - IMessagesBundleGroup messagesBundleGroup, IMessage message) { + public boolean checkKey(IMessagesBundleGroup messagesBundleGroup, + IMessage message) { Collection<String> keys = new ArrayList<String>(); if (message != null) { - IMessagesBundle messagesBundle = - messagesBundleGroup.getMessagesBundle(message.getLocale()); + IMessagesBundle messagesBundle = messagesBundleGroup + .getMessagesBundle(message.getLocale()); for (IMessage duplicateEntry : messagesBundle.getMessages()) { if (!message.getKey().equals(duplicateEntry.getKey()) - && BabelUtils.equals(message.getValue(), - duplicateEntry.getValue())) { + && BabelUtils.equals(message.getValue(), + duplicateEntry.getValue())) { keys.add(duplicateEntry.getKey()); } } @@ -59,12 +60,12 @@ public boolean checkKey( } } - duplicateKeys = keys.toArray(new String[]{}); + 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 index ef297bdc..6c613255 100644 --- 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 @@ -15,15 +15,16 @@ 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. + * 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(); - + /** The singleton */ + public static MissingValueCheck MISSING_KEY = new MissingValueCheck(); + /** * Constructor. */ @@ -32,12 +33,11 @@ private MissingValueCheck() { } /** - * @see org.eclipse.babel.core.message.internal.checks.IMessageCheck#checkKey( - * org.eclipse.babel.core.message.internal.MessagesBundleGroup, - * org.eclipse.babel.core.message.internal.Message) + * @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) { + public boolean checkKey(IMessagesBundleGroup messagesBundleGroup, + IMessage message) { if (message == null || message.getValue() == null || message.getValue().length() == 0) { return true; 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 index 437b6b95..6b6563ae 100644 --- 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 @@ -20,16 +20,16 @@ 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. */ @@ -39,26 +39,26 @@ public SimilarValueCheck(IProximityAnalyzer 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) + * @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) { + public boolean checkKey(IMessagesBundleGroup messagesBundleGroup, + IMessage message) { Collection<String> keys = new ArrayList<String>(); if (message != null) { - //TODO have case as preference + // TODO have case as preference String value1 = message.getValue().toLowerCase(); - IMessagesBundle messagesBundle = - messagesBundleGroup.getMessagesBundle(message.getLocale()); + 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 + // TODO have preference to report identical as similar if (!BabelUtils.equals(value1, value2) && analyzer.analyse(value1, value2) >= 0.75) { - //TODO use preferences -// >= RBEPreferences.getReportSimilarValuesPrecision()) { + // TODO use preferences + // >= RBEPreferences.getReportSimilarValuesPrecision()) + // { keys.add(similarEntry.getKey()); } } @@ -67,12 +67,13 @@ public boolean checkKey( keys.add(message.getKey()); } } - similarKeys = keys.toArray(new String[]{}); + similarKeys = keys.toArray(new String[] {}); return !keys.isEmpty(); } - + /** * Gets similar keys. + * * @return similar keys */ public String[] getSimilarMessageKeys() { diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java index a54d609f..aa0ac6fc 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java @@ -12,18 +12,21 @@ /** * 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. + * 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) + * @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.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java index 891381df..4b86c745 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java @@ -10,53 +10,56 @@ ******************************************************************************/ package org.eclipse.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>). + * 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(); - + private static final IProximityAnalyzer INSTANCE = new LevenshteinDistanceAnalyzer(); + /** * Constructor. */ private LevenshteinDistanceAnalyzer() { - //TODO add case sensitivity? + // 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) { + 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 + * + * @param a + * first value + * @param b + * second value + * @param c + * third value * @return lowest value */ private int minimum(int a, int b, int c) { @@ -75,8 +78,11 @@ private int minimum(int a, int b, int c) { /*** * Compute the distance - * @param s source string - * @param t target string + * + * @param s + * source string + * @param t + * target string * @return distance */ public int distance(String s, String t) { diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java index 32703378..f035cee5 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java @@ -15,28 +15,29 @@ 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. + * 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$ + private static final String WORD_SPLIT_PATTERN = "\r\n|\r|\n|\\s"; //$NON-NLS-1$ /** * Constructor. */ private WordCountAnalyzer() { - //TODO add case sensitivity? + // TODO add case sensitivity? super(); } /** * Gets the unique instance. + * * @return a proximity analyzer */ public static IProximityAnalyzer getInstance() { @@ -45,19 +46,19 @@ public static IProximityAnalyzer getInstance() { /** * @see com.essiembre.eclipse.rbe.model.utils.IProximityAnalyzer - * #analyse(java.lang.Object, java.lang.Object) + * #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))); - + 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)) { 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 index ecfc44df..7065bd0a 100644 --- 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 @@ -15,75 +15,81 @@ 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. + * 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); - } + /** + * 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 index 474786d4..990e9c4b 100644 --- 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 @@ -19,13 +19,12 @@ 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>. - * + * 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]) */ @@ -34,13 +33,15 @@ public abstract class AbstractMessageModel implements Serializable { private transient PropertyChangeSupport changeSupport; /** - * Adds a PropertyChangeListener to the listener list. The listener is - * registered for all properties of this class.<p> + * 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 + * @param listener + * the PropertyChangeListener to be added */ - /*default*/ final synchronized void addPropertyChangeListener( + /* default */final synchronized void addPropertyChangeListener( final PropertyChangeListener listener) { if (listener == null) { return; @@ -53,13 +54,15 @@ public abstract class AbstractMessageModel implements Serializable { /** * 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> + * 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 + * + * @param listener + * the PropertyChangeListener to be removed */ - /*default*/ final synchronized void removePropertyChangeListener( + /* default */final synchronized void removePropertyChangeListener( final PropertyChangeListener listener) { if (listener == null || changeSupport == null) { return; @@ -68,15 +71,14 @@ public abstract class AbstractMessageModel implements Serializable { } /** - * 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 + * 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() { + /* default */final synchronized PropertyChangeListener[] getPropertyChangeListeners() { if (changeSupport == null) { return new PropertyChangeListener[0]; } @@ -84,19 +86,20 @@ PropertyChangeListener[] 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 + * 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 + * + * @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) { + protected final void firePropertyChange(final String propertyName, + final Object oldValue, final Object newValue) { if (changeSupport == null || !DirtyHack.isFireEnabled()) { return; } @@ -104,19 +107,20 @@ protected final void firePropertyChange( } /** - * 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 + * 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 + * + * @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) { + protected final void firePropertyChange(final String propertyName, + final boolean oldValue, final boolean newValue) { if (changeSupport == null || !DirtyHack.isFireEnabled()) { return; } @@ -124,71 +128,74 @@ protected final void firePropertyChange( } /** - * 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 + * 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 + * + * @param event + * the event that triggered the change */ - protected final void firePropertyChange( - final PropertyChangeEvent event) { + 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 + * 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 + * + * @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)); + 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 + * 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 + * + * @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)); + 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 + * 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 + * + * @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) { + protected final void firePropertyChange(final String propertyName, + final int oldValue, final int newValue) { if (changeSupport == null || !DirtyHack.isFireEnabled()) { return; } @@ -196,31 +203,33 @@ protected final void firePropertyChange( } /** - * 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 + * 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 + * + * @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)); + 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 + * 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 index 1bf9948f..2328b048 100644 --- 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 @@ -14,6 +14,7 @@ /** * A listener for changes on a {@link MessagesBundleGroup}. + * * @author Pascal Essiembre ([email protected]) * @see MessagesBundleGroup */ @@ -21,29 +22,43 @@ public interface IMessagesBundleGroupListener extends IMessagesBundleListener { /** * A message key has been added. - * @param key the added key + * + * @param key + * the added key */ void keyAdded(String key); + /** * A message key has been removed. - * @param key the removed key + * + * @param key + * the removed key */ void keyRemoved(String key); + /** * A messages bundle has been added. - * @param messagesBundle the messages bundle + * + * @param messagesBundle + * the messages bundle */ void messagesBundleAdded(MessagesBundle messagesBundle); + /** * A messages bundle has been removed. - * @param messagesBundle the messages bundle + * + * @param messagesBundle + * the messages bundle */ void messagesBundleRemoved(MessagesBundle messagesBundle); + /** * A messages bundle was modified. - * @param messagesBundle the messages bundle + * + * @param messagesBundle + * the messages bundle */ - void messagesBundleChanged( - MessagesBundle messagesBundle, PropertyChangeEvent changeEvent); + 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 index 76a3fb36..1f430e76 100644 --- 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 @@ -15,29 +15,39 @@ /** * 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 + * + * @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 + * + * @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 + * + * @param messagesBundle + * the messages bundle on which the message was changed. + * @param message + * the message */ - void messageChanged( - MessagesBundle messagesBundle, PropertyChangeEvent changeEvent); + 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 index cba200a4..0bee1bc6 100644 --- 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 @@ -44,9 +44,12 @@ public final class Message extends AbstractMessageModel implements IMessage { 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 + * 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(); @@ -54,33 +57,35 @@ public Message(final String key, final Locale locale) { this.locale = locale; } - - /** * Sets the message comment. - * @param comment The comment to set. + * + * @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); + 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. + * 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; @@ -90,40 +95,46 @@ public void setActive(boolean active) { /** * Sets the actual message text. - * @param text The text to set. + * + * @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); + firePropertyChange(PROPERTY_TEXT, oldValue, text); } } /** - * Gets the comment associated with this message (<code>null</code> if - * no comments). + * 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() { @@ -132,24 +143,26 @@ public String getValue() { /** * 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. + * 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) { @@ -166,32 +179,32 @@ public boolean equals(Object obj) { 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); + 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$ + 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$ + + "]]"; //$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 index 5ef6454a..5961cfe2 100644 --- 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 @@ -11,7 +11,8 @@ package org.eclipse.babel.core.message.internal; /** - * Exception thrown when a message-related operation raised a problem. + * Exception thrown when a message-related operation raised a problem. + * * @author Pascal Essiembre ([email protected]) */ public class MessageException extends RuntimeException { @@ -28,7 +29,9 @@ public MessageException() { /** * Creates a new <code>MessageException</code>. - * @param message exception message + * + * @param message + * exception message */ public MessageException(String message) { super(message); @@ -36,8 +39,11 @@ public MessageException(String message) { /** * Creates a new <code>MessageException</code>. - * @param message exception message - * @param cause root cause + * + * @param message + * exception message + * @param cause + * root cause */ public MessageException(String message, Throwable cause) { super(message, cause); @@ -45,7 +51,9 @@ public MessageException(String message, Throwable cause) { /** * Creates a new <code>MessageException</code>. - * @param cause root cause + * + * @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 index 9473955f..21a4cdba 100644 --- 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 @@ -28,44 +28,43 @@ import org.eclipse.babel.core.util.BabelUtils; /** - * For a given scope, all messages for a national language. + * For a given scope, all messages for a national language. + * * @author Pascal Essiembre ([email protected]) */ -public class MessagesBundle extends AbstractMessageModel - implements IMessagesResourceChangeListener, IMessagesBundle { +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$ + public static final String PROPERTY_MESSAGES_COUNT = "messagesCount"; //$NON-NLS-1$ - private static final IMessagesBundleListener[] EMPTY_MSG_BUNDLE_LISTENERS = - new IMessagesBundleListener[] {}; + 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 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 + * + * @param resource + * the messages bundle resource */ public MessagesBundle(IMessagesResource resource) { super(); this.resource = resource; readFromResource(); // Handle resource changes - resource.addMessagesResourceChangeListener( - new IMessagesResourceChangeListener(){ + resource.addMessagesResourceChangeListener(new IMessagesResourceChangeListener() { public void resourceChanged(IMessagesResource changedResource) { readFromResource(); } @@ -76,6 +75,7 @@ public void messageChanged(MessagesBundle messagesBundle, PropertyChangeEvent changeEvent) { writetoResource(); } + public void propertyChange(PropertyChangeEvent evt) { writetoResource(); } @@ -86,24 +86,26 @@ public void propertyChange(PropertyChangeEvent evt) { * Called before this object will be discarded. */ public void dispose() { - this.resource.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). + * Gets the locale for the messages bundle (<code>null</code> assumes the + * default system locale). + * * @return Returns the locale. */ public Locale getLocale() { @@ -112,6 +114,7 @@ public Locale getLocale() { /** * Gets the overall comment, or description, for this messages bundle.. + * * @return Returns the comment. */ public String getComment() { @@ -120,7 +123,9 @@ public String getComment() { /** * Sets the comment for this messages bundle. - * @param comment The comment to set. + * + * @param comment + * The comment to set. */ public void setComment(String comment) { Object oldValue = this.comment; @@ -130,17 +135,18 @@ public void setComment(String comment) { /** * @see org.eclipse.babel.core.message.resource - * .IMessagesResourceChangeListener#resourceChanged( - * org.eclipse.babel.core.message.internal.resource.IMessagesResource) + * .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 + * 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; @@ -151,8 +157,8 @@ public void addMessage(IMessage message) { if (!keyedMessages.containsKey(m.getKey())) { keyedMessages.put(m.getKey(), m); m.addMessageListener(messageListener); - firePropertyChange( - PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount()); + firePropertyChange(PROPERTY_MESSAGES_COUNT, oldCount, + getMessagesCount()); fireMessageAdded(m); } else { // Entry already exists, update it. @@ -160,9 +166,12 @@ public void addMessage(IMessage message) { matchingEntry.copyFrom(m); } } + /** * Removes a message from this messages bundle. - * @param messageKey the key of the message to remove + * + * @param messageKey + * the key of the message to remove */ public void removeMessage(String messageKey) { int oldCount = getMessagesCount(); @@ -171,31 +180,36 @@ public void removeMessage(String messageKey) { if (message != null) { message.removePropertyChangeListener(messageListener); keyedMessages.remove(messageKey); - firePropertyChange( - PROPERTY_MESSAGES_COUNT, oldCount, getMessagesCount()); + 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 + * 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); - + removeMessage(messageKey); + // add parent key int index = messageKey.lastIndexOf("."); messageKey = (index == -1 ? "" : messageKey.substring(0, index)); - - if (! messageKey.isEmpty()) - addMessage(new Message(messageKey, getLocale())); + + if (!messageKey.isEmpty()) + addMessage(new Message(messageKey, getLocale())); } - + /** * Removes messages from this messages bundle. - * @param messageKeys the keys of the messages to remove + * + * @param messageKeys + * the keys of the messages to remove */ public void removeMessages(String[] messageKeys) { for (int i = 0; i < messageKeys.length; i++) { @@ -205,14 +219,18 @@ public void removeMessages(String[] messageKeys) { /** * 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 + * + * @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$ + "Cannot rename: target key already exists."); //$NON-NLS-1$ } IMessage sourceEntry = getMessage(sourceKey); if (sourceEntry != null) { @@ -222,16 +240,21 @@ public void renameMessageKey(String sourceKey, String targetKey) { 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 + * + * @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$ + "Cannot duplicate: target key already exists."); //$NON-NLS-1$ } IMessage sourceEntry = getMessage(sourceKey); if (sourceEntry != null) { @@ -243,7 +266,9 @@ public void duplicateMessage(String sourceKey, String targetKey) { /** * Gets a message. - * @param key a message key + * + * @param key + * a message key * @return a message */ public IMessage getMessage(String key) { @@ -252,7 +277,9 @@ public IMessage getMessage(String key) { /** * Adds an empty message. - * @param key the new message key + * + * @param key + * the new message key */ public void addMessage(String key) { addMessage(new Message(key, getLocale())); @@ -260,14 +287,16 @@ public void addMessage(String key) { /** * 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() { @@ -279,8 +308,8 @@ public Collection<IMessage> getMessages() { */ public String toString() { String str = "MessagesBundle=[[locale=" + getLocale() //$NON-NLS-1$ - + "][comment=" + comment //$NON-NLS-1$ - + "][entries="; //$NON-NLS-1$ + + "][comment=" + comment //$NON-NLS-1$ + + "][entries="; //$NON-NLS-1$ for (IMessage message : getMessages()) { str += message.toString(); } @@ -295,14 +324,14 @@ 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()); + 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; } @@ -315,33 +344,33 @@ public boolean equals(Object obj) { } MessagesBundle messagesBundle = (MessagesBundle) obj; return equals(comment, messagesBundle.comment) - && equals(keyedMessages, messagesBundle.keyedMessages); - } + && 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); + + 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++) { @@ -349,6 +378,7 @@ private void fireMessageAdded(Message message) { listener.messageAdded(this, message); } } + private void fireMessageRemoved(Message message) { IMessagesBundleListener[] listeners = getMessagesBundleListeners(); for (int i = 0; i < listeners.length; i++) { @@ -356,6 +386,7 @@ private void fireMessageRemoved(Message message) { listener.messageRemoved(this, message); } } + private void fireMessageChanged(PropertyChangeEvent event) { IMessagesBundleListener[] listeners = getMessagesBundleListeners(); for (int i = 0; i < listeners.length; i++) { @@ -363,11 +394,13 @@ private void fireMessageChanged(PropertyChangeEvent event) { 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. + * 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) { 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 index 971e5e67..3c9059ca 100644 --- 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 @@ -13,40 +13,42 @@ import java.beans.PropertyChangeEvent; /** - * An adapter class for a {@link IMessagesBundleListener}. Methods + * 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) + * @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) + * 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) + * org.eclipse.babel.core.message.internal.Message) */ public void messageRemoved(MessagesBundle messagesBundle, Message message) { // do nothing } + /** - * @see java.beans.PropertyChangeListener#propertyChange( - * java.beans.PropertyChangeEvent) + * @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 index b6d6d62c..68c37357 100644 --- 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 @@ -38,7 +38,7 @@ * @author Pascal Essiembre ([email protected]) */ public class MessagesBundleGroup extends AbstractMessageModel implements - IMessagesBundleGroup { + IMessagesBundleGroup { private String projectName; @@ -67,24 +67,24 @@ public class MessagesBundleGroup extends AbstractMessageModel implements * a IMessagesBundleGroupStrategy instance */ public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) { - super(); - this.groupStrategy = groupStrategy; - this.name = groupStrategy.createMessagesBundleGroupName(); - this.resourceBundleId = groupStrategy.createMessagesBundleId(); + super(); + this.groupStrategy = groupStrategy; + this.name = groupStrategy.createMessagesBundleGroupName(); + this.resourceBundleId = groupStrategy.createMessagesBundleId(); - this.projectName = groupStrategy.getProjectName(); + this.projectName = groupStrategy.getProjectName(); - MessagesBundle[] bundles = groupStrategy.loadMessagesBundles(); - if (bundles != null) { - for (int i = 0; i < bundles.length; i++) { - addMessagesBundle(bundles[i]); - } - } + MessagesBundle[] bundles = groupStrategy.loadMessagesBundles(); + if (bundles != null) { + for (int i = 0; i < bundles.length; i++) { + addMessagesBundle(bundles[i]); + } + } - if (this.projectName != null) { - RBManager.getInstance(this.projectName) - .notifyMessagesBundleGroupCreated(this); - } + if (this.projectName != null) { + RBManager.getInstance(this.projectName) + .notifyMessagesBundleGroupCreated(this); + } } /** @@ -93,20 +93,20 @@ public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) { */ @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); + 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); } /** @@ -118,7 +118,7 @@ public void dispose() { */ @Override public IMessagesBundle getMessagesBundle(Locale locale) { - return localeBundles.get(locale); + return localeBundles.get(locale); } /** @@ -133,13 +133,13 @@ public IMessagesBundle getMessagesBundle(Locale locale) { * @see IMessagesResource */ public MessagesBundle getMessagesBundle(Object source) { - for (IMessagesBundle messagesBundle : getMessagesBundles()) { - if (equals(source, ((MessagesBundle) messagesBundle).getResource() - .getSource())) { - return (MessagesBundle) messagesBundle; - } - } - return null; + for (IMessagesBundle messagesBundle : getMessagesBundles()) { + if (equals(source, ((MessagesBundle) messagesBundle).getResource() + .getSource())) { + return (MessagesBundle) messagesBundle; + } + } + return null; } /** @@ -150,14 +150,14 @@ public MessagesBundle getMessagesBundle(Object source) { * locale for the new bundle added */ public void addMessagesBundle(Locale locale) { - addMessagesBundle(groupStrategy.createMessagesBundle(locale)); + addMessagesBundle(groupStrategy.createMessagesBundle(locale)); } /** * Gets all locales making up this messages bundle group. */ public Locale[] getLocales() { - return localeBundles.keySet().toArray(EMPTY_LOCALES); + return localeBundles.keySet().toArray(EMPTY_LOCALES); } /** @@ -169,14 +169,14 @@ public Locale[] getLocales() { */ @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); + 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); } /** @@ -190,106 +190,107 @@ public IMessage[] getMessages(String key) { */ @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) { - MessagesBundle mb = (MessagesBundle) messagesBundle; - if (localeBundles.containsKey(mb.getLocale())) { - int oldBundleCount = localeBundles.size(); - - localeBundles.remove(mb.getLocale()); - firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount, - localeBundles.size()); - fireMessagesBundleRemoved(mb); - } - - // 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 - int oldKeyCount = keys.size(); - keys.remove(keyToRemove); - firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size()); - fireKeyRemoved(keyToRemove); - } - } - } - - - public void removeMessagesBundle(Locale locale) { - removeMessagesBundle(getMessagesBundle(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) { + MessagesBundle mb = (MessagesBundle) messagesBundle; + if (localeBundles.containsKey(mb.getLocale())) { + int oldBundleCount = localeBundles.size(); + + localeBundles.remove(mb.getLocale()); + firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount, + localeBundles.size()); + fireMessagesBundleRemoved(mb); + } + + // 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 + int oldKeyCount = keys.size(); + keys.remove(keyToRemove); + firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size()); + fireKeyRemoved(keyToRemove); + } + } + } + + public void removeMessagesBundle(Locale locale) { + removeMessagesBundle(getMessagesBundle(locale)); + } /** * Gets this messages bundle group name. That is the name, which is used for @@ -299,7 +300,7 @@ public void removeMessagesBundle(Locale locale) { */ @Override public String getName() { - return name; + return name; } /** @@ -311,9 +312,9 @@ public String getName() { */ @Override public void addMessages(String key) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - ((MessagesBundle) msgBundle).addMessage(key); - } + for (IMessagesBundle msgBundle : localeBundles.values()) { + ((MessagesBundle) msgBundle).addMessage(key); + } } /** @@ -325,9 +326,9 @@ public void addMessages(String key) { * the new message name */ public void renameMessageKeys(String sourceKey, String targetKey) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - msgBundle.renameMessageKey(sourceKey, targetKey); - } + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.renameMessageKey(sourceKey, targetKey); + } } /** @@ -338,9 +339,9 @@ public void renameMessageKeys(String sourceKey, String targetKey) { */ @Override public void removeMessages(String key) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - msgBundle.removeMessage(key); - } + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.removeMessage(key); + } } /** @@ -352,9 +353,9 @@ public void removeMessages(String key) { */ @Override public void removeMessagesAddParentKey(String key) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - msgBundle.removeMessageAddParentKey(key); - } + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.removeMessageAddParentKey(key); + } } /** @@ -364,12 +365,12 @@ public void removeMessagesAddParentKey(String 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); - } - } + for (IMessagesBundle msgBundle : localeBundles.values()) { + IMessage entry = msgBundle.getMessage(key); + if (entry != null) { + entry.setActive(active); + } + } } /** @@ -384,12 +385,12 @@ public void setMessagesActive(String key, boolean active) { * 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); - } + if (sourceKey.equals(targetKey)) { + return; + } + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.duplicateMessage(sourceKey, targetKey); + } } /** @@ -399,7 +400,7 @@ public void duplicateMessages(String sourceKey, String targetKey) { */ @Override public Collection<IMessagesBundle> getMessagesBundles() { - return localeBundles.values(); + return localeBundles.values(); } /** @@ -409,7 +410,7 @@ public Collection<IMessagesBundle> getMessagesBundles() { */ @Override public String[] getMessageKeys() { - return keys.toArray(BabelUtils.EMPTY_STRINGS); + return keys.toArray(BabelUtils.EMPTY_STRINGS); } /** @@ -421,7 +422,7 @@ public String[] getMessageKeys() { */ @Override public boolean isMessageKey(String key) { - return keys.contains(key); + return keys.contains(key); } /** @@ -431,7 +432,7 @@ public boolean isMessageKey(String key) { */ @Override public int getMessagesBundleCount() { - return localeBundles.size(); + return localeBundles.size(); } /** @@ -439,59 +440,59 @@ public int getMessagesBundleCount() { */ @Override public boolean equals(Object obj) { - if (!(obj instanceof MessagesBundleGroup)) { - return false; - } - MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj; - return equals(localeBundles, messagesBundleGroup.localeBundles); + 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); + final IMessagesBundleGroupListener listener) { + addPropertyChangeListener(listener); } public final synchronized void removeMessagesBundleGroupListener( - final IMessagesBundleGroupListener listener) { - removePropertyChangeListener(listener); + 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); + // 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); - } + 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); - } + 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); - } + 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); - } + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.messagesBundleRemoved(messagesBundle); + } } /** @@ -504,17 +505,17 @@ private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) { */ @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; + 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; } /** @@ -526,7 +527,7 @@ public boolean containsKey(String key) { */ @Override public boolean isKey(String key) { - return keys.contains(key); + return keys.contains(key); } /** @@ -538,7 +539,7 @@ public boolean isKey(String key) { */ @Override public String getResourceBundleId() { - return resourceBundleId; + return resourceBundleId; } /** @@ -548,7 +549,7 @@ public String getResourceBundleId() { */ @Override public String getProjectName() { - return this.projectName; + return this.projectName; } /** @@ -556,69 +557,70 @@ public String getProjectName() { * 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; - } + @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 index fa654b19..edbc9e85 100644 --- 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 @@ -3,26 +3,28 @@ import java.beans.PropertyChangeEvent; /** - * An adapter class for a {@link IMessagesBundleGroupListener}. Methods + * An adapter class for a {@link IMessagesBundleGroupListener}. Methods * implementation do nothing. + * * @author Pascal Essiembre ([email protected]) */ -public class MessagesBundleGroupAdapter - implements IMessagesBundleGroupListener { +public class MessagesBundleGroupAdapter implements IMessagesBundleGroupListener { /** * @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener# - * keyAdded(java.lang.String) + * keyAdded(java.lang.String) */ public void keyAdded(String key) { // do nothing } + /** * @see org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener# - * keyRemoved(java.lang.String) + * 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) @@ -30,50 +32,54 @@ public void keyRemoved(String key) { 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) + * 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) + * #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) + * @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) + * 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) + * org.eclipse.babel.core.message.internal.Message) */ public void messageRemoved(MessagesBundle messagesBundle, Message message) { // do nothing } + /** - * @see java.beans.PropertyChangeListener#propertyChange( - * java.beans.PropertyChangeEvent) + * @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 9ab5b378..2455a890 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 @@ -13,28 +13,29 @@ import org.eclipse.babel.core.message.IMessagesBundle; /** - * Used to sync TapiJI with Babel and vice versa. - * <br><br> + * 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() - + /** + * 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 index 15b18db6..a0a7bdae 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java @@ -13,26 +13,30 @@ 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> + * 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); - + /** + * 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 542b83dc..ba1c391f 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 @@ -68,14 +68,14 @@ public class RBManager { private static final String TAPIJI_NATURE = "org.eclipse.babel.tapiji.tools.core.ui.nature"; private static Logger logger = Logger.getLogger(RBManager.class - .getSimpleName()); + .getSimpleName()); private static IRefactoringService refactorService; - + private RBManager() { - resourceBundles = new HashMap<String, IMessagesBundleGroup>(); - editorListeners = new ArrayList<IMessagesEditorListener>(3); - resourceListeners = new ArrayList<IResourceDeltaListener>(2); + resourceBundles = new HashMap<String, IMessagesBundleGroup>(); + editorListeners = new ArrayList<IMessagesEditorListener>(3); + resourceListeners = new ArrayList<IResourceDeltaListener>(2); } /** @@ -84,14 +84,14 @@ private RBManager() { * @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(resourceBundleId); - } + if (!resourceBundles.containsKey(resourceBundleId)) { + logger.log(Level.SEVERE, + "getMessagesBundleGroup with non-existing Id: " + + resourceBundleId); + return null; + } else { + return resourceBundles.get(resourceBundleId); + } } /** @@ -99,12 +99,12 @@ public IMessagesBundleGroup getMessagesBundleGroup(String resourceBundleId) { * <projectName>/<resourceBundleId> */ public List<String> getMessagesBundleGroupNames() { - List<String> bundleGroupNames = new ArrayList<String>(); + List<String> bundleGroupNames = new ArrayList<String>(); - for (String key : resourceBundles.keySet()) { - bundleGroupNames.add(project.getName() + "/" + key); - } - return bundleGroupNames; + for (String key : resourceBundles.keySet()) { + bundleGroupNames.add(project.getName() + "/" + key); + } + return bundleGroupNames; } /** @@ -112,17 +112,17 @@ public List<String> getMessagesBundleGroupNames() { * projects. */ public static List<String> getAllMessagesBundleGroupNames() { - List<String> bundleGroupNames = new ArrayList<String>(); - - for (IProject project : getAllSupportedProjects()) { - RBManager manager = getInstance(project); - for (String name : manager.getMessagesBundleGroupNames()) { - if (!bundleGroupNames.contains(name)) { - bundleGroupNames.add(name); - } - } - } - return bundleGroupNames; + List<String> bundleGroupNames = new ArrayList<String>(); + + for (IProject project : getAllSupportedProjects()) { + RBManager manager = getInstance(project); + for (String name : manager.getMessagesBundleGroupNames()) { + if (!bundleGroupNames.contains(name)) { + bundleGroupNames.add(name); + } + } + } + return bundleGroupNames; } /** @@ -133,74 +133,74 @@ public static List<String> getAllMessagesBundleGroupNames() { * The new {@link IMessagesBundleGroup} */ public void notifyMessagesBundleGroupCreated( - IMessagesBundleGroup bundleGroup) { - if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) { - IMessagesBundleGroup oldbundleGroup = resourceBundles - .get(bundleGroup.getResourceBundleId()); - - // not the same object - if (!equalHash(oldbundleGroup, bundleGroup)) { - // 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); - - 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 - // do not need -> read only phenomenon - 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 - logger.log(Level.INFO, - "dispose: " + bundleGroup.getResourceBundleId()); - - bundleGroup.dispose(); - } - } - } else { - resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup); - - logger.log(Level.INFO, "add: " + bundleGroup.getResourceBundleId()); - } + IMessagesBundleGroup bundleGroup) { + if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) { + IMessagesBundleGroup oldbundleGroup = resourceBundles + .get(bundleGroup.getResourceBundleId()); + + // not the same object + if (!equalHash(oldbundleGroup, bundleGroup)) { + // 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); + + 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 + // do not need -> read only phenomenon + 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 + logger.log(Level.INFO, + "dispose: " + bundleGroup.getResourceBundleId()); + + bundleGroup.dispose(); + } + } + } else { + resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup); + + logger.log(Level.INFO, "add: " + bundleGroup.getResourceBundleId()); + } } /** @@ -210,18 +210,18 @@ public void notifyMessagesBundleGroupCreated( * The {@link IMessagesBundleGroup} to remove */ public void notifyMessagesBundleGroupDeleted( - IMessagesBundleGroup bundleGroup) { - if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) { - if (equalHash( - resourceBundles.get(bundleGroup.getResourceBundleId()), - bundleGroup)) { - resourceBundles.remove(bundleGroup.getResourceBundleId()); - - for (IResourceDeltaListener deltaListener : resourceListeners) { - deltaListener.onDelete(bundleGroup); - } - } - } + IMessagesBundleGroup bundleGroup) { + if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) { + if (equalHash( + resourceBundles.get(bundleGroup.getResourceBundleId()), + bundleGroup)) { + resourceBundles.remove(bundleGroup.getResourceBundleId()); + + for (IResourceDeltaListener deltaListener : resourceListeners) { + deltaListener.onDelete(bundleGroup); + } + } + } } /** @@ -232,31 +232,31 @@ public void notifyMessagesBundleGroupDeleted( * The removed {@link MessagesBundle} */ public void notifyResourceRemoved(IResource resourceBundle) { - String resourceBundleId = NameUtils.getResourceBundleId(resourceBundle); + String resourceBundleId = NameUtils.getResourceBundleId(resourceBundle); - IMessagesBundleGroup bundleGroup = resourceBundles - .get(resourceBundleId); + IMessagesBundleGroup bundleGroup = resourceBundles + .get(resourceBundleId); - if (bundleGroup != null) { - Locale locale = NameUtils.getLocaleByName( - NameUtils.getResourceBundleName(resourceBundle), - resourceBundle.getName()); - IMessagesBundle messagesBundle = bundleGroup - .getMessagesBundle(locale); - if (messagesBundle != null) { - bundleGroup.removeMessagesBundle(messagesBundle); - } + if (bundleGroup != null) { + 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); - } + for (IResourceDeltaListener deltaListener : resourceListeners) { + deltaListener.onDelete(resourceBundleId, resourceBundle); + } - if (bundleGroup.getMessagesBundleCount() == 0) { - notifyMessagesBundleGroupDeleted(bundleGroup); - } - } + if (bundleGroup.getMessagesBundleCount() == 0) { + notifyMessagesBundleGroupDeleted(bundleGroup); + } + } - // TODO: maybe save and reinit the editor? + // TODO: maybe save and reinit the editor? } @@ -272,8 +272,8 @@ public void notifyResourceRemoved(IResource resourceBundle) { * <code>false</code> */ private boolean equalHash(IMessagesBundleGroup oldBundleGroup, - IMessagesBundleGroup newBundleGroup) { - return oldBundleGroup.hashCode() == newBundleGroup.hashCode(); + IMessagesBundleGroup newBundleGroup) { + return oldBundleGroup.hashCode() == newBundleGroup.hashCode(); } /** @@ -287,68 +287,68 @@ private boolean equalHash(IMessagesBundleGroup oldBundleGroup, * 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 - - 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); + 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); } @@ -359,14 +359,14 @@ private void syncBundles(IMessagesBundleGroup oldBundleGroup, * The resourceBundleId */ public void deleteMessagesBundleGroup(String resourceBundleId) { - // TODO: Try to unify it some time - if (resourceBundles.containsKey(resourceBundleId)) { - resourceBundles.remove(resourceBundleId); - } else { - logger.log(Level.SEVERE, - "deleteMessagesBundleGroup with non-existing Id: " - + resourceBundleId); - } + // TODO: Try to unify it some time + if (resourceBundles.containsKey(resourceBundleId)) { + resourceBundles.remove(resourceBundleId); + } else { + logger.log(Level.SEVERE, + "deleteMessagesBundleGroup with non-existing Id: " + + resourceBundleId); + } } /** @@ -376,7 +376,7 @@ public void deleteMessagesBundleGroup(String resourceBundleId) { * {@link MessagesBundleGroup} with the id resourceBundleId */ public boolean containsMessagesBundleGroup(String resourceBundleId) { - return resourceBundles.containsKey(resourceBundleId); + return resourceBundles.containsKey(resourceBundleId); } /** @@ -385,23 +385,23 @@ public boolean containsMessagesBundleGroup(String resourceBundleId) { * @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); - } - - INSTANCE = managerMap.get(project); - - if (INSTANCE == null) { - INSTANCE = new RBManager(); - INSTANCE.project = project; - managerMap.put(project, INSTANCE); - INSTANCE.detectResourceBundles(); - - refactorService = getRefactoringService(); - } - - return INSTANCE; + // 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(); + + refactorService = getRefactoringService(); + } + + return INSTANCE; } /** @@ -411,18 +411,18 @@ public static RBManager getInstance(IProject project) { * @return The corresponding {@link RBManager} to the project */ public static RBManager getInstance(String projectName) { - 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)) { - return getInstance(PDEUtils.getFragmentHost(project)); - } else { - return getInstance(project); - } - } - } - return null; + 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)) { + return getInstance(PDEUtils.getFragmentHost(project)); + } else { + return getInstance(project); + } + } + } + return null; } /** @@ -433,28 +433,28 @@ public static RBManager getInstance(String projectName) { * 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.isOpen() && (ignoreNature || p.hasNature(TAPIJI_NATURE))) { - projs.add(p); - } - } catch (CoreException e) { - logger.log(Level.SEVERE, - "getAllWorkspaceProjects(...): hasNature failed!", e); - } - } - return projs; + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() + .getProjects(); + Set<IProject> projs = new HashSet<IProject>(); + + for (IProject p : projects) { + try { + if (p.isOpen() && (ignoreNature || p.hasNature(TAPIJI_NATURE))) { + projs.add(p); + } + } catch (CoreException e) { + 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); + return getAllWorkspaceProjects(false); } /** @@ -462,7 +462,7 @@ public static Set<IProject> getAllSupportedProjects() { * {@link IMessagesEditorListener} to add */ public void addMessagesEditorListener(IMessagesEditorListener listener) { - this.editorListeners.add(listener); + this.editorListeners.add(listener); } /** @@ -470,7 +470,7 @@ public void addMessagesEditorListener(IMessagesEditorListener listener) { * {@link IMessagesEditorListener} to remove */ public void removeMessagesEditorListener(IMessagesEditorListener listener) { - this.editorListeners.remove(listener); + this.editorListeners.remove(listener); } /** @@ -478,7 +478,7 @@ public void removeMessagesEditorListener(IMessagesEditorListener listener) { * {@link IResourceDeltaListener} to add */ public void addResourceDeltaListener(IResourceDeltaListener listener) { - this.resourceListeners.add(listener); + this.resourceListeners.add(listener); } /** @@ -486,57 +486,57 @@ public void addResourceDeltaListener(IResourceDeltaListener listener) { * {@link IResourceDeltaListener} to remove */ public void removeResourceDeltaListener(IResourceDeltaListener listener) { - this.resourceListeners.remove(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"); + 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"); + 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()); - } + for (IMessagesEditorListener listener : this.editorListeners) { + listener.onResourceChanged(bundle); + logger.log(Level.INFO, "fireResourceChanged" + + bundle.getResource().getResourceLocationLabel()); + } } /** * 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) { - p.accept(new ResourceBundleDetectionVisitor(this)); - } - - } - } catch (CoreException e) { - logger.log(Level.SEVERE, "detectResourceBundles: accept failed!", e); - } + 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) { + logger.log(Level.SEVERE, "detectResourceBundles: accept failed!", e); + } } // passive loading -> see detectResourceBundles @@ -544,47 +544,47 @@ protected void 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 = 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()); - } + // 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 = 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 void writeToFile(IMessagesBundleGroup bundleGroup) { - for (IMessagesBundle bundle : bundleGroup.getMessagesBundles()) { - FileUtils.writeToFile(bundle); - fireResourceChanged(bundle); - } + for (IMessagesBundle bundle : bundleGroup.getMessagesBundles()) { + FileUtils.writeToFile(bundle); + fireResourceChanged(bundle); + } } - + private static IRefactoringService getRefactoringService() { - IExtensionPoint extp = Platform.getExtensionRegistry() - .getExtensionPoint( - "org.eclipse.babel.core" + ".refactoringService"); - IConfigurationElement[] elements = extp.getConfigurationElements(); - - if (elements.length != 0) { - try { - return (IRefactoringService) elements[0] - .createExecutableExtension("class"); - } catch (CoreException e) { - e.printStackTrace(); - } - } - return null; - } - - public static IRefactoringService getRefactorService() { - return refactorService; - } + IExtensionPoint extp = Platform.getExtensionRegistry() + .getExtensionPoint( + "org.eclipse.babel.core" + ".refactoringService"); + IConfigurationElement[] elements = extp.getConfigurationElements(); + + if (elements.length != 0) { + try { + return (IRefactoringService) elements[0] + .createExecutableExtension("class"); + } catch (CoreException e) { + e.printStackTrace(); + } + } + return null; + } + + public static IRefactoringService getRefactorService() { + return refactorService; + } } 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 892b8aa8..fdf3ac51 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 @@ -27,134 +27,134 @@ import org.eclipse.core.runtime.CoreException; public class ResourceBundleDetectionVisitor implements IResourceVisitor, - IResourceDeltaVisitor { + IResourceDeltaVisitor { private RBManager manager = null; public ResourceBundleDetectionVisitor(RBManager manager) { - this.manager = manager; + this.manager = manager; } public boolean visit(IResource resource) throws CoreException { - try { - if (isResourceBundleFile(resource)) { - manager.addBundleResource(resource); - return false; - } else - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } + try { + if (isResourceBundleFile(resource)) { + manager.addBundleResource(resource); + return false; + } else + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } } public boolean visit(IResourceDelta delta) throws CoreException { - IResource resource = delta.getResource(); + IResource resource = delta.getResource(); - if (isResourceBundleFile(resource)) { - // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); - return false; - } + if (isResourceBundleFile(resource)) { + // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); + return false; + } - return true; + return true; } 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")) { - 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; + 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(); - if (configuration != null) { - return convertStringToList(configuration.getNonRbPattern()); - } else { - return new ArrayList<CheckItem>(); - } + IConfiguration configuration = ConfigurationManager.getInstance() + .getConfiguration(); + if (configuration != null) { + return convertStringToList(configuration.getNonRbPattern()); + } else { + return new ArrayList<CheckItem>(); + } } 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; + 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; - } + 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; + boolean checked; + String name; - public CheckItem(String item, boolean checked) { - this.name = item; - this.checked = checked; - } + public CheckItem(String item, boolean checked) { + this.name = item; + this.checked = checked; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public boolean getChecked() { - return checked; - } + public boolean getChecked() { + return checked; + } } } 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 index ca16df44..fb839c49 100644 --- 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 @@ -24,63 +24,63 @@ */ public interface IMessagesResource { - /** - * Gets the resource locale. - * - * @return locale - */ - Locale getLocale(); + /** + * 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(); + /** + * 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); + /** + * 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); + /** + * 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); + /** + * 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); + /** + * Removes a messages resource listener. + * + * @param listener + * the listener + */ + void removeMessagesResourceChangeListener( + IMessagesResourceChangeListener listener); - /** - * @return The resource location label. or null if unknown. - */ - String getResourceLocationLabel(); + /** + * @return The resource location label. or null if unknown. + */ + String getResourceLocationLabel(); - /** - * Called when the group it belongs to is disposed. - */ - void dispose(); + /** + * 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/internal/AbstractMessagesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java index 95512f4c..8d48ce27 100644 --- 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 @@ -18,19 +18,22 @@ 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} + * 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 + * + * @param locale + * bound locale */ public AbstractMessagesResource(Locale locale) { super(); @@ -46,18 +49,17 @@ public Locale getLocale() { /** * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource# - * addMessagesResourceChangeListener( - * org.eclipse.babel.core.message.resource - * .IMessagesResourceChangeListener) + * 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) + * removeMessagesResourceChangeListener(org.eclipse.babel.core.message.resource.IMessagesResourceChangeListener) */ public void removeMessagesResourceChangeListener( IMessagesResourceChangeListener listener) { @@ -66,9 +68,11 @@ public void removeMessagesResourceChangeListener( /** * Fires notification that a {@link IMessagesResource} changed. - * @param resource {@link IMessagesResource} + * + * @param resource + * {@link IMessagesResource} */ - protected void fireResourceChange(IMessagesResource resource) { + 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 index 5b6b9fe0..13153830 100644 --- 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 @@ -17,38 +17,39 @@ 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. + * 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 { +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 + * + * @param locale + * properties locale + * @param serializer + * properties serializer + * @param deserializer + * properties deserializer */ - public AbstractPropertiesResource( - Locale locale, - PropertiesSerializer serializer, - PropertiesDeserializer deserializer) { + public AbstractPropertiesResource(Locale locale, + PropertiesSerializer serializer, PropertiesDeserializer deserializer) { super(locale); this.deserializer = deserializer; this.serializer = serializer; - //TODO initialises with configurations only... + // TODO initialises with configurations only... } /** - * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource#serialize( - * org.eclipse.babel.core.message.internal.MessagesBundle) + * @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)); @@ -56,7 +57,7 @@ public void serialize(IMessagesBundle messagesBundle) { /** * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource - * #deserialize(org.eclipse.babel.core.message.internal.MessagesBundle) + * #deserialize(org.eclipse.babel.core.message.internal.MessagesBundle) */ public void deserialize(IMessagesBundle messagesBundle) { deserializer.deserialize(messagesBundle, getText()); @@ -64,13 +65,17 @@ public void deserialize(IMessagesBundle messagesBundle) { /** * 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 + * + * @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 index bff9a1b7..cc382768 100644 --- 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 @@ -54,16 +54,16 @@ public class PropertiesFileResource extends AbstractPropertiesResource { * @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 + 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 } /** @@ -72,27 +72,27 @@ public PropertiesFileResource(Locale locale, */ @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(); + 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(); } /** @@ -101,33 +101,33 @@ public String getText() { */ @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(); - // } - } + 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(); + // } + } } /** @@ -136,7 +136,7 @@ public void setText(String content) { */ @Override public Object getSource() { - return file; + return file; } /** @@ -144,31 +144,31 @@ public Object getSource() { */ @Override public String getResourceLocationLabel() { - return file.getAbsolutePath(); + 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); - } - } + 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); - } - } + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + // TODO handle better. + throw new RuntimeException("Cannot close reader.", e); + } + } } /** @@ -177,16 +177,16 @@ public void closeReader(Reader reader) { */ @Override public void dispose() { - FileMonitor.getInstance().removeFileChangeListener( - this.fileChangeListener, file); + FileMonitor.getInstance().removeFileChangeListener( + this.fileChangeListener, file); } private class FileChangeListenerImpl implements FileChangeListener { - @Override - public void fileChanged(final File changedFile) { - fireResourceChange(PropertiesFileResource.this); - } + @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 index 68b6e6ce..058be453 100644 --- 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 @@ -26,11 +26,10 @@ 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}. + * 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 @@ -38,57 +37,63 @@ 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. + * + * @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, + public PropertiesIFileResource(Locale locale, PropertiesSerializer serializer, - PropertiesDeserializer deserializer, - IFile file, IFileChangeListenerRegistry listenerRegistry) { + 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. + + // [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); + 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; + fileListener = null; } } /** * @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource - * #getText() + * #getText() */ public String getText() { try { @@ -100,54 +105,52 @@ public String getText() { String content = new String(b, file.getCharset()); return content; } catch (IOException e) { - throw new RuntimeException(e); //TODO handle better + throw new RuntimeException(e); // TODO handle better } catch (CoreException e) { - throw new RuntimeException(e); //TODO handle better + throw new RuntimeException(e); // TODO handle better } } /** - * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText( - * java.lang.String) + * @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)); + 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 + // 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() + * #getSource() */ public Object getSource() { return file; - } - + } + /** * @return The resource location label. or null if unknown. */ public String getResourceLocationLabel() { - return file.getFullPath().toString(); + return file.getFullPath().toString(); } - + /** - * Called before this object will be discarded. - * If this object was listening to file changes: then unsubscribe it. + * 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); - } + 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 index 559aa1f1..08e1b290 100644 --- 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 @@ -15,36 +15,39 @@ 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. + * 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{ +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. + * + * @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, + public PropertiesReadOnlyResource(Locale locale, PropertiesSerializer serializer, - PropertiesDeserializer deserializer, - String contents, + PropertiesDeserializer deserializer, String contents, String resourceLocationLabel) { super(locale, serializer, deserializer); this.contents = contents; @@ -53,7 +56,7 @@ public PropertiesReadOnlyResource( /** * @see org.eclipse.babel.core.message.internal.resource.AbstractPropertiesResource - * #getText() + * #getText() */ public String getText() { return contents; @@ -61,34 +64,34 @@ public String getText() { /** * Unsupported here. This is read-only. - * @see org.eclipse.babel.core.message.internal.resource.TextResource#setText( - * java.lang.String) + * + * @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) + + " resource is read-only"); //$NON-NLS-1$ (just an error message) } - + /** * @see org.eclipse.babel.core.message.internal.resource.IMessagesResource - * #getSource() + * #getSource() */ public Object getSource() { return this; - } - + } + /** * @return The resource location label. or null if unknown. */ public String getResourceLocationLabel() { - return resourceLocationLabel; + return resourceLocationLabel; } - + /** - * Called before this object will be discarded. - * Nothing to do: we were not listening to changes to this object. + * 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. + // 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 6791225b..13c8bd8b 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 @@ -19,6 +19,7 @@ public interface IPropertiesDeserializerConfig { /** * Defaults true. + * * @return Returns the unicodeUnescapeEnabled. */ boolean isUnicodeUnescapeEnabled(); 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 c5f452e6..3a6fcba6 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 @@ -28,42 +28,49 @@ public interface IPropertiesSerializerConfig { /** * 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(); @@ -80,12 +87,14 @@ public interface IPropertiesSerializerConfig { /** * Defaults to 8. + * * @return Returns the wrapIndentLength. */ int getWrapIndentLength(); /** * Defaults to true. + * * @return Returns the spacesAroundEqualsEnabled. */ boolean isSpacesAroundEqualsEnabled(); @@ -112,12 +121,14 @@ public interface IPropertiesSerializerConfig { /** * Defaults to true. + * * @return Returns the groupAlignEqualsEnabled. */ boolean isGroupAlignEqualsEnabled(); - + /** * Defaults to true. + * * @return <code>true</code> if keys are to be sorted */ boolean isKeySortingEnabled(); 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 4d9ab3f7..b94146d5 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 @@ -23,22 +23,23 @@ import org.eclipse.babel.core.util.BabelUtils; /** - * Class responsible for deserializing {@link Properties}-like text into - * a {@link MessagesBundle}. + * 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$ - + 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. */ @@ -48,21 +49,23 @@ public PropertiesDeserializer(IPropertiesDeserializerConfig 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 + * 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> 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(); @@ -71,12 +74,12 @@ public void deserialize(IMessagesBundle messagesBundle, String properties) { String line = lines[i]; lineBuf.setLength(0); lineBuf.append(line); - + int equalPosition = findKeyValueSeparator(line); boolean isRegularLine = line.matches("^[^#].*"); //$NON-NLS-1$ - boolean isCommentedLine = doneWithFileComment + boolean isCommentedLine = doneWithFileComment && line.matches("^##[^#].*"); //$NON-NLS-1$ - + // parse regular and commented lines if (equalPosition >= 1 && (isRegularLine || isCommentedLine)) { doneWithFileComment = true; @@ -91,17 +94,14 @@ public void deserialize(IMessagesBundle messagesBundle, String properties) { equalPosition -= 2; } String backslash = "\\"; //$NON-NLS-1$ - while (lineBuf.lastIndexOf(backslash) == lineBuf.length() -1) { + while (lineBuf.lastIndexOf(backslash) == lineBuf.length() - 1) { int lineBreakPosition = lineBuf.lastIndexOf(backslash); - lineBuf.replace( - lineBreakPosition, - lineBreakPosition + 1, ""); //$NON-NLS-1$ + lineBuf.replace(lineBreakPosition, lineBreakPosition + 1, + ""); //$NON-NLS-1$ if (++i < lines.length) { - String wrappedLine = lines[i].replaceFirst( - "^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$ + String wrappedLine = lines[i].replaceFirst("^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (isCommentedLine) { - lineBuf.append(wrappedLine.replaceFirst( - "^##", "")); //$NON-NLS-1$ //$NON-NLS-2$ + lineBuf.append(wrappedLine.replaceFirst("^##", "")); //$NON-NLS-1$ //$NON-NLS-2$ } else { lineBuf.append(wrappedLine); } @@ -109,22 +109,20 @@ public void deserialize(IMessagesBundle messagesBundle, String properties) { } String key = lineBuf.substring(0, equalPosition).trim(); key = unescapeKey(key); - + String value = lineBuf.substring(equalPosition + 1) - .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$ + .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$ // Unescape leading spaces if (value.startsWith("\\ ")) { //$NON-NLS-1$ value = value.substring(1); } - + if (this.config != null && config.isUnicodeUnescapeEnabled()) { key = convertEncodedToUnicode(key); value = convertEncodedToUnicode(value); } else { - value = value.replaceAll( - "\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$ - value = value.replaceAll( - "\\\\n", "\n"); //$NON-NLS-1$//$NON-NLS-2$ + 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) { @@ -135,7 +133,7 @@ public void deserialize(IMessagesBundle messagesBundle, String properties) { entry.setComment(comment); entry.setText(value); newKeys.add(key); - // parse comment line + // parse comment line } else if (lineBuf.indexOf("#") == 0) { //$NON-NLS-1$ if (!doneWithFileComment) { fileComment.append(lineBuf); @@ -144,22 +142,23 @@ public void deserialize(IMessagesBundle messagesBundle, String properties) { lineComment.append(lineBuf); lineComment.append(SYSTEM_LINE_SEPARATOR); } - // handle blank or unsupported line + // handle blank or unsupported line } else { doneWithFileComment = true; } } oldKeys.removeAll(newKeys); - messagesBundle.removeMessages( - oldKeys.toArray(BabelUtils.EMPTY_STRINGS)); + messagesBundle + .removeMessages(oldKeys.toArray(BabelUtils.EMPTY_STRINGS)); messagesBundle.setComment(fileComment.toString()); } - - + /** - * Converts encoded &#92;uxxxx to unicode chars - * and changes special saved chars to their original forms - * @param str the string to convert + * Converts encoded &#92;uxxxx to unicode chars and changes special saved + * chars to their original forms + * + * @param str + * the string to convert * @return converted string * @see java.util.Properties */ @@ -178,25 +177,40 @@ private String convertEncodedToUnicode(String str) { 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': + 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': + 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': + 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); + System.err.println("PropertiesDeserializer: " //$NON-NLS-1$ + + "bad character " //$NON-NLS-1$ + + "encoding for string:" //$NON-NLS-1$ + + str); } } outBuffer.append((char) value); @@ -220,10 +234,12 @@ private String convertEncodedToUnicode(String str) { } return outBuffer.toString(); } - + /** * Finds the separator symbol that separates keys and values. - * @param str the string on which to find seperator + * + * @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) { @@ -240,7 +256,7 @@ private int findKeyValueSeparator(String str) { } return index; } - + private String unescapeKey(String key) { int length = key.length(); StringBuffer buf = new StringBuffer(); @@ -252,5 +268,5 @@ private String unescapeKey(String key) { } return buf.toString(); } - + } 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 0f134301..bc1aa5ae 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 @@ -20,44 +20,38 @@ /** * 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$ + 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' - }; + 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$ + 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$ - + 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$ + 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$ + 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. */ @@ -69,7 +63,9 @@ public PropertiesSerializer(IPropertiesSerializerConfig 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 + * + * @param messagesBundle + * the bundle used to generate the string * @return the generated string */ public String serialize(IMessagesBundle messagesBundle) { @@ -79,7 +75,7 @@ public String serialize(IMessagesBundle messagesBundle) { // Header comment String headComment = messagesBundle.getComment(); - if (config.isShowSupportEnabled() + if (config.isShowSupportEnabled() && !headComment.startsWith(GENERATED_BY)) { text.append(GENERATED_BY); text.append(SYSTEM_LINE_SEP); @@ -87,7 +83,7 @@ public String serialize(IMessagesBundle messagesBundle) { if (headComment != null && headComment.length() > 0) { text.append(headComment); } - + // Format String group = null; int equalIndex = -1; @@ -96,36 +92,32 @@ public String serialize(IMessagesBundle messagesBundle) { Arrays.sort(keys); } for (int i = 0; i < keys.length; i++) { - String key = keys[i]; + String key = keys[i]; IMessage message = messagesBundle.getMessage(key); - String value = message.getValue(); - String comment = message.getComment(); - - if (value != null){ + 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$ + 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$ + 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$ + 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 - + + // 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); @@ -139,7 +131,7 @@ public String serialize(IMessagesBundle messagesBundle) { } else { equalIndex = getEqualIndex(key, null, messagesBundle); } - + // Build line if (config.isUnicodeEscapeEnabled()) { key = convertUnicodeToEncoded(key); @@ -154,10 +146,12 @@ public String serialize(IMessagesBundle messagesBundle) { } return text.toString(); } - + /** * Converts unicodes to encoded &#92;uxxxx. - * @param str string to convert + * + * @param str + * string to convert * @return converted string * @see java.util.Properties */ @@ -180,10 +174,12 @@ private String convertUnicodeToEncoded(String str) { } return outBuffer.toString(); } - + /** * Converts a nibble to a hex character - * @param nibble the nibble to convert. + * + * @param nibble + * the nibble to convert. * @return a converted character */ private char toHex(int nibble) { @@ -196,14 +192,18 @@ private char toHex(int nibble) { /** * 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 + * + * @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) { + private void appendValue(StringBuffer text, String value, int equalIndex, + boolean active) { if (value != null) { // Escape potential leading spaces. if (value.startsWith(" ")) { //$NON-NLS-1$ @@ -216,11 +216,10 @@ private void appendValue( } else { valueStartPos += 1; } - + // Break line after escaped new line if (config.isNewLineNice()) { - value = value.replaceAll( - "(\\\\r\\\\n|\\\\r|\\\\n)", //$NON-NLS-1$ + value = value.replaceAll("(\\\\r\\\\n|\\\\r|\\\\n)", //$NON-NLS-1$ "$1\\\\" + SYSTEM_LINE_SEP); //$NON-NLS-1$ } // Wrap lines @@ -228,20 +227,20 @@ private void appendValue( 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); + 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)); + // 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(valueBuf.substring(0, endPos)); text.append("\\"); //$NON-NLS-1$ text.append(SYSTEM_LINE_SEP); } @@ -263,28 +262,33 @@ private void appendValue( text.append(valueBuf); } else { saveValue(text, value); - //text.append(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 + * + * @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) { + 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); + // text.append(key); for (int i = 0; i < equalIndex - key.length(); i++) { text.append(' '); } @@ -294,25 +298,28 @@ private void appendKey( 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 + * + * @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) { + private void saveText(StringBuffer buf, String str, String escapeChars) { int len = str.length(); - for(int x = 0; x < len; x++) { + for (int x = 0; x < len; x++) { char aChar = str.charAt(x); if (escapeChars.indexOf(aChar) != -1) { buf.append('\\'); @@ -320,10 +327,12 @@ private void saveText( buf.append(aChar); } } - + /** * Gets the group from a resource bundle key. - * @param key the key to get a group from + * + * @param key + * the key to get a group from * @return key group */ private String getKeyGroup(String key) { @@ -331,7 +340,7 @@ private String getKeyGroup(String key) { 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) { @@ -347,39 +356,43 @@ private String getKeyGroup(String key) { } 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 + * 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) { + 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) { + 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]; + 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.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 3d1c5511..c8f3b457 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 @@ -17,49 +17,54 @@ import org.eclipse.babel.core.message.internal.MessagesBundle; import org.eclipse.babel.core.message.resource.IMessagesResource; - - /** - * This class holds the algorithms required to abstract the internal nature - * of a <code>MessagesBundleGroup</code>. + * 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? - + // 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> + * 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>. + * <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>. + * 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 + * @throws MessageException + * problem loading bundles */ MessagesBundle[] loadMessagesBundles() throws MessageException; - + /** - * Creates a new bundle for the given <code>Locale</code>. If the + * 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 + * + * @param locale + * locale for which to create the messages bundle * @return a new messages bundle - * @throws MessageException problem creating a new messages bundle + * @throws MessageException + * problem creating a new messages bundle */ MessagesBundle createMessagesBundle(Locale locale) throws MessageException; - + String getProjectName(); } 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 8649996c..8aff394e 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 @@ -39,7 +39,7 @@ * @author Pascal Essiembre */ public class PropertiesFileGroupStrategy implements - IMessagesBundleGroupStrategy { + IMessagesBundleGroupStrategy { /** Empty bundle array. */ private static final MessagesBundle[] EMPTY_MESSAGES = new MessagesBundle[] {}; @@ -64,24 +64,24 @@ public class PropertiesFileGroupStrategy implements * 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$ + 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$ } /** @@ -89,7 +89,7 @@ public PropertiesFileGroupStrategy(File file, * #getMessagesBundleGroupName() */ public String createMessagesBundleGroupName() { - return baseName + "[...]." + fileExtension; //$NON-NLS-1$ + return baseName + "[...]." + fileExtension; //$NON-NLS-1$ } /** @@ -97,26 +97,26 @@ public String createMessagesBundleGroupName() { * #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); + 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); } /** @@ -124,8 +124,8 @@ public MessagesBundle[] loadMessagesBundles() throws MessageException { * #createBundle(java.util.Locale) */ public MessagesBundle createMessagesBundle(Locale locale) { - // TODO Implement me (code exists in SourceForge version) - return null; + // TODO Implement me (code exists in SourceForge version) + return null; } /** @@ -138,54 +138,54 @@ public MessagesBundle createMessagesBundle(Locale locale) { * @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$ - } + 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"); - if (index == -1 ) - return ""; - 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 NameUtils.getResourceBundleId(f); + public String createMessagesBundleId() { + String path = file.getAbsolutePath(); + int index = path.indexOf("src"); + if (index == -1) + return ""; + 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 NameUtils.getResourceBundleId(f); } 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); - - if (file != null) { - return ResourcesPlugin.getWorkspace().getRoot() - .getProject(file.getFullPath().segments()[0]).getName(); - } else { - return null; - } - + 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); + + if (file != null) { + return ResourcesPlugin.getWorkspace().getRoot() + .getProject(file.getFullPath().segments()[0]).getName(); + } else { + return null; + } + } // public static String getResourceBundleId (IResource resource) { diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java index 632184f9..3b0cbb36 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java @@ -10,19 +10,18 @@ ******************************************************************************/ package org.eclipse.babel.core.message.tree; - public interface IAbstractKeyTreeModel { - IKeyTreeNode[] getChildren(IKeyTreeNode node); + IKeyTreeNode[] getChildren(IKeyTreeNode node); - IKeyTreeNode getChild(String key); + IKeyTreeNode getChild(String key); - IKeyTreeNode[] getRootNodes(); + IKeyTreeNode[] getRootNodes(); - IKeyTreeNode getRootNode(); + IKeyTreeNode getRootNode(); - IKeyTreeNode getParent(IKeyTreeNode node); + IKeyTreeNode getParent(IKeyTreeNode node); - void accept(IKeyTreeVisitor visitor, IKeyTreeNode node); + void accept(IKeyTreeVisitor visitor, IKeyTreeNode 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 index b7b85856..552774d3 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java @@ -14,66 +14,66 @@ public interface IKeyTreeNode { - /** - * Returns the key of the corresponding Resource-Bundle entry. - * - * @return The key of the Resource-Bundle entry - */ - String getMessageKey(); + /** + * 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(); + /** + * 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(); + /** + * 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 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); + /** + * 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-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(); + /** + * The Resource-Bundles key representation. + * + * @return The Resource-Bundle reference, if known + */ + IMessagesBundleGroup getMessagesBundleGroup(); - boolean isUsedAsKey(); + boolean isUsedAsKey(); - void setParent(IKeyTreeNode parentNode); + void setParent(IKeyTreeNode parentNode); - void addChild(IKeyTreeNode childNode); + 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 index ac7a5355..5bdd8089 100644 --- 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 @@ -10,7 +10,6 @@ ******************************************************************************/ package org.eclipse.babel.core.message.tree; - /** * Objects implementing this interface can act as a visitor to a * <code>IKeyTreeModel</code>. @@ -18,11 +17,11 @@ * @author Pascal Essiembre ([email protected]) */ public interface IKeyTreeVisitor { - /** - * Visits a key tree node. - * - * @param item - * key tree node to visit - */ - void visitKeyTreeNode(IKeyTreeNode node); + /** + * 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/TreeType.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java index bf833e90..c2e771c1 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java @@ -11,18 +11,20 @@ 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: + * 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 + 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 index ed4fceae..8e242b70 100644 --- 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 @@ -23,15 +23,18 @@ import org.eclipse.babel.core.message.tree.IKeyTreeNode; import org.eclipse.babel.core.message.tree.IKeyTreeVisitor; - /** - * Hierarchical representation of all keys making up a + * 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> + * + * 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 @@ -44,13 +47,13 @@ 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[]{}; + + protected static final KeyTreeNode[] EMPTY_NODES = new KeyTreeNode[] {}; /** * Defaults to ".". @@ -61,30 +64,36 @@ public AbstractKeyTreeModel(MessagesBundleGroup messagesBundleGroup) { /** * Constructor. - * @param messagesBundleGroup {@link MessagesBundleGroup} instance - * @param delimiter key section delimiter + * + * @param messagesBundleGroup + * {@link MessagesBundleGroup} instance + * @param delimiter + * key section delimiter */ - public AbstractKeyTreeModel( - MessagesBundleGroup messagesBundleGroup, String 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); - } - }); + + 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 + * + * @param listener + * key tree model listener */ public void addKeyTreeModelListener(IKeyTreeModelListener listener) { listeners.add(0, listener); @@ -92,27 +101,34 @@ public void addKeyTreeModelListener(IKeyTreeModelListener listener) { /** * Removes a key tree model listener. - * @param listener 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 + * + * @param node + * added node */ - protected void fireNodeAdded(KeyTreeNode 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 + * + * @param node + * removed node */ - protected void fireNodeRemoved(KeyTreeNode node) { - for (IKeyTreeModelListener listener : listeners) { + protected void fireNodeRemoved(KeyTreeNode node) { + for (IKeyTreeModelListener listener : listeners) { listener.nodeRemoved(node); } } @@ -121,26 +137,30 @@ protected void fireNodeRemoved(KeyTreeNode 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 + * + * @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[]{}); + 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 + * 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); } @@ -152,14 +172,16 @@ public void accept(IKeyTreeVisitor visitor, IKeyTreeNode node) { /** * Gets the child nodes of a given key tree node. - * @param node the node from which to get children + * + * @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()); @@ -167,8 +189,9 @@ public IKeyTreeNode[] getChildren(IKeyTreeNode node) { return nodes; } - /** + /** * Gets the comparator. + * * @return the comparator */ public Comparator<IKeyTreeNode> getComparator() { @@ -177,76 +200,90 @@ public Comparator<IKeyTreeNode> getComparator() { /** * Sets the node comparator for sorting sibling nodes. - * @param comparator node comparator + * + * @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 + * 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 filter + * The leaf filter. * @param node - * @return true if this node or one of its descendant is in the filter (ie is displayed) + * @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; + 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 + * + * @param delimiter + * delimiter */ public void setDelimiter(String delimiter) { this.delimiter = delimiter; } - - /** - * Gets the key tree root nodes. - * @return key tree root nodes - */ + + /** + * Gets the key tree root nodes. + * + * @return key tree root nodes + */ public IKeyTreeNode[] getRootNodes() { return getChildren(rootNode); } public IKeyTreeNode getRootNode() { - return rootNode; + return rootNode; } - + /** * Gets the parent node of the given node. - * @param node node from which to get parent + * + * @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 + // TODO consider moving this method (and part of constructor) to super return messagesBundleGroup; } @@ -254,11 +291,11 @@ 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]; + String key = keys[i]; createTreeNodes(key); } } - + private void createTreeNodes(String bundleKey) { StringTokenizer tokens = new StringTokenizer(bundleKey, delimiter); KeyTreeNode node = rootNode; @@ -268,7 +305,8 @@ private void createTreeNodes(String bundleKey) { bundleKeyPart += name; KeyTreeNode child = (KeyTreeNode) node.getChild(name); if (child == null) { - child = new KeyTreeNode(node, name, bundleKeyPart, messagesBundleGroup); + child = new KeyTreeNode(node, name, bundleKeyPart, + messagesBundleGroup); fireNodeAdded(child); } bundleKeyPart += delimiter; @@ -276,6 +314,7 @@ private void createTreeNodes(String bundleKey) { } node.setUsedAsKey(); } + private void removeTreeNodes(String bundleKey) { if (bundleKey == null) { return; @@ -286,8 +325,8 @@ private void removeTreeNodes(String bundleKey) { 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$ + System.err + .println("No RegEx node matching bundleKey to remove"); //$NON-NLS-1$ return; } } @@ -295,34 +334,35 @@ private void removeTreeNodes(String bundleKey) { parentNode.removeChild(node); fireNodeRemoved(node); while (parentNode != rootNode) { - if (!parentNode.hasChildren() && !messagesBundleGroup.isMessageKey( - parentNode.getMessageKey())) { - ((KeyTreeNode)parentNode.getParent()).removeChild(parentNode); + if (!parentNode.hasChildren() + && !messagesBundleGroup.isMessageKey(parentNode + .getMessageKey())) { + ((KeyTreeNode) parentNode.getParent()).removeChild(parentNode); fireNodeRemoved(parentNode); } - parentNode = (KeyTreeNode)parentNode.getParent(); + 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); + /** + * @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())) { + + if (!key.equals(node.getMessageKey())) { for (IKeyTreeNode n : node.getChildren()) { IKeyTreeNode returnNode = returnNodeWithKey(key, n); - if (returnNode == null) { + if (returnNode == null) { continue; } else { return returnNode; 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 index 83da223f..34af800e 100644 --- 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 @@ -12,18 +12,24 @@ /** * 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 - */ + /** + * 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 - */ + + /** + * 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 index 81dbb02e..9c9d982b 100644 --- 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 @@ -22,47 +22,50 @@ /** * 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[] {}; - + 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 + * 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 + * object */ private String messageKey; - + private final Map<String, IKeyTreeNode> children = new TreeMap<String, IKeyTreeNode>(); - private boolean usedAsKey = false; - - private IMessagesBundleGroup messagesBundleGroup; - + private boolean usedAsKey = false; + + private IMessagesBundleGroup messagesBundleGroup; + /** * Constructor. - * @param parent parent node - * @param name node name - * @param messageKey messages bundle key + * + * @param parent + * parent node + * @param name + * node name + * @param messageKey + * messages bundle key */ - public KeyTreeNode( - IKeyTreeNode parent, String name, String messageKey, IMessagesBundleGroup messagesBundleGroup) { + public KeyTreeNode(IKeyTreeNode parent, String name, String messageKey, + IMessagesBundleGroup messagesBundleGroup) { super(); this.parent = parent; this.name = name; @@ -74,35 +77,37 @@ public KeyTreeNode( } /** - * @return the name, being the part of the full key that follows the last period + * @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 + * @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 + * @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() { + /* default */IKeyTreeNode[] getPath() { List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>(); IKeyTreeNode node = this; while (node != null && node.getName() != null) { @@ -115,26 +120,29 @@ public String getMessageKey() { public IKeyTreeNode[] getChildren() { return children.values().toArray(EMPTY_KEY_TREE_NODES); } - /*default*/ boolean hasChildren() { + + /* 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(); + 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!!! + // 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; } @@ -150,7 +158,7 @@ public int compareTo(KeyTreeNode node) { 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); @@ -160,66 +168,67 @@ public boolean equals(Object obj) { * @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$ + 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 parent on child node? } // TODO: remove this, or simplify it using method getDescendants - public Collection<KeyTreeNode> getBranch() { + public Collection<KeyTreeNode> getBranch() { Collection<KeyTreeNode> childNodes = new ArrayList<KeyTreeNode>(); childNodes.add(this); for (IKeyTreeNode childNode : this.getChildren()) { - childNodes.addAll(((KeyTreeNode)childNode).getBranch()); + 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) { + } + + 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 5805c186..9dc96eb9 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 @@ -13,18 +13,22 @@ import org.eclipse.babel.core.message.internal.MessagesBundleGroup; /** - * All purpose key testing. Use this interface to establish whether - * a message key within a {@link MessagesBundleGroup} is answering - * successfully to any condition. + * 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 - */ + /** + * 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.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 724da52f..bdf51f74 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 @@ -18,31 +18,32 @@ import org.eclipse.babel.core.message.tree.IKeyTreeVisitor; import org.eclipse.babel.core.message.tree.internal.KeyTreeNode; - /** * 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) { + public KeyCheckVisitor(MessagesBundleGroup messagesBundleGroup, + IKeyCheck keyCheck) { super(); this.keyCheck = keyCheck; this.messagesBundleGroup = messagesBundleGroup; } + /** * Constructor. */ @@ -50,11 +51,10 @@ public KeyCheckVisitor(MessagesBundleGroup messagesBundleGroup) { super(); this.messagesBundleGroup = messagesBundleGroup; } - + /** * @see org.eclipse.babel.core.message.internal.tree.visitor.IKeyTreeVisitor - * #visitKeyTreeNode( - * org.eclipse.babel.core.message.internal.tree.internal.KeyTreeNode) + * #visitKeyTreeNode(org.eclipse.babel.core.message.internal.tree.internal.KeyTreeNode) */ public void visitKeyTreeNode(IKeyTreeNode node) { if (keyCheck == null) { @@ -69,19 +69,22 @@ public void visitKeyTreeNode(IKeyTreeNode 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. */ @@ -92,8 +95,11 @@ public void reset() { /** * Sets the key check for this visitor. - * @param newKeyCheck new key check - * @param reset whether to reset the passed and failed nodes. + * + * @param newKeyCheck + * new key check + * @param reset + * whether to reset the passed and failed nodes. */ public void setKeyCheck(IKeyCheck newKeyCheck, boolean reset) { if (reset) { 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 ead7a26a..9098a643 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 @@ -18,6 +18,7 @@ /** * Visitor for finding keys matching the given regular expression. + * * @author Pascal Essiembre ([email protected]) */ public class NodePathRegexVisitor implements IKeyTreeVisitor { @@ -25,7 +26,7 @@ public class NodePathRegexVisitor implements IKeyTreeVisitor { /** Holder for matching keys. */ private List<IKeyTreeNode> nodes = new ArrayList<IKeyTreeNode>(); private final String regex; - + /** * Constructor. */ @@ -46,6 +47,7 @@ public void visitKeyTreeNode(IKeyTreeNode node) { /** * Gets matching key tree nodes. + * * @return matching key tree nodes */ public List<IKeyTreeNode> getKeyTreeNodes() { @@ -54,6 +56,7 @@ public List<IKeyTreeNode> getKeyTreeNodes() { /** * Gets matching key tree node paths. + * * @return matching key tree node paths */ public List<String> getKeyTreeNodePaths() { @@ -64,9 +67,9 @@ public List<String> getKeyTreeNodePaths() { return paths; } - /** * Gets the first item matched. + * * @return first item matched, or <code>null</code> if none was found */ public IKeyTreeNode getKeyTreeNode() { diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/refactoring/IRefactoringService.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/refactoring/IRefactoringService.java index fc394ccb..31ddb0a8 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/refactoring/IRefactoringService.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/refactoring/IRefactoringService.java @@ -16,64 +16,79 @@ import org.eclipse.core.resources.IFile; /** - * Service class, which can be used to execute key refactorings. - * This can be retrieved via:<br> + * Service class, which can be used to execute key refactorings. This can be + * retrieved via:<br> * {@link RBManager#getRefactorService()} * * @author Alexej Strelzow */ public interface IRefactoringService { - /** - * Executes following steps:<br> - * <ol> - * <li>Changes the {@link CompilationUnit}s, which must be changed</li> - * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> - * <li>Displays the summary dialog</li> - * </ol> - * <br> - * - * @param projectName The project the resource bundle is in. - * @param resourceBundleId The resource bundle, which contains the key to be refactored. - * @param selectedLocale The selected {@link Locale} to change. - * @param oldKey The old key name - * @param newKey The new key name, which should overwrite the old one - * @param enumPath The path of the enum file to change - */ - void refactorKey(String projectName, String resourceBundleId, - String selectedLocale, String oldKey, String newKey, String enumName); - - /** - * Executes following steps:<br> - * <ol> - * <li>Displays the initial refactoring dialog</li> - * <li>Changes the {@link CompilationUnit}s, which must be changed</li> - * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> - * <li>Displays the summary dialog</li> - * </ol> - * <br> - * - * @param projectName The project the resource bundle is in. - * @param resourceBundleId The resource bundle, which contains the key to be refactored. - * @param selectedLocale The selected {@link Locale} to change. - * @param oldKey The old key name - * @param newKey The new key name, which should overwrite the old one - * @param enumPath The path of the enum file to change - */ - void openRefactorDialog(String projectName, String resourceBundleId, - String oldKey, String enumName); - - /** - * Executes following steps:<br> - * <ol> - * <li>Displays the initial refactoring dialog</li> - * <li>Changes the {@link CompilationUnit}s, which must be changed</li> - * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> - * <li>Displays the summary dialog</li> - * </ol> - * <br> - * @param file The file, of the editor input - * @param selectionOffset The position of the cursor - */ - void openRefactorDialog(IFile file, int selectionOffset); + /** + * Executes following steps:<br> + * <ol> + * <li>Changes the {@link CompilationUnit}s, which must be changed</li> + * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> + * <li>Displays the summary dialog</li> + * </ol> + * <br> + * + * @param projectName + * The project the resource bundle is in. + * @param resourceBundleId + * The resource bundle, which contains the key to be refactored. + * @param selectedLocale + * The selected {@link Locale} to change. + * @param oldKey + * The old key name + * @param newKey + * The new key name, which should overwrite the old one + * @param enumPath + * The path of the enum file to change + */ + void refactorKey(String projectName, String resourceBundleId, + String selectedLocale, String oldKey, String newKey, String enumName); + + /** + * Executes following steps:<br> + * <ol> + * <li>Displays the initial refactoring dialog</li> + * <li>Changes the {@link CompilationUnit}s, which must be changed</li> + * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> + * <li>Displays the summary dialog</li> + * </ol> + * <br> + * + * @param projectName + * The project the resource bundle is in. + * @param resourceBundleId + * The resource bundle, which contains the key to be refactored. + * @param selectedLocale + * The selected {@link Locale} to change. + * @param oldKey + * The old key name + * @param newKey + * The new key name, which should overwrite the old one + * @param enumPath + * The path of the enum file to change + */ + void openRefactorDialog(String projectName, String resourceBundleId, + String oldKey, String enumName); + + /** + * Executes following steps:<br> + * <ol> + * <li>Displays the initial refactoring dialog</li> + * <li>Changes the {@link CompilationUnit}s, which must be changed</li> + * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> + * <li>Displays the summary dialog</li> + * </ol> + * <br> + * + * @param file + * The file, of the editor input + * @param selectionOffset + * The position of the cursor + */ + void openRefactorDialog(IFile file, int selectionOffset); } diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java index ff788d55..5aeb8379 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java @@ -16,15 +16,16 @@ import java.util.StringTokenizer; /** - * Utility methods of all kinds used across the Babel API. + * 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? - + // TODO find a better sport for these methods? + public static final String[] EMPTY_STRINGS = new String[] {}; - + /** * Constructor. */ @@ -34,10 +35,13 @@ private BabelUtils() { /** * Null-safe testing of two objects for equality. - * @param o1 object 1 - * @param o2 object 2 + * + * @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>. + * <code>null</code>. */ public static boolean equals(Object o1, Object o2) { return (o1 == null && o2 == null || o1 != null && o1.equals(o2)); @@ -45,8 +49,11 @@ public static boolean equals(Object o1, Object o2) { /** * Joins an array by the given separator. - * @param array the array to join - * @param separator the joining separator + * + * @param array + * the array to join + * @param separator + * the joining separator * @return joined string */ public static String join(Object[] array, String separator) { @@ -63,19 +70,19 @@ public static String join(Object[] array, String separator) { 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 + * 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$ + StringTokenizer tokens = new StringTokenizer(localeString, "_"); //$NON-NLS-1$ List<String> localeSections = new ArrayList<String>(); while (tokens.hasMoreTokens()) { localeSections.add(tokens.nextToken()); @@ -86,14 +93,10 @@ public static Locale parseLocale(String localeString) { locale = new Locale(localeSections.get(0)); break; case 2: - locale = new Locale( - localeSections.get(0), - localeSections.get(1)); + locale = new Locale(localeSections.get(0), localeSections.get(1)); break; case 3: - locale = new Locale( - localeSections.get(0), - localeSections.get(1), + locale = new Locale(localeSections.get(0), localeSections.get(1), localeSections.get(2)); break; default: diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java index 5a346251..a550bcee 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java @@ -14,12 +14,15 @@ /** * Listener interested in {@link File} changes. + * * @author Pascal Essiembre */ public interface FileChangeListener { /** - * Invoked when a file changes. - * @param fileName name of changed file. + * Invoked when a file changes. + * + * @param fileName + * name of changed file. */ public void fileChanged(File file); } diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java index 898e5ba8..38a727cd 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java @@ -17,9 +17,9 @@ import java.util.Timer; import java.util.TimerTask; - /** * Class monitoring a {@link File} for changes. + * * @author Pascal Essiembre */ public class FileMonitor { @@ -27,10 +27,11 @@ public class FileMonitor { private static final FileMonitor instance = new FileMonitor(); private Timer timer; - private Hashtable<String,FileMonitorTask> timerEntries; + private Hashtable<String, FileMonitorTask> timerEntries; /** * Gets the file monitor instance. + * * @return file monitor instance */ public static FileMonitor getInstance() { @@ -40,69 +41,80 @@ public static FileMonitor getInstance() { /** * Constructor. */ - private FileMonitor() { + private FileMonitor() { // Create timer, run timer thread as daemon. - timer = new Timer(true); - timerEntries = new Hashtable<String,FileMonitorTask>(); + 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. + * + * @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 { + 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. + * + * @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); + 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. + * + * @param listener + * the listener to be removed. */ - public void removeFileChangeListener(FileChangeListener listener, - String fileName) { + 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. + * + * @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(); - } + 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 + * + * @param listener + * file change listener + * @param file + * the file that changed */ - protected void fireFileChangeEvent( - FileChangeListener listener, File file) { - listener.fileChanged(file); + protected void fireFileChangeEvent(FileChangeListener listener, File file) { + listener.fileChanged(file); } /** @@ -113,30 +125,29 @@ class FileMonitorTask extends TimerTask { 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 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); - } - } + long lastModified = monitoredFile.lastModified(); + if (lastModified != this.lastModified) { + this.lastModified = lastModified; + fireFileChangeEvent(this.listener, monitoredFile); + } + } } } diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java index 2a226522..784cdb15 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java @@ -28,47 +28,48 @@ * @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()); + 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); + } + } - 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 index 7fafe733..6920ff76 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java @@ -24,63 +24,63 @@ */ public class NameUtils { - - public static String getResourceBundleId(IResource resource) { - String packageFragment = ""; + public static String getResourceBundleId(IResource resource) { + String packageFragment = ""; - IJavaElement propertyFile = JavaCore.create(resource.getParent()); - if (propertyFile != null && propertyFile instanceof IPackageFragment) - packageFragment = ((IPackageFragment) propertyFile) - .getElementName(); + IJavaElement propertyFile = JavaCore.create(resource.getParent()); + if (propertyFile != null && propertyFile instanceof IPackageFragment) + packageFragment = ((IPackageFragment) propertyFile) + .getElementName(); - return (packageFragment.length() > 0 ? packageFragment + "." : "") - + getResourceBundleName(resource); - } + 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("_"); + 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$ + } - 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; - } - } + 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); + } - return locale; - } + // 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.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java index 69ede279..42b3954d 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java @@ -45,246 +45,268 @@ * @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; - } + /** 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 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 + /** + * 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; + 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 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; + + 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 - */ + * 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; - } - + 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 + * 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; - } + 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(); - } - } + /** + * 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 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(); - } - } + 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; + 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.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 index ffffe0c9..244bc756 100644 --- 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 @@ -6,11 +6,11 @@ public class MyFormToolkit extends FormToolkit { - public MyFormToolkit(FormColors colors) { - super(colors); - } + public MyFormToolkit(FormColors colors) { + super(colors); + } - public MyFormToolkit(Display display) { - super(display); - } + public MyFormToolkit(Display display) { + super(display); + } } 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 index 3d77342e..5fed3ffd 100644 --- 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 @@ -5,26 +5,31 @@ public class Activator implements BundleActivator { - private static BundleContext context; + private static BundleContext context; - static BundleContext getContext() { - return 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#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; - } + /* + * (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/src/org/eclipse/babel/editor/i18n/I18NEntry.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/i18n/I18NEntry.java index 8ee342c0..19d8bcbb 100755 --- a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/i18n/I18NEntry.java +++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/i18n/I18NEntry.java @@ -13,64 +13,64 @@ public class I18NEntry extends AbstractI18NEntry { - public I18NEntry(Composite parent, AbstractMessagesEditor editor, - Locale locale) { - super(parent, editor, locale); - } + public I18NEntry(Composite parent, AbstractMessagesEditor editor, + Locale locale) { + super(parent, editor, locale); + } - @Override - void updateKey(String key) { - IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); - 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); - } - } + @Override + void updateKey(String key) { + IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); + 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); + } + } - @Override - KeyListener getKeyListener() { - return 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); - // } - // } - // - //}); - // } - } + @Override + KeyListener getKeyListener() { + return 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); + // } + // } + // + // }); + // } + } } diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/internal/MessagesEditor.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/internal/MessagesEditor.java index 9864224f..8e3e0d76 100755 --- a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/internal/MessagesEditor.java +++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/internal/MessagesEditor.java @@ -1,41 +1,42 @@ package org.eclipse.babel.editor.internal; + import org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener; import org.eclipse.babel.core.message.internal.MessagesBundle; import org.eclipse.babel.core.message.internal.MessagesBundleGroupAdapter; import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.texteditor.ITextEditor; - public class MessagesEditor extends AbstractMessagesEditor { - @Override - protected IMessagesBundleGroupListener getMsgBundleGroupListner() { - return new MessagesBundleGroupAdapter() { - @Override - public void messagesBundleAdded(MessagesBundle messagesBundle) { - addMessagesBundle(messagesBundle, messagesBundle.getLocale()); - // refresh i18n page - i18nPage.addI18NEntry(MessagesEditor.this, messagesBundle.getLocale()); - } - }; - } + @Override + protected IMessagesBundleGroupListener getMsgBundleGroupListner() { + return new MessagesBundleGroupAdapter() { + @Override + public void messagesBundleAdded(MessagesBundle messagesBundle) { + addMessagesBundle(messagesBundle, messagesBundle.getLocale()); + // refresh i18n page + i18nPage.addI18NEntry(MessagesEditor.this, + messagesBundle.getLocale()); + } + }; + } - @Override - protected void initRAP() { - // nothing to do - } + @Override + protected void initRAP() { + // nothing to do + } - @Override - protected void disposeRAP() { - // nothing to do - } + @Override + protected void disposeRAP() { + // nothing to do + } - @Override - public void setEnabled(boolean enabled) { - i18nPage.setEnabled(enabled); - for (ITextEditor textEditor : textEditorsIndex) { - // TODO disable editors - } - } + @Override + public void setEnabled(boolean enabled) { + i18nPage.setEnabled(enabled); + for (ITextEditor textEditor : textEditorsIndex) { + // TODO disable editors + } + } } diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RefactoringHandler.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RefactoringHandler.java index 18b92e61..65dd1227 100644 --- a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RefactoringHandler.java +++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RefactoringHandler.java @@ -30,53 +30,65 @@ import org.eclipse.ui.part.FileEditorInput; /** - * Handler for the key binding M1 (= Ctrl) + R. - * This handler triggers the refactoring process. + * Handler for the key binding M1 (= Ctrl) + R. This handler triggers the + * refactoring process. * * @author Alexej Strelzow */ public class RefactoringHandler extends AbstractHandler { - /** - * Gets called if triggered - * @param event The {@link ExecutionEvent} - */ - public Object execute(ExecutionEvent event) throws ExecutionException { + /** + * Gets called if triggered + * + * @param event + * The {@link ExecutionEvent} + */ + public Object execute(ExecutionEvent event) throws ExecutionException { + + Event e = ((Event) event.getTrigger()); + Widget widget = e.widget; + + ISelectionService selectionService = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getSelectionService(); + ISelection selection = selectionService.getSelection(); + + if (selection instanceof TextSelection && widget instanceof StyledText) { // Java-File + TextSelection txtSel = (TextSelection) selection; + IEditorPart activeEditor = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getActivePage() + .getActiveEditor(); + FileEditorInput input = (FileEditorInput) activeEditor + .getEditorInput(); + IFile file = input.getFile(); + + RBManager.getRefactorService().openRefactorDialog(file, + txtSel.getOffset()); + } + + if (widget != null && widget instanceof Tree) { // Messages-Editor or + // TapiJI-View + Tree tree = (Tree) widget; + TreeItem[] treeItems = tree.getSelection(); + if (treeItems.length == 1) { + TreeItem item = treeItems[0]; + String oldKey = item.getText(); + if (tree.getData() instanceof AbstractKeyTreeModel) { + AbstractKeyTreeModel model = (AbstractKeyTreeModel) tree + .getData(); + MessagesBundleGroup messagesBundleGroup = model + .getMessagesBundleGroup(); + String projectName = messagesBundleGroup.getProjectName(); + String resourceBundleId = messagesBundleGroup + .getResourceBundleId(); + + RBManager.getRefactorService().openRefactorDialog( + projectName, resourceBundleId, oldKey, null); + + } + } + } + + return null; + } - Event e = ((Event)event.getTrigger()); - Widget widget = e.widget; - - ISelectionService selectionService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService(); - ISelection selection = selectionService.getSelection(); - - if (selection instanceof TextSelection && widget instanceof StyledText) { // Java-File - TextSelection txtSel = (TextSelection) selection; - IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); - FileEditorInput input = (FileEditorInput) activeEditor.getEditorInput(); - IFile file = input.getFile(); - - RBManager.getRefactorService().openRefactorDialog(file, txtSel.getOffset()); - } - - if (widget != null && widget instanceof Tree) { // Messages-Editor or TapiJI-View - Tree tree = (Tree) widget; - TreeItem[] treeItems = tree.getSelection(); - if (treeItems.length == 1) { - TreeItem item = treeItems[0]; - String oldKey = item.getText(); - if (tree.getData() instanceof AbstractKeyTreeModel) { - AbstractKeyTreeModel model = (AbstractKeyTreeModel) tree.getData(); - MessagesBundleGroup messagesBundleGroup = model.getMessagesBundleGroup(); - String projectName = messagesBundleGroup.getProjectName(); - String resourceBundleId = messagesBundleGroup.getResourceBundleId(); - - RBManager.getRefactorService().openRefactorDialog(projectName, resourceBundleId, oldKey, null); - - } - } - } - - return null; - } - } diff --git a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java index d2bc7182..9f545ce8 100644 --- a/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java +++ b/org.eclipse.babel.editor.rcp/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java @@ -19,63 +19,64 @@ */ public class RenameKeyArguments extends RefactoringArguments { - private String fNewName; + private String fNewName; - private boolean fRenameChildKeys; + private boolean fRenameChildKeys; - private boolean fUpdateReferences; + 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; - } + /** + * 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 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 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; - } + /** + * 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$ - } + 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.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 index 826d16fa..16f70a91 100644 --- 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 @@ -27,132 +27,157 @@ */ 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(); - } - } + 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 index 9f73c3c6..cfcf982d 100644 --- 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 @@ -32,109 +32,119 @@ */ 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); - } + 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 index 5ce68f52..42b24b91 100644 --- 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 @@ -31,221 +31,281 @@ 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. - * + * 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; - } + 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 index 18b0f0c0..1778f6ee 100644 --- 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 @@ -33,131 +33,157 @@ */ 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()); - } - } + /** + * 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 index 5d9ae818..c9a95e6c 100644 --- 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 @@ -9,26 +9,26 @@ import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation; public class RenameKeyAction extends AbstractRenameKeyAction { - - public RenameKeyAction(AbstractMessagesEditor editor, TreeViewer treeViewer) { - super(editor, treeViewer); - } + + public RenameKeyAction(AbstractMessagesEditor 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 - } + 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/IMessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java index c5626f29..9d397d4c 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java @@ -13,13 +13,13 @@ import org.eclipse.babel.core.message.internal.MessagesBundleGroup; public interface IMessagesEditor { - String getSelectedKey(); + String getSelectedKey(); - void setSelectedKey(String key); - - MessagesBundleGroup getBundleGroup(); + void setSelectedKey(String key); - void setTitleName(String string); - - void setEnabled(boolean enabled); + MessagesBundleGroup getBundleGroup(); + + void setTitleName(String string); + + void setEnabled(boolean enabled); } 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 c37f6996..cce87368 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 @@ -12,11 +12,9 @@ import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel; - - /** * @author Pascal Essiembre - * + * */ public interface IMessagesEditorChangeListener { @@ -24,14 +22,15 @@ public interface IMessagesEditorChangeListener { 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 keyTreeModelChanged(AbstractKeyTreeModel oldModel, + AbstractKeyTreeModel newModel); + void editorDisposed(); } 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 28e15d9a..a470bb06 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 @@ -27,10 +27,12 @@ public class FilterKeysAction extends Action { private AbstractMessagesEditor editor; - private final int flagToSet; - private ChangeListener listener; + private final int flagToSet; + private ChangeListener listener; + /** - * @param flagToSet The flag that will be set on unset + * @param flagToSet + * The flag that will be set on unset */ public FilterKeysAction(int flagToSet) { super("", IAction.AS_CHECK_BOX); @@ -38,120 +40,121 @@ public FilterKeysAction(int flagToSet) { listener = new ChangeListener(); update(); } - + private class ChangeListener extends MessagesEditorChangeAdapter { public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) { - MessagesEditorContributor.FILTERS.updateActionBars(); + MessagesEditorContributor.FILTERS.updateActionBars(); } } - - - /* (non-Javadoc) + + /* + * (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) - } - } + 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) { + super.setEnabled(false); + } else { + super.setEnabled(true); + } - if (editor != null && editor.isShowOnlyUnusedAndMissingKeys() == flagToSet) { - setChecked(true); - } else { - setChecked(false); - } - setText(getTextInternal()); - setToolTipText(getTooltipInternal()); + if (editor != null + && editor.isShowOnlyUnusedAndMissingKeys() == flagToSet) { + setChecked(true); + } else { + setChecked(false); + } + setText(getTextInternal()); + setToolTipText(getTooltipInternal()); setImageDescriptor(ImageDescriptor.createFromImage(getImage())); } - + 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); - } + 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; - 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 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"; - } + 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"; -// } + 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(AbstractMessagesEditor editor) { - if (editor == this.editor) { - return;//no change - } + if (editor == this.editor) { + return;// no change + } if (this.editor != null) { - this.editor.removeChangeListener(listener); + this.editor.removeChangeListener(listener); } this.editor = editor; update(); if (editor != null) { - editor.addChangeListener(listener); + editor.addChangeListener(listener); } } 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 7c016cd9..f1df1e55 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 @@ -18,23 +18,24 @@ /** * @author Pascal Essiembre - * + * */ public class KeyTreeVisibleAction extends Action { private AbstractMessagesEditor editor; - + /** * */ public KeyTreeVisibleAction() { super("Show/Hide Key Tree", IAction.AS_CHECK_BOX); -// setText(); + // 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 + // TODO RBEditor hold such an action registry. Then move this method to + // constructor public void setEditor(AbstractMessagesEditor editor) { this.editor = editor; editor.addChangeListener(new MessagesEditorChangeAdapter() { @@ -45,13 +46,14 @@ public void keyTreeVisibleChanged(boolean visible) { setChecked(editor.getI18NPage().isKeyTreeVisible()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.action.Action#run() */ public void run() { editor.getI18NPage().setKeyTreeVisible( !editor.getI18NPage().isKeyTreeVisible()); } - - + } 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 e1788cfd..4531a86e 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 @@ -25,75 +25,79 @@ /** * @author Pascal Essiembre - * + * */ public class NewLocaleAction extends Action { private AbstractMessagesEditor editor; - + /** * */ public NewLocaleAction() { super("New &Locale..."); setToolTipText("Add a new locale to the resource bundle."); - setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_NEW_PROPERTIES_FILE)); + setImageDescriptor(UIUtils + .getImageDescriptor(UIUtils.IMAGE_NEW_PROPERTIES_FILE)); } - //TODO RBEditor hold such an action registry. Then move this method to constructor + // TODO RBEditor hold such an action registry. Then move this method to + // constructor public void setEditor(AbstractMessagesEditor editor) { this.editor = editor; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.action.Action#run() */ public void run() { - // created choose locale dialog - Dialog localeDialog = new Dialog(editor.getSite().getShell()) { - LocaleSelector selector; - - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Add new local"); - } - - @Override - protected Control createDialogArea(Composite parent) { - Composite comp = (Composite) super.createDialogArea(parent); - selector = new LocaleSelector(comp); - return comp; - } - - @Override - protected void okPressed() { - // add local to bundleGroup - MessagesBundleGroup bundleGroup = editor.getBundleGroup(); - Locale newLocal = selector.getSelectedLocale(); - - // exists local already? - boolean existsLocal = false; - Locale[] locales = bundleGroup.getLocales(); - for (Locale locale : locales) { - if (locale == null) { - if (newLocal == null) { - existsLocal = true; - break; - } - } else if (locale.equals(newLocal)) { - existsLocal = true; - break; - } - } - - if (! existsLocal) - bundleGroup.addMessagesBundle(newLocal); - - super.okPressed(); - } - }; - // open dialog - localeDialog.open(); + // created choose locale dialog + Dialog localeDialog = new Dialog(editor.getSite().getShell()) { + LocaleSelector selector; + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Add new local"); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite comp = (Composite) super.createDialogArea(parent); + selector = new LocaleSelector(comp); + return comp; + } + + @Override + protected void okPressed() { + // add local to bundleGroup + MessagesBundleGroup bundleGroup = editor.getBundleGroup(); + Locale newLocal = selector.getSelectedLocale(); + + // exists local already? + boolean existsLocal = false; + Locale[] locales = bundleGroup.getLocales(); + for (Locale locale : locales) { + if (locale == null) { + if (newLocal == null) { + existsLocal = true; + break; + } + } else if (locale.equals(newLocal)) { + existsLocal = true; + break; + } + } + + if (!existsLocal) + bundleGroup.addMessagesBundle(newLocal); + + super.okPressed(); + } + }; + // open dialog + localeDialog.open(); } } 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 f0710190..6e117f55 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 @@ -14,17 +14,17 @@ import org.eclipse.babel.core.message.checks.proximity.LevenshteinDistanceAnalyzer; /** - * Provides the {@link IProximityAnalyzer} - * <br><br> + * Provides the {@link IProximityAnalyzer} <br> + * <br> * * @author Alexej Strelzow */ public class AnalyzerFactory { - /** - * @return An instance of the {@link LevenshteinDistanceAnalyzer} - */ - public static IProximityAnalyzer getLevenshteinDistanceAnalyzer () { - return (IProximityAnalyzer) LevenshteinDistanceAnalyzer.getInstance(); - } + /** + * @return An instance of the {@link LevenshteinDistanceAnalyzer} + */ + public static IProximityAnalyzer getLevenshteinDistanceAnalyzer() { + return (IProximityAnalyzer) 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 7be5ff36..335c8e40 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 @@ -8,24 +8,28 @@ import org.eclipse.ui.IWorkbenchPage; /** - * Util class for editor operations. - * <br><br> + * 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) { - AbstractMessagesEditor editor = (AbstractMessagesEditor)page.getActiveEditor(); + + /** + * @param page + * The {@link IWorkbenchPage} + * @return The selected {@link IKeyTreeNode} of the page. + */ + public static IKeyTreeNode getSelectedKeyTreeNode(IWorkbenchPage page) { + AbstractMessagesEditor editor = (AbstractMessagesEditor) 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(); + if (!selection.isEmpty() + && selection instanceof IStructuredSelection) { + return (IKeyTreeNode) ((IStructuredSelection) selection) + .getFirstElement(); } } return null; diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java index 88e53f98..f2e6173b 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java @@ -18,20 +18,20 @@ 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 addValue(Locale locale, String value); - public void setValue(Locale locale, String newValue); + public void setValue(Locale locale, String newValue); - public String getValue(Locale locale); + public String getValue(Locale locale); - public Collection<String> getValues(); + public Collection<String> getValues(); - public void setInfo(Object info); + public void setInfo(Object info); - public Object getInfo(); + public Object getInfo(); - public Collection<Locale> getLocales(); + 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 f79ae8fe..5c16b9b6 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 @@ -16,35 +16,42 @@ 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> + * @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); + /** + * @param messagesBundleGroup + * Input of the key tree model + * @return The {@link IAbstractKeyTreeModel} + */ + public static IAbstractKeyTreeModel createModel( + IMessagesBundleGroup messagesBundleGroup) { + return new AbstractKeyTreeModel( + (MessagesBundleGroup) messagesBundleGroup); } - + /** - * @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} + * @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) { + 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/ValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java index 89ab1a6f..2e3eef9b 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 @@ -21,36 +21,36 @@ import org.eclipse.babel.core.message.tree.IKeyTreeNode; import org.eclipse.babel.core.message.tree.internal.KeyTreeNode; +public class ValuedKeyTreeNode extends KeyTreeNode implements + IValuedKeyTreeNode { -public class ValuedKeyTreeNode extends KeyTreeNode implements IValuedKeyTreeNode { - - public ValuedKeyTreeNode(IKeyTreeNode parent, String name, String messageKey, - IMessagesBundleGroup messagesBundleGroup) { + 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) { + public void initValues(Map<Locale, String> values) { this.values = values; } - public void addValue (Locale locale, String value) { + public void addValue(Locale locale, String value) { values.put(locale, value); } - - public String getValue (Locale locale) { + + 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); + if (values.containsKey(locale)) + values.remove(locale); + addValue(locale, newValue); } - - public Collection<String> getValues () { + + public Collection<String> getValues() { return values.values(); } @@ -61,13 +61,13 @@ public void setInfo(Object info) { public Object getInfo() { return info; } - - public Collection<Locale> getLocales () { - List<Locale> locs = new ArrayList<Locale> (); + + public Collection<Locale> getLocales() { + List<Locale> locs = new ArrayList<Locale>(); for (Locale loc : values.keySet()) { locs.add(loc); } return locs; } - + } 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 93fb1470..779824ff 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 @@ -41,254 +41,279 @@ /** * @author Pascal Essiembre - * + * */ public class Builder extends IncrementalProjectBuilder { - public static final String BUILDER_ID = - "org.eclipse.babel.editor.rbeBuilder"; //$NON-NLS-1$ - + 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 + + 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: + 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: + 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; - } - } + // 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; - } - } + 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. */ + /** + * 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. + * 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; - } + 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? + /** + * 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; + return; } - //System.err.println("Looking at " + file.getFullPath()); + // System.err.println("Looking at " + file.getFullPath()); deleteMarkers(file); MessagesBundleGroup msgBundleGrp = null; if (_alreadBuiltMessageBundle == null) { - _alreadBuiltMessageBundle = new HashMap<IFile,MessagesBundleGroup>(); - _resourcesToValidate = new HashSet(); + _alreadBuiltMessageBundle = new HashMap<IFile, MessagesBundleGroup>(); + _resourcesToValidate = new HashSet(); } else { - msgBundleGrp = _alreadBuiltMessageBundle.get(file); + 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); - } - } - } + 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) { - } - } + /** + * 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); - protected void fullBuild(final IProgressMonitor monitor) - throws CoreException { -// System.out.println("Builder: fullBuild"); //$NON-NLS-1$ + 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$ + 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); - } - - + } + + protected void clean(IProgressMonitor monitor) throws CoreException { + ResourcesPlugin + .getWorkspace() + .getRoot() + .deleteMarkers(MessagesEditorPlugin.MARKER_TYPE, false, + IResource.DEPTH_INFINITE); + } + } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java index 49599cbc..6436f902 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java @@ -18,73 +18,75 @@ public class Nature implements IProjectNature { - /** - * ID of this project nature - */ - public static final String NATURE_ID = "org.eclipse.babel.editor.rbeNature"; + /** + * ID of this project nature + */ + public static final String NATURE_ID = "org.eclipse.babel.editor.rbeNature"; - private IProject project; + 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(); + /* + * (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; - } - } + 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); - } + 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#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#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; - } + /* + * (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.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java index cbef6339..fdc796b1 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java @@ -24,126 +24,133 @@ import org.eclipse.ui.IWorkbenchPart; 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 - } - } - + /** + * 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); + } + } - private ISelection selection; + /** + * + * @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 + } - /* - * (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; - } + private ISelection 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) { - } + /* + * (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); + } + } + } + } - /** - * 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(); + /** + * 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; + } - 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; - } - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface. + * action.IAction, org.eclipse.ui.IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + } - // 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) { - } - } + /** + * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java index f55b9276..3e02bac2 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java @@ -10,7 +10,6 @@ ******************************************************************************/ package org.eclipse.babel.editor.builder; - /** * @author hmalphettes */ diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java index 069e8ea8..0574b6ab 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java @@ -10,7 +10,6 @@ ******************************************************************************/ package org.eclipse.babel.editor.builder; - /** * @author hmalphettes */ 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 d3addff3..36c9b95f 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 @@ -13,16 +13,14 @@ import org.eclipse.babel.core.message.internal.MessagesBundleGroup; import org.eclipse.core.resources.IResource; - /** * @author Pascal Essiembre - * + * */ public class BundleGroupRegistry { - public static MessagesBundleGroup getBundleGroup(IResource resource) { - return null;//MessagesBundleGroupFactory. + return null;// MessagesBundleGroupFactory. } - + } 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 c00b9fb3..98f055f9 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 @@ -43,22 +43,21 @@ import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.part.FileEditorInput; - /** - * MessagesBundle group strategy for standard properties file structure. That is, - * all *.properties files of the same base name within the same directory. + * 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$ + 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. */ @@ -67,58 +66,59 @@ public class DefaultBundleGroupStrategy implements IMessagesBundleGroupStrategy 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 + * + * @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$ + 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$ - + this.baseName = file.getName().replaceFirst(namePattern, "$1"); //$NON-NLS-1$ + // File matching pattern - this.fileMatchPattern = - "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$ + this.fileMatchPattern = "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$ } /** * @see org.eclipse.babel.core.message.internal.strategy.IMessagesBundleGroupStrategy - * #createMessagesBundleGroupName() + * #createMessagesBundleGroupName() */ public String createMessagesBundleGroupName() { - return getProjectName()+"*.properties"; + return getProjectName() + "*.properties"; } - + public String createMessagesBundleId() { - return getResourceBundleId(file); + 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 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$ + 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$ @@ -127,25 +127,25 @@ public static String getResourceBundleName(IResource res) { /** * @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy - * #loadMessagesBundles() + * #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; - } + 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$ + throw new MessageException("Can't load resource bundles.", e); //$NON-NLS-1$ } for (int i = 0; i < resources.length; i++) { @@ -154,78 +154,90 @@ protected void collectBundlesInContainer(IContainer container, if (resource instanceof IFile && resourceName.matches(fileMatchPattern)) { // Build local title - String localeText = resourceName.replaceFirst( - fileMatchPattern, "$2"); //$NON-NLS-1$ + String localeText = resourceName.replaceFirst(fileMatchPattern, + "$2"); //$NON-NLS-1$ Locale locale = BabelUtils.parseLocale(localeText); if (UIUtils.isDisplayed(locale)) { - bundlesCollector.add(createBundle(locale, resource)); + bundlesCollector.add(createBundle(locale, resource)); } } } - + } - /* (non-Javadoc) - * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy#createBundle(java.util.Locale) + /* + * (non-Javadoc) + * + * @see + * org.eclipse.babel.core.bundle.IBundleGroupStrategy#createBundle(java. + * util.Locale) */ public MessagesBundle createMessagesBundle(Locale locale) { - // create new empty locale file - IFile openedFile = getOpenedFile(); - IPath path = openedFile.getProjectRelativePath(); - String localeStr = locale != null ? "_" + locale.toString() : ""; - String newFilename = getBaseName()+localeStr+"."+openedFile.getFileExtension(); - IFile newFile = openedFile.getProject().getFile(path.removeLastSegments(1).addTrailingSeparator()+newFilename); - - if (! newFile.exists()) { - try { - // create new ifile with an empty input stream - newFile.create(new ByteArrayInputStream(new byte[0]), IResource.NONE, null); - } catch (CoreException e) { - e.printStackTrace(); - } + // create new empty locale file + IFile openedFile = getOpenedFile(); + IPath path = openedFile.getProjectRelativePath(); + String localeStr = locale != null ? "_" + locale.toString() : ""; + String newFilename = getBaseName() + localeStr + "." + + openedFile.getFileExtension(); + IFile newFile = openedFile.getProject() + .getFile( + path.removeLastSegments(1).addTrailingSeparator() + + newFilename); + + if (!newFile.exists()) { + try { + // create new ifile with an empty input stream + newFile.create(new ByteArrayInputStream(new byte[0]), + IResource.NONE, null); + } catch (CoreException e) { + e.printStackTrace(); + } } - return createBundle(locale, newFile); + return createBundle(locale, newFile); } - + /** * Creates a resource bundle for an existing resource. - * @param locale locale for which to create a bundle - * @param resource resource used to create bundle + * + * @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 + + // 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, + // site is null during the build. + messagesResource = new PropertiesIFileResource(locale, new PropertiesSerializer(prefs.getSerializerConfig()), - new PropertiesDeserializer(prefs.getDeserializerConfig()), + new PropertiesDeserializer(prefs + .getDeserializerConfig()), (IFile) resource, MessagesEditorPlugin.getDefault()); } else { - messagesResource = new EclipsePropertiesEditorResource( - locale, + messagesResource = new EclipsePropertiesEditorResource(locale, new PropertiesSerializer(prefs.getSerializerConfig()), - new PropertiesDeserializer(prefs.getDeserializerConfig()), - createEditor(resource, locale)); + 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$ + 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 site * @param resource * @param locale * @return @@ -233,17 +245,16 @@ protected MessagesBundle createBundle(Locale locale, IResource resource) */ 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); + 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 @@ -257,23 +268,24 @@ protected TextEditor createEditor(IResource resource, Locale locale) } return textEditor; } - + /** * @return The file opened. */ protected IFile getOpenedFile() { - return file; + return file; } - /** + /** * @return The base name of the resource bundle. */ protected String getBaseName() { - return baseName; + return baseName; } - + public String getProjectName() { - return ResourcesPlugin.getWorkspace().getRoot().getProject(file.getFullPath().segments()[0]).getName(); + return ResourcesPlugin.getWorkspace().getRoot() + .getProject(file.getFullPath().segments()[0]).getName(); } - + } 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 b690c280..2b6b5768 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 @@ -30,12 +30,11 @@ import org.eclipse.core.runtime.Path; import org.eclipse.ui.IEditorSite; - /** * @author Pascal Essiembre * @author Hugues Malphettes */ -//TODO make /*default*/ that only the registry would use +// TODO make /*default*/ that only the registry would use public final class MessagesBundleGroupFactory { /** @@ -46,216 +45,227 @@ private MessagesBundleGroupFactory() { } /** - * Creates a new bundle group, based on the given site and file. Currently, + * 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); - } + 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(); + try { + if (proj == null || !proj.hasNature(UIUtils.PDE_NATURE)) { //$NON-NLS-1$ + return createDefaultBundleGroup(site, file); + } + } catch (CoreException e) { + } + + IFolder nl = getNLFolder(file); - //check we are inside an eclipse plugin project where NL is supported at runtime: - IProject proj = file.getProject(); - try { - if (proj == null || !proj.hasNature(UIUtils.PDE_NATURE)) { //$NON-NLS-1$ - return createDefaultBundleGroup(site, file); - } - } catch (CoreException e) { } + // 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)); + } - 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 (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)); + // 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)); + 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 ? - + + // 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. + * pde-project that is a fragment. null otherwise. */ static String getHostPluginId(IResource file) { - return getPDEManifestAttribute(file, FRAG_HOST); + 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. + * pde-project. null otherwise. */ static String getBundleId(IResource file) { - return getPDEManifestAttribute(file, BUNDLE_NAME); + 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). + * 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; + 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. + * @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; + 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. + * 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); + 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.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 2611de92..d4a78077 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 @@ -54,12 +54,12 @@ import org.osgi.framework.Bundle; /** - * This strategy is used when a resource bundle that belongs to a plug-in fragment - * project is loaded. + * 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 + * 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 @@ -70,22 +70,22 @@ * * @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> + * @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; - - - /** + private final String _fragmentHostID; + + private boolean hostPluginInWorkspaceWasLookedFor = false; + private IProject hostPluginInWorkspace; + + /** * */ public NLFragmentBundleGroupStrategy(IEditorSite site, IFile file, - String fragmentHostID, IFolder nlFolder) { + String fragmentHostID, IFolder nlFolder) { super(site, file, nlFolder); _fragmentHostID = fragmentHostID; } @@ -94,40 +94,40 @@ public NLFragmentBundleGroupStrategy(IEditorSite site, IFile file, * @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(); - } + 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) + * #createBundle(java.util.Locale) */ public MessagesBundle createMessagesBundle(Locale locale) { return super.createMessagesBundle(locale); @@ -135,371 +135,382 @@ public MessagesBundle createMessagesBundle(Locale locale) { /** * @see org.eclipse.babel.core.message.internal.strategy.IMessagesBundleGroupStrategy - * #createMessagesBundleGroupName() + * #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. + * the edited resource bundle once this code is executed by eclipse. * @throws CoreException - * @throws IOException + * @throws IOException */ - private MessagesBundle loadDefaultMessagesBundle() - throws IOException, CoreException { + 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 + // 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. + 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()); - } + + 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 (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); + // 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); + 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); + + EclipsePropertiesEditorResource readOnly = new EclipsePropertiesEditorResource( + UIUtils.ROOT_LOCALE, new PropertiesSerializer( + prefs.getSerializerConfig()), + new PropertiesDeserializer(prefs.getDeserializerConfig()), + textEditor); if (resourceLocationLabel != null) { - readOnly.setResourceLocationLabel(resourceLocationLabel); + readOnly.setResourceLocationLabel(resourceLocationLabel); } return new MessagesBundle(readOnly); } // we did not find it. - return null; + return null; } - + private String getContents(InputStream in) throws IOException { - Reader reader = new BufferedReader( - new InputStreamReader(in)); - //, "ISO 8859-1");need to find actual name + 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); + 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. + * 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; + 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> + * 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$ + 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(); + * @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); + 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. + * @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. + // 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 + * @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$ + 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 + * @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$ + 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; + + 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. + * 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 { @@ -507,7 +518,7 @@ private class DummyEditorInput implements IStorageEditorInput, IStorage { * the error messages as a Java inputStream. */ private String _contents; - + /** * the name of the input */ @@ -517,23 +528,28 @@ private class DummyEditorInput implements IStorageEditorInput, IStorage { * the tooltip text, optional */ private String _toolTipText; - + /** - * Simplified constructor that does not need - * a tooltip, the name is used instead + * 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) { + 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. + * + * @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(); @@ -592,7 +608,7 @@ public Object getAdapter(Class adapter) { } // the methods to implement as an IStorage object - + /** * the contents */ @@ -614,100 +630,100 @@ 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. + * 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. + * 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; + 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. + * 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; + 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); + Bundle bundle = Platform.getBundle(_fragmentHostID); if (bundle != null) { - return bundle; + return bundle; } - return null; + return null; } - + } 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 cd7faa9b..f1d096a3 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 @@ -31,19 +31,18 @@ import org.eclipse.core.runtime.Path; import org.eclipse.ui.IEditorSite; - /** - * MessagesBundle group strategies for dealing with Eclipse "NL" - * directory structure within a plugin. + * 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}. + * 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 + * Note it is unclear how * <p> * * @@ -51,52 +50,55 @@ * @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; - + 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 + * @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) { + 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 + * @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) { + IFolder nlFolder) { super(site, file); this.nlFolder = nlFolder; } @@ -106,318 +108,329 @@ public NLPluginBundleGroupStrategy(IEditorSite site, IFile file, */ 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); - } - } - } - - } - + 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); + collectBundlesInContainer(getOpenedFile().getParent(), bundles); return bundles.toArray(EMPTY_BUNDLES); } if (nlFolder != null) { - nlFolders.add(nlFolder); + nlFolders.add(nlFolder); } - //get the nl directory. - //navigate the entire directory from there - //and look for the file with the same file names. + // 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; - } + 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); + Locale locale = extractLocale(getOpenedFile(), true); if (UIUtils.isDisplayed(locale)) { - bundles.add(createBundle(locale, getOpenedFile())); + bundles.add(createBundle(locale, getOpenedFile())); } for (IFolder nlFolder : nlFolders) { - nlFolder.accept(visitor); + 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; } - } 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); - } + } + 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); + + 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. + * 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; + 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. + * 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. + * @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(); + 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; - } + return null; + } if (docomputeBasePath) { - basePathInsideNL = ""; - return new Locale(lang); + basePathInsideNL = ""; + return new Locale(lang); } else if ("".equals(basePathInsideNL)) { - return new Locale(lang); + return new Locale(lang); } else { - return null; + 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; - } - } - } + 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); + basePathInsideNL = ""; + return new Locale(lang, country); } else if (basePathInsideNL.equals(country)) { - return new Locale(lang, country); + return new Locale(lang, country); } else { - return null; + 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()); - } + 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); + basePathInsideNL = b.toString(); + return new Locale(lang, country); } else if (basePathInsideNL.equals(b.toString())) { - return new Locale(lang); + return new Locale(lang); } else { - return null; + return null; } - } - StringBuffer b = new StringBuffer(); - while (tokens.hasMoreTokens()) { - b.append("/" + tokens.nextToken()); - } + } + StringBuffer b = new StringBuffer(); + while (tokens.hasMoreTokens()) { + b.append("/" + tokens.nextToken()); + } if (docomputeBasePath) { - basePathInsideNL = b.toString(); - return new Locale(lang, country, variant); + basePathInsideNL = b.toString(); + return new Locale(lang, country, variant); } else if (basePathInsideNL.equals(b.toString())) { - return new Locale(lang); + return new Locale(lang); } else { - return null; + return null; } - } - } - return UIUtils.ROOT_LOCALE; + } + } + 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. + * 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(); + return getOpenedFile().getProject().getFolder(folderName).exists(); } - + } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/AbstractI18NEntry.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/AbstractI18NEntry.java index 1e9b21c9..b6c1fd8f 100755 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/AbstractI18NEntry.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/AbstractI18NEntry.java @@ -42,6 +42,7 @@ /** * Tree for displaying and navigating through resource bundle keys. + * * @author Pascal Essiembre */ public abstract class AbstractI18NEntry extends Composite { @@ -55,31 +56,32 @@ public abstract class AbstractI18NEntry extends Composite { protected NullableText textBox; private CBanner banner; protected String focusGainedText; - + public static final String INSTANCE_CLASS = "org.eclipse.babel.editor.i18n.I18NEntry"; - + private IMessagesEditorChangeListener msgEditorUpdateKey = new MessagesEditorChangeAdapter() { public void selectedKeyChanged(String oldKey, String newKey) { - updateKey(newKey); + updateKey(newKey); } }; - + /** * Constructor. - * @param parent parent composite - * @param keyTree key tree + * + * @param parent + * parent composite + * @param keyTree + * key tree */ - public AbstractI18NEntry( - Composite parent, - final AbstractMessagesEditor editor, - final Locale locale) { + public AbstractI18NEntry(Composite parent, + final AbstractMessagesEditor 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 gridLayout = new GridLayout(1, false); gridLayout.horizontalSpacing = 0; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; @@ -87,716 +89,716 @@ public AbstractI18NEntry( setLayout(gridLayout); GridData gd = new GridData(GridData.FILL_BOTH); -// gd.heightHint = 80; + // 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.setRightWidth(300); banner.setSimple(false); banner.setLayoutData(gridData); - createTextbox(); - - } - - + } public AbstractMessagesEditor 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); - + 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); + 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 = editor.getBundleGroup(); + IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale); - return ((TextEditor) bundle.getResource().getSource()).isEditable(); + return ((TextEditor) bundle.getResource().getSource()).isEditable(); } - + public String getResourceLocationLabel() { - IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); - IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale); - return bundle.getResource().getResourceLocationLabel(); + IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); + IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale); + return bundle.getResource().getResourceLocationLabel(); } - -// /*default*/ Text getTextBox() { -// return textBox; -// } - + + // /*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 = 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) { + 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 + // -- 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 + + // --- 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; -// } + // if (!MsgEditorPreferences.getFieldTabInserts() + // && event.character == SWT.TAB) { + // event.doit = true; + // } } }); // Handle dirtyness textBox.addKeyListener(getKeyListener()); - + editor.addChangeListener(msgEditorUpdateKey); } - - abstract void updateKey(String key); - - abstract KeyListener getKeyListener(); + + abstract void updateKey(String key); + + abstract KeyListener getKeyListener(); protected void updateModel() { if (editor.getSelectedKey() != null) { if (!BabelUtils.equals(focusGainedText, textBox.getText())) { - //IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId); - IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); + // IMessagesBundleGroup messagesBundleGroup = + // RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId); + IMessagesBundleGroup messagesBundleGroup = editor + .getBundleGroup(); String key = editor.getSelectedKey(); IMessage entry = messagesBundleGroup.getMessage(key, locale); if (entry == null) { entry = new Message(key, locale); - IMessagesBundle messagesBundle = messagesBundleGroup.getMessagesBundle(locale); + IMessagesBundle messagesBundle = messagesBundleGroup + .getMessagesBundle(locale); if (messagesBundle != null) { - messagesBundle.addMessage(entry); + messagesBundle.addMessage(entry); } } entry.setText(textBox.getText()); } } } - + @Override public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - textBox.setEnabled(enabled); + super.setEnabled(enabled); + textBox.setEnabled(enabled); } - + @Override public void dispose() { - editor.removeChangeListener(msgEditorUpdateKey); - super.dispose(); + editor.removeChangeListener(msgEditorUpdateKey); + super.dispose(); } - -} - - - - - - +} -//TODO Grab and Apply font fix: -///** +// 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) { +// 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); +// 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); +// 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); +// 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( +// 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( +// simButton.addSelectionListener(new SelectionAdapter() { +// public void widgetSelected(SelectionEvent event) { +// String head = RBEPlugin.getString( // "dialog.similar.head"); //$NON-NLS-1$ -// String body = RBEPlugin.getString( +// String body = RBEPlugin.getString( // "dialog.similar.body", activeKey, //$NON-NLS-1$ -// UIUtils.getDisplayName(locale)); +// UIUtils.getDisplayName(locale)); // body += "\n\n"; //$NON-NLS-1$ -// for (Iterator iter = similarVisitor.getSimilars().iterator(); -// iter.hasNext();) { +// for (Iterator iter = similarVisitor.getSimilars().iterator(); +// iter.hasNext();) { // body += " " //$NON-NLS-1$ -// + ((Message) iter.next()).getKey() +// + ((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); +// } +// 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( +// 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( +// duplButton.addSelectionListener(new SelectionAdapter() { +// public void widgetSelected(SelectionEvent event) { +// String head = RBEPlugin.getString( // "dialog.identical.head"); //$NON-NLS-1$ -// String body = RBEPlugin.getString( +// String body = RBEPlugin.getString( // "dialog.identical.body", activeKey, //$NON-NLS-1$ -// UIUtils.getDisplayName(locale)); +// UIUtils.getDisplayName(locale)); // body += "\n\n"; //$NON-NLS-1$ -// for (Iterator iter = duplVisitor.getDuplicates().iterator(); -// iter.hasNext();) { +// for (Iterator iter = duplVisitor.getDuplicates().iterator(); +// iter.hasNext();) { // body += " " //$NON-NLS-1$ -// + ((Message) iter.next()).getKey() +// + ((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); +// } +// 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( +// 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( +// 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( +// 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; -// } - -//} +// 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.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java index e06916d1..eae73818 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java @@ -28,47 +28,50 @@ /** * 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 + * + * @param parent + * parent composite + * @param keyTree + * key tree */ - public EntryLeftBanner( - Composite parent, - final AbstractI18NEntry i18NEntry) { + public EntryLeftBanner(Composite parent, final AbstractI18NEntry 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")); - - + // 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.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( @@ -76,8 +79,8 @@ public void widgetSelected(SelectionEvent e) { } }); - //TODO have "show country flags" in preferences. - //TODO have text aligned bottom next to flag icon. + // 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); @@ -85,10 +88,11 @@ public void widgetSelected(SelectionEvent e) { } } - /** * Loads country icon based on locale country. - * @param countryLocale the locale on which to grab the 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) { @@ -102,9 +106,9 @@ private Image loadCountryIcon(Locale countryLocale) { countryCode.toLowerCase() + ".gif"; //$NON-NLS-1$ image = UIUtils.getImage(imageName); } -// if (image == null) { -// image = UIUtils.getImage("countries/blank.gif"); //$NON-NLS-1$ -// } + // if (image == null) { + // image = UIUtils.getImage("countries/blank.gif"); //$NON-NLS-1$ + // } return image; } 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 5d26802f..48a077eb 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 @@ -37,6 +37,7 @@ /** * Tree for displaying and navigating through resource bundle keys. + * * @author Pascal Essiembre */ public class EntryRightBanner extends Composite { @@ -58,20 +59,21 @@ public void selectedKeyChanged(String oldKey, String newKey) { updateMarkers(); } }; - + /** * Constructor. - * @param parent parent composite - * @param keyTree key tree + * + * @param parent + * parent composite + * @param keyTree + * key tree */ - public EntryRightBanner( - Composite parent, - final AbstractI18NEntry i18nEntry) { + public EntryRightBanner(Composite parent, final AbstractI18NEntry 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; @@ -80,19 +82,18 @@ public EntryRightBanner( layout.marginTop = 0; warningIcon = new Label(this, SWT.NONE); - warningIcon.setImage( - PlatformUI.getWorkbench().getSharedImages().getImage( - ISharedImages.IMG_OBJS_WARN_TSK)); + 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(msgEditorChangeListener); editor.getMarkers().addObserver(observer); } @@ -102,60 +103,59 @@ public EntryRightBanner( * @param colon */ private void updateMarkers() { - Display display = toolBarMgr.getControl().getDisplay(); - // [RAP] only update markers, which belong to this UIThread - if (display.equals(Display.getCurrent()) && ! isDisposed()) { - display.asyncExec(new Runnable () { - public void run() { - if (isDisposed()) - return; - // 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); - } - // } - }); + Display display = toolBarMgr.getControl().getDisplay(); + // [RAP] only update markers, which belong to this UIThread + if (display.equals(Display.getCurrent()) && !isDisposed()) { + display.asyncExec(new Runnable() { + public void run() { + if (isDisposed()) + return; + // 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) { + + 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); + ((DuplicateValueCheck) check).getDuplicateKeys(), key, + locale); } return null; } - + @Override public void dispose() { - editor.removeChangeListener(msgEditorChangeListener); - editor.getMarkers().deleteObserver(observer); - super.dispose(); + editor.removeChangeListener(msgEditorChangeListener); + editor.getMarkers().deleteObserver(observer); + super.dispose(); } } 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 23654e40..6ba23488 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 @@ -41,98 +41,114 @@ import org.eclipse.ui.IWorkbenchPart; /** - * Internationalization page where one can edit all resource bundle entries - * at once for all supported locales. + * 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; protected final AbstractMessagesEditor editor; protected final SideNavComposite keysComposite; private final Composite valuesComposite; - private final Map<Locale,AbstractI18NEntry> entryComposites = new HashMap<Locale,AbstractI18NEntry>(); + private final Map<Locale, AbstractI18NEntry> entryComposites = new HashMap<Locale, AbstractI18NEntry>(); private Composite entriesComposite; - -// private Composite parent; + + // private Composite parent; private boolean keyTreeVisible = true; - -// private final StackLayout layout = new StackLayout(); + + // 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 + * + * @param parent + * parent component. + * @param style + * style to apply to this component + * @param resourceMediator + * resource manager */ - public I18NPage( - Composite parent, int style, + public I18NPage(Composite parent, int style, final AbstractMessagesEditor editor) { super(parent, style); - this.editor = editor; + this.editor = editor; sashForm = new SashForm(this, SWT.SMOOTH); - sashForm.setBackground(UIUtils.getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT)); - editor.getEditorSite().getPage().addPartListener(new IPartListener(){ + 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)); + 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)); + sashForm.setBackground(UIUtils + .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } } - public void partBroughtToTop(IWorkbenchPart part) {} - public void partClosed(IWorkbenchPart part) {} - public void partOpened(IWorkbenchPart part) {} + + 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}); + sashForm.setWeights(new int[] { 25, 75 }); setExpandHorizontal(true); setExpandVertical(true); setMinWidth(400); - - RBManager instance = RBManager.getInstance(editor.getBundleGroup().getProjectName()); + + 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) { - // [RAP] only update tree, which belongs to this UIThread - Display display = keysComposite.getTreeViewer().getTree().getDisplay(); - if (display.equals(Display.getCurrent())) { - AbstractI18NEntry i18nEntry = entryComposites.get(bundle.getLocale()); - if (i18nEntry != null && !getSelection().isEmpty()) { - i18nEntry.updateKey(String.valueOf(((IStructuredSelection)getSelection()).getFirstElement())); - } - } - } - - }); + + public void onSave() { + // TODO Auto-generated method stub + + } + + public void onModify() { + // TODO Auto-generated method stub + } + + public void onResourceChanged(IMessagesBundle bundle) { + // [RAP] only update tree, which belongs to this UIThread + Display display = keysComposite.getTreeViewer().getTree() + .getDisplay(); + if (display.equals(Display.getCurrent())) { + AbstractI18NEntry i18nEntry = entryComposites.get(bundle + .getLocale()); + if (i18nEntry != null && !getSelection().isEmpty()) { + i18nEntry.updateKey(String + .valueOf(((IStructuredSelection) getSelection()) + .getFirstElement())); + } + } + } + + }); } - + /** * @see org.eclipse.swt.widgets.Widget#dispose() */ @@ -140,7 +156,7 @@ public void dispose() { keysComposite.dispose(); super.dispose(); } - + public void setKeyTreeVisible(boolean visible) { keyTreeVisible = visible; if (visible) { @@ -148,30 +164,28 @@ public void setKeyTreeVisible(boolean visible) { } else { sashForm.setMaximizedControl(valuesComposite); } - for (IMessagesEditorChangeListener listener : editor.getChangeListeners()) { - listener.keyTreeVisibleChanged(visible); + 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); + final ScrolledComposite scrolledComposite = new ScrolledComposite( + parent, SWT.V_SCROLL | SWT.H_SCROLL); scrolledComposite.setExpandHorizontal(true); scrolledComposite.setExpandVertical(true); scrolledComposite.setSize(SWT.DEFAULT, 100); entriesComposite = new Composite(scrolledComposite, SWT.BORDER); scrolledComposite.setContent(entriesComposite); - scrolledComposite.setMinSize(entriesComposite.computeSize( - SWT.DEFAULT, + 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); @@ -180,102 +194,100 @@ private Composite createValuesComposite(SashForm parent) { Locale locale = locales[i]; addI18NEntry(editor, locale); } - + editor.addChangeListener(new MessagesEditorChangeAdapter() { public void selectedKeyChanged(String oldKey, String newKey) { - boolean isKey = - newKey != null && editor.getBundleGroup().isMessageKey(newKey); -// scrolledComposite.setBackground(isKey); + boolean isKey = newKey != null + && editor.getBundleGroup().isMessageKey(newKey); + // scrolledComposite.setBackground(isKey); } }); - - return scrolledComposite; } - + public void addI18NEntry(AbstractMessagesEditor editor, Locale locale) { - AbstractI18NEntry i18NEntry = null; - try { - Class<?> clazz = Class - .forName(AbstractI18NEntry.INSTANCE_CLASS); - Constructor<?> cons = clazz.getConstructor(Composite.class, AbstractMessagesEditor.class, Locale.class); - i18NEntry = (AbstractI18NEntry) cons - .newInstance(entriesComposite, editor, locale); - } catch (Exception e) { - e.printStackTrace(); - } -// entryComposite.addFocusListener(localBehaviour); + AbstractI18NEntry i18NEntry = null; + try { + Class<?> clazz = Class.forName(AbstractI18NEntry.INSTANCE_CLASS); + Constructor<?> cons = clazz.getConstructor(Composite.class, + AbstractMessagesEditor.class, Locale.class); + i18NEntry = (AbstractI18NEntry) cons.newInstance(entriesComposite, + editor, locale); + } catch (Exception e) { + e.printStackTrace(); + } + // entryComposite.addFocusListener(localBehaviour); entryComposites.put(locale, i18NEntry); entriesComposite.layout(); } - + public void removeI18NEntry(Locale locale) { - AbstractI18NEntry i18NEntry = entryComposites.get(locale); - if (i18NEntry != null) { - i18NEntry.dispose(); - entryComposites.remove(locale); - entriesComposite.layout(); - } + AbstractI18NEntry i18NEntry = entryComposites.get(locale); + if (i18NEntry != null) { + i18NEntry.dispose(); + entryComposites.remove(locale); + entriesComposite.layout(); + } } - + public void selectLocale(Locale locale) { Collection<Locale> locales = entryComposites.keySet(); for (Locale entryLocale : locales) { - AbstractI18NEntry 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(); -// } + AbstractI18NEntry 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) { + public void removeSelectionChangedListener( + ISelectionChangedListener listener) { keysComposite.getTreeViewer().removeSelectionChangedListener(listener); } public void setSelection(ISelection selection) { keysComposite.getTreeViewer().setSelection(selection); } - + public TreeViewer getTreeViewer() { - return keysComposite.getTreeViewer(); + return keysComposite.getTreeViewer(); } - + @Override public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - for (AbstractI18NEntry entry : entryComposites.values()) - entry.setEnabled(enabled); + super.setEnabled(enabled); + for (AbstractI18NEntry entry : entryComposites.values()) + entry.setEnabled(enabled); } - + public void setEnabled(boolean enabled, Locale locale) { - //super.setEnabled(enabled); - for (AbstractI18NEntry entry : entryComposites.values()) { - if ( locale == entry.getLocale() || (locale != null && locale.equals(entry.getLocale())) ) { - entry.setEnabled(enabled); - break; - } - } + // super.setEnabled(enabled); + for (AbstractI18NEntry entry : entryComposites.values()) { + if (locale == entry.getLocale() + || (locale != null && locale.equals(entry.getLocale()))) { + entry.setEnabled(enabled); + break; + } + } } - + public SideNavTextBoxComposite getSidNavTextBoxComposite() { - return keysComposite.getSidNavTextBoxComposite(); + return keysComposite.getSidNavTextBoxComposite(); } } - 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 0f1b03dd..b31a4f86 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 @@ -27,23 +27,28 @@ /** * Tree for displaying and navigating through resource bundle keys. + * * @author Pascal Essiembre */ public class SideNavComposite extends Composite { /** Key Tree Viewer. */ private TreeViewer treeViewer; - + private AbstractMessagesEditor editor; - + private SideNavTextBoxComposite textBoxComp; + /** * Constructor. - * @param parent parent composite - * @param keyTree key tree + * + * @param parent + * parent composite + * @param keyTree + * key tree */ - public SideNavComposite( - Composite parent, final AbstractMessagesEditor editor) { + public SideNavComposite(Composite parent, + final AbstractMessagesEditor editor) { super(parent, SWT.BORDER); this.editor = editor; @@ -51,11 +56,9 @@ public SideNavComposite( 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); + this.treeViewer = new TreeViewer(this, SWT.SINGLE | SWT.BORDER + | SWT.V_SCROLL | SWT.H_SCROLL); - setLayout(new GridLayout(1, false)); GridData gid; @@ -70,45 +73,47 @@ public SideNavComposite( 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(); + + // TODO have two toolbars, one left-align, and one right, with drop + // down menu + // initListener(); + + // createTopSection(); createKeyTree(); textBoxComp = 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); -// -// } + // 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. */ @@ -120,14 +125,13 @@ private void createKeyTree() { gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; - KeyTreeContributor treeContributor = new KeyTreeContributor(editor); treeContributor.contribute(treeViewer); - treeViewer.getTree().setLayoutData(gridData); + treeViewer.getTree().setLayoutData(gridData); } - + public SideNavTextBoxComposite getSidNavTextBoxComposite() { - return textBoxComp; + return textBoxComp; } } 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 b71754bb..fcca5ca8 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 @@ -30,26 +30,28 @@ /** * 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 Button addButton; private AbstractMessagesEditor editor; - + /** * Constructor. - * @param parent parent composite - * @param keyTree key tree + * + * @param parent + * parent composite + * @param keyTree + * key tree */ - public SideNavTextBoxComposite( - Composite parent, + public SideNavTextBoxComposite(Composite parent, final AbstractMessagesEditor editor) { super(parent, SWT.NONE); this.editor = editor; @@ -89,9 +91,9 @@ public void keyReleased(KeyEvent event) { String key = addTextBox.getText(); if (event.character == SWT.CR && isNewKey(key)) { addKey(key); - } else if (key.length() > 0){ + } else if (key.length() > 0) { NodePathRegexVisitor visitor = new NodePathRegexVisitor( - "^" + key + ".*"); //$NON-NLS-1$//$NON-NLS-2$ + "^" + key + ".*"); //$NON-NLS-1$//$NON-NLS-2$ editor.getKeyTreeModel().accept(visitor, null); IKeyTreeNode node = visitor.getKeyTreeNode(); if (node != null) { @@ -114,21 +116,21 @@ public void selectedKeyChanged(String oldKey, String 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; } - + @Override public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - addButton.setEnabled(enabled); + super.setEnabled(enabled); + addButton.setEnabled(enabled); } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java index f3eb425f..b59c3304 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java @@ -16,13 +16,13 @@ /** * @author Pascal Essiembre - * + * */ public class FoldingAction extends Action { private final AbstractI18NEntry i18NEntry; private boolean expanded; - + /** * */ @@ -31,12 +31,13 @@ public FoldingAction(AbstractI18NEntry i18NEntry) { this.i18NEntry = i18NEntry; this.expanded = i18NEntry.getExpanded(); setText("Collapse"); - setImageDescriptor( - UIUtils.getImageDescriptor("minus.gif")); - setToolTipText("TODO put something here"); //TODO put tooltip + setImageDescriptor(UIUtils.getImageDescriptor("minus.gif")); + setToolTipText("TODO put something here"); // TODO put tooltip } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.action.IAction#run() */ public void run() { 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 6feca3b4..54d873ac 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 @@ -23,48 +23,48 @@ */ 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(UIUtils.IMAGE_DUPLICATE)); - setToolTipText("Check duplicate values"); - } + 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"); + /* + * (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()); - } - } + 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/i18n/actions/ShowMissingAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java index 45844a01..91ce116e 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java @@ -17,10 +17,9 @@ import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; - /** * @author Pascal Essiembre - * + * */ public class ShowMissingAction extends Action { @@ -30,19 +29,18 @@ 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 + setImageDescriptor(UIUtils.getImageDescriptor("empty.gif")); + setToolTipText("TODO put something here"); // TODO put tooltip } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.action.IAction#run() */ public void run() { - MessageDialog.openInformation( - Display.getDefault().getActiveShell(), - "Missing value", - "Key missing a value"); + MessageDialog.openInformation(Display.getDefault().getActiveShell(), + "Missing value", "Key missing a value"); } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java index 57ab92ac..4766da56 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java @@ -17,17 +17,16 @@ import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; - /** * @author Pascal Essiembre - * + * */ public class ShowSimilarAction extends Action { private final String[] keys; private final String key; private final Locale locale; - + /** * */ @@ -37,30 +36,30 @@ public ShowSimilarAction(String[] keys, String key, Locale locale) { this.key = key; this.locale = locale; setText("Show similar keys."); - setImageDescriptor( - UIUtils.getImageDescriptor("similar.gif")); - setToolTipText("TODO put something here"); //TODO put tooltip + setImageDescriptor(UIUtils.getImageDescriptor("similar.gif")); + setToolTipText("TODO put something here"); // TODO put tooltip } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.action.IAction#run() */ public void run() { - StringBuffer buf = new StringBuffer("\"" + key + "\" (" + UIUtils.getDisplayName(locale) + ") has similar " + 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(" � "); buf.append(similarKey); buf.append(" (" + UIUtils.getDisplayName(locale) + ")"); buf.append("\n"); } } - MessageDialog.openInformation( - Display.getDefault().getActiveShell(), - "Similar value", - buf.toString()); + MessageDialog.openInformation(Display.getDefault().getActiveShell(), + "Similar value", buf.toString()); } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java index dd0ba5c4..472cd5dc 100755 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java @@ -68,534 +68,539 @@ /** * Multi-page editor for editing resource bundles. */ -public abstract class AbstractMessagesEditor 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$ - - protected String selectedKey; - protected List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>( - 2); - - /** MessagesBundle group. */ - protected MessagesBundleGroup messagesBundleGroup; - - /** Page with key tree and text fields for all locales. */ - protected I18NPage i18nPage; - protected final List<Locale> localesIndex = new ArrayList<Locale>(); - protected final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>(); - - protected MessagesBundleGroupOutline outline; - - protected MessagesEditorMarkers markers; - - protected AbstractKeyTreeModel keyTreeModel; - - protected IFile file; // init - - protected boolean updateSelectedKey; - - /** - * Creates a multi-page editor example. - */ - public AbstractMessagesEditor() { - 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$ - } - messagesBundleGroup.addMessagesBundleGroupListener(getMsgBundleGroupListner()); - 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$ - } - initRAP(); - } - - // 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 - 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); - addMessagesBundle(messagesBundle, locale); - } - } - - /** - * Creates a new text editor for the messages bundle and locale, which gets added to a new page - */ - - protected void addMessagesBundle(MessagesBundle messagesBundle, Locale locale) { - try { - IMessagesResource resource = messagesBundle.getResource(); - final TextEditor textEditor = (TextEditor) resource.getSource(); - int 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()); - } - } - - protected void removeMessagesBundle(MessagesBundle messagesBundle, - Locale locale) { - IMessagesResource resource = messagesBundle.getResource(); - final TextEditor textEditor = (TextEditor) resource.getSource(); - // index + 1 because of i18n page - int pageIndex = textEditorsIndex.indexOf(textEditor) + 1; - removePage(pageIndex); - - textEditorsIndex.remove(textEditor); - localesIndex.remove(locale); - - textEditor.dispose(); - - // remove entry from i18n page - i18nPage.removeI18NEntry(messagesBundle.getLocale()); - } - - - /** - * 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? - } - - protected 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; - } - - protected 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 AbstractMessagesEditor) { - AbstractMessagesEditor rbe = (AbstractMessagesEditor) 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(); - } - - disposeRAP(); - } - - /** - * @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); - } - - // Needed for RAP, otherwise super implementation of getTitleImage always returns - // same image with same device and same session context, and when this session ends - // -> NPE at org.eclipse.swt.graphics.Image.getImageData(Image.java:348) - @Override - public Image getTitleImage() { - // create new image with current display - return UIUtils.getImageDescriptor(UIUtils.IMAGE_RESOURCE_BUNDLE).createImage(); - } - - public void setTitleName(String name) { - setPartName(name); - } - - abstract public void setEnabled(boolean enabled); - abstract protected void initRAP(); - abstract protected void disposeRAP(); - abstract protected IMessagesBundleGroupListener getMsgBundleGroupListner(); +public abstract class AbstractMessagesEditor 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$ + + protected String selectedKey; + protected List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>( + 2); + + /** MessagesBundle group. */ + protected MessagesBundleGroup messagesBundleGroup; + + /** Page with key tree and text fields for all locales. */ + protected I18NPage i18nPage; + protected final List<Locale> localesIndex = new ArrayList<Locale>(); + protected final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>(); + + protected MessagesBundleGroupOutline outline; + + protected MessagesEditorMarkers markers; + + protected AbstractKeyTreeModel keyTreeModel; + + protected IFile file; // init + + protected boolean updateSelectedKey; + + /** + * Creates a multi-page editor example. + */ + public AbstractMessagesEditor() { + 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$ + } + messagesBundleGroup + .addMessagesBundleGroupListener(getMsgBundleGroupListner()); + 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$ + } + initRAP(); + } + + // 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 + 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); + addMessagesBundle(messagesBundle, locale); + } + } + + /** + * Creates a new text editor for the messages bundle and locale, which gets + * added to a new page + */ + + protected void addMessagesBundle(MessagesBundle messagesBundle, + Locale locale) { + try { + IMessagesResource resource = messagesBundle.getResource(); + final TextEditor textEditor = (TextEditor) resource.getSource(); + int 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()); + } + } + + protected void removeMessagesBundle(MessagesBundle messagesBundle, + Locale locale) { + IMessagesResource resource = messagesBundle.getResource(); + final TextEditor textEditor = (TextEditor) resource.getSource(); + // index + 1 because of i18n page + int pageIndex = textEditorsIndex.indexOf(textEditor) + 1; + removePage(pageIndex); + + textEditorsIndex.remove(textEditor); + localesIndex.remove(locale); + + textEditor.dispose(); + + // remove entry from i18n page + i18nPage.removeI18NEntry(messagesBundle.getLocale()); + } + + /** + * 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? + } + + protected 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; + } + + protected 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 AbstractMessagesEditor) { + AbstractMessagesEditor rbe = (AbstractMessagesEditor) 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(); + } + + disposeRAP(); + } + + /** + * @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); + } + + // Needed for RAP, otherwise super implementation of getTitleImage always + // returns + // same image with same device and same session context, and when this + // session ends + // -> NPE at org.eclipse.swt.graphics.Image.getImageData(Image.java:348) + @Override + public Image getTitleImage() { + // create new image with current display + return UIUtils.getImageDescriptor(UIUtils.IMAGE_RESOURCE_BUNDLE) + .createImage(); + } + + public void setTitleName(String name) { + setPartName(name); + } + + abstract public void setEnabled(boolean enabled); + + abstract protected void initRAP(); + + abstract protected void disposeRAP(); + + abstract protected IMessagesBundleGroupListener getMsgBundleGroupListner(); } - 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 index de1eeb1a..f98eb3da 100644 --- 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 @@ -15,9 +15,10 @@ /** * @author Pascal Essiembre - * + * */ -public class MessagesEditorChangeAdapter implements IMessagesEditorChangeListener { +public class MessagesEditorChangeAdapter implements + IMessagesEditorChangeListener { /** * @@ -32,6 +33,7 @@ public MessagesEditorChangeAdapter() { public void keyTreeVisibleChanged(boolean visible) { // do nothing } + /** * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#keyTreeVisibleChanged(boolean) */ @@ -40,19 +42,26 @@ public void showOnlyUnusedAndMissingChanged(int showFilterFlag) { } /** - * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#selectedKeyChanged(java.lang.String, java.lang.String) + * @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) + /* + * (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) { + public void keyTreeModelChanged(AbstractKeyTreeModel oldModel, + AbstractKeyTreeModel newModel) { // do nothing } - + /** * @see org.eclipse.babel.editor.IMessagesEditorChangeListener#editorDisposed() */ 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 index b546d8ab..adc2731c 100644 --- 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 @@ -29,153 +29,156 @@ 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. + * 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; +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(); + } + /** - * 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)); - } + * 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) { + * @see MultiPageEditorActionBarContributor + * #setActivePage(org.eclipse.ui.IEditorPart) + */ + public void setActivePage(IEditorPart part) { if (activeEditorPart == part) { - return; + 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)); - + + 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)); + // 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) - */ + + /** + * @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); - } + // 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) + * #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); + 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) + + ((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); - AbstractMessagesEditor me = part instanceof AbstractMessagesEditor - ? (AbstractMessagesEditor)part : null; + AbstractMessagesEditor me = part instanceof AbstractMessagesEditor ? (AbstractMessagesEditor) part + : null; toggleKeyTreeAction.setEditor(me); ((FilterKeysActionGroup) FILTERS).setActiveEditor(part); newLocaleAction.setEditor(me); } - + /** * Groups the filter actions together. */ @@ -183,38 +186,43 @@ 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); + 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) { + AbstractMessagesEditor me = part instanceof AbstractMessagesEditor ? (AbstractMessagesEditor) part + : null; + for (int i = 0; i < filtersAction.length; i++) { + filtersAction[i].setEditor(me); + } } - - 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) { - AbstractMessagesEditor me = part instanceof AbstractMessagesEditor - ? (AbstractMessagesEditor)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 index 4854b1bb..8f234595 100644 --- 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 @@ -30,28 +30,31 @@ import org.eclipse.babel.editor.util.UIUtils; import org.eclipse.swt.widgets.Display; - /** * @author Pascal Essiembre - * + * */ -public class MessagesEditorMarkers - extends Observable implements IValidationMarkerStrategy { +public class MessagesEditorMarkers extends Observable implements + IValidationMarkerStrategy { -// private final Collection validationEvents = new ArrayList(); + // 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,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. - */ + + /** + * 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 */ @@ -59,65 +62,70 @@ 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(); - } - }); + 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; + // 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) + * @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()); + Collection<IMessageCheck> markersForKey = markersIndex.get(event + .getKey()); if (markersForKey == null) { - markersForKey = new HashSet<IMessageCheck>(); - markersIndex.put(event.getKey(), markersForKey); + markersForKey = new HashSet<IMessageCheck>(); + markersIndex.put(event.getKey(), markersForKey); } markersForKey.add(event.getCheck()); - - String localizedKey = buildLocalizedKey(event.getLocale(), event.getKey()); + + String localizedKey = buildLocalizedKey(event.getLocale(), + event.getKey()); markersForKey = localizedMarkersMap.get(localizedKey); if (markersForKey == null) { - markersForKey = new HashSet<IMessageCheck>(); - localizedMarkersMap.put(localizedKey, markersForKey); + markersForKey = new HashSet<IMessageCheck>(); + localizedMarkersMap.put(localizedKey, markersForKey); } markersForKey.add(event.getCheck()); - - //System.out.println("CREATE EDITOR MARKER"); + + // System.out.println("CREATE EDITOR MARKER"); setChanged(); } - + public void clear() { markersIndex.clear(); localizedMarkersMap.clear(); @@ -125,103 +133,107 @@ public void clear() { notifyObservers(this); } - public boolean isMarked(String key) { - return markersIndex.containsKey(key); + public boolean isMarked(String key) { + return markersIndex.containsKey(key); } public Collection<IMessageCheck> getFailedChecks(String key) { - return markersIndex.get(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 + * @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)); + public Collection<IMessageCheck> getFailedChecks(final String key, + final Locale locale) { + return localizedMarkersMap.get(buildLocalizedKey(locale, key)); } - + private void validate() { - //TODO in a UI thread + // 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); + 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); + 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); + 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 + * @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); + 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; + 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; + 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 8b7e3564..9a1a9ba5 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 @@ -48,105 +48,110 @@ /** * 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>>(); - } - +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>>(); + } + 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); - } - } - } - } - } - + + 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( - * 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 + /** + * @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) { + URL messagesUrl = FileLocator.find(getBundle(), new Path( + "$nl$/messages.properties"), null);//$NON-NLS-1$ + if (messagesUrl != null) { resourceBundle = new PropertyResourceBundle( messagesUrl.openStream()); } @@ -154,210 +159,240 @@ public void start(BundleContext context) throws Exception { resourceBundle = null; } - //the unique file change listener + // 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); - } - } - } - } + 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); + ResourcesPlugin.getWorkspace().addResourceChangeListener( + resourceChangeListener); try { - Display.getDefault().asyncExec(new Runnable() { - - public void run() { - Display.getDefault().addFilter(SWT.KeyUp, new UndoKeyListener()); - - } - }); + Display.getDefault().asyncExec(new Runnable() { + + public void run() { + Display.getDefault().addFilter(SWT.KeyUp, + new UndoKeyListener()); + + } + }); } catch (NullPointerException e) { - // TODO [RAP] Non UI-Thread, no default display available, in RAP multiple clients and displays + // TODO [RAP] Non UI-Thread, no default display available, in RAP + // multiple clients and displays + } + } + + /** + * @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); } - } - - /** - * @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 + } + + /** + * @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; - } - } + */ + 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 + * 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}); + 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 + * 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}); + 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 + * 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}); + 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. + + /** + * 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; - } - - + */ + 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.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java index fc226c53..b577b710 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java @@ -14,7 +14,7 @@ /** * @author Pascal Essiembre - * + * */ public class Startup implements IStartup { @@ -22,10 +22,10 @@ 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???"); + // done. + // System.out.println("Starting up. " + // + "TODO: Register nature with every project and listen for new " + // + "projects???"); } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java index 6f73de8d..751f80d7 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java @@ -29,17 +29,18 @@ /** * Plugin base preference page. + * * @author Pascal Essiembre ([email protected]) */ public abstract class AbstractPrefPage extends PreferencePage implements IWorkbenchPreferencePage { - /** Number of pixels per field indentation */ + /** 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>(); - + protected final Map<Text, String> errors = new HashMap<Text, String>(); + /** * Constructor. */ @@ -52,13 +53,14 @@ public AbstractPrefPage() { * #init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { - setPreferenceStore( - MessagesEditorPlugin.getDefault().getPreferenceStore()); + 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); @@ -70,24 +72,26 @@ protected Composite createFieldComposite(Composite parent, int indent) { } protected class IntTextValidatorKeyListener extends KeyAdapter { - + private String errMsg = null; - + /** * Constructor. - * @param errMsg error message + * + * @param errMsg + * error message */ public IntTextValidatorKeyListener(String errMsg) { super(); this.errMsg = errMsg; } + /** - * @see org.eclipse.swt.events.KeyAdapter#keyPressed( - * org.eclipse.swt.events.KeyEvent) + * @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(); + String value = text.getText(); event.doit = value.matches("^\\d*$"); //$NON-NLS-1$ if (event.doit) { errors.remove(text); @@ -95,8 +99,7 @@ public void keyReleased(KeyEvent event) { setErrorMessage(null); setValid(true); } else { - setErrorMessage( - (String) errors.values().iterator().next()); + setErrorMessage((String) errors.values().iterator().next()); } } else { errors.put(text, errMsg); @@ -107,40 +110,46 @@ public void keyReleased(KeyEvent event) { } protected class DoubleTextValidatorKeyListener extends KeyAdapter { - + private String errMsg; private double minValue; private double maxValue; - + /** * Constructor. - * @param errMsg error message + * + * @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) + * + * @param errMsg + * error message + * @param minValue + * minimum value (inclusive) + * @param maxValue + * maximum value (inclusive) */ - public DoubleTextValidatorKeyListener( - String errMsg, double minValue, double maxValue) { + 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) + * @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(); + String value = text.getText(); boolean valid = value.length() > 0; if (valid) { valid = value.matches("^\\d*\\.?\\d*$"); //$NON-NLS-1$ @@ -165,7 +174,7 @@ public void keyReleased(KeyEvent event) { } } } - + protected void setWidthInChars(Control field, int widthInChars) { GridData gd = new GridData(); gd.widthHint = UIUtils.getWidthInChars(field, widthInChars); diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java index e1f76f6b..d20f0798 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java @@ -25,10 +25,11 @@ /** * Plugin formatting preference page. + * * @author Pascal Essiembre ([email protected]) */ public class FormattingPrefPage extends AbstractPrefPage { - + /* Preference fields. */ private Button showGeneratedBy; @@ -37,24 +38,24 @@ public class FormattingPrefPage extends AbstractPrefPage { 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. */ @@ -63,183 +64,179 @@ public FormattingPrefPage() { } /** - * @see org.eclipse.jface.preference.PreferencePage#createContents( - * org.eclipse.swt.widgets.Composite) + * @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$ + 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.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$ + 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$ - + 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.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$ + 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$ - + 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.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$ + 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$ + 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.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$ - + 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$ + 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.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$ + 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$ + 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.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$ - + 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$ + 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.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$ - + 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.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$ + 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$ + 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.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$ + 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$ + 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.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$ + 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$ @@ -247,31 +244,29 @@ public void widgetSelected(SelectionEvent event) { 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); - + 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$ + 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$ + 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() */ @@ -318,55 +313,60 @@ public boolean performOk() { 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)); + 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() { + /* default */void refreshEnabledStatuses() { boolean isEncodingUnicode = convertUnicodeToEncoded.getSelection(); boolean isGroupKeyEnabled = groupKeys.getSelection(); boolean isAlignEqualsEnabled = alignEqualSigns.getSelection(); @@ -377,8 +377,8 @@ protected void performDefaults() { convertUnicodeUpperCase.setEnabled(isEncodingUnicode); groupLevelDeep.setEnabled(isGroupKeyEnabled); groupLineBreaks.setEnabled(isGroupKeyEnabled); - groupAlignEqualSigns.setEnabled( - isGroupKeyEnabled && isAlignEqualsEnabled); + groupAlignEqualSigns.setEnabled(isGroupKeyEnabled + && isAlignEqualsEnabled); wrapCharLimit.setEnabled(isWrapEnabled); wrapAlignEqualSigns.setEnabled(isWrapEnabled); wrapIndentSpaces.setEnabled(isWrapEnabled && !isWrapAlignEqualsEnabled); @@ -386,5 +386,5 @@ protected void performDefaults() { newLineTypes[i].setEnabled(isNewLineStyleForced); } } - + } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java index 421a5b7e..bd9775e2 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java @@ -22,30 +22,31 @@ /** * Plugin generic preference page. + * * @author Pascal Essiembre ([email protected]) */ -public class GeneralPrefPage extends AbstractPrefPage { - +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 supportFragments; + // private Button loadOnlyFragmentResources; + private Button keyTreeHierarchical; private Button keyTreeExpanded; private Button fieldTabInserts; - -// private Button noTreeInEditor; - + + // private Button noTreeInEditor; + private Button setupRbeNatureAutomatically; - + /** * Constructor. */ @@ -55,111 +56,111 @@ public GeneralPrefPage() { /** * @see org.eclipse.jface.preference.PreferencePage - * #createContents(org.eclipse.swt.widgets.Composite) + * #createContents(org.eclipse.swt.widgets.Composite) */ protected Control createContents(Composite parent) { MsgEditorPreferences prefs = MsgEditorPreferences.getInstance(); - -// IPreferenceStore prefs = getPreferenceStore(); + + // 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$ + 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.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$ + 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)); + // 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$ + 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$ + // 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$ - + 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$ + 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$ + // 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$ - + // 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; } @@ -177,7 +178,8 @@ public boolean performOk() { convertEncodedToUnicode.getSelection()); prefs.setValue(MsgEditorPreferences.NL_SUPPORT_ENABLED, supportNL.getSelection()); - prefs.setValue(MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS, + prefs.setValue( + MsgEditorPreferences.ADD_MSG_EDITOR_BUILDER_TO_JAVA_PROJECTS, setupRbeNatureAutomatically.getSelection()); prefs.setValue(MsgEditorPreferences.KEY_TREE_HIERARCHICAL, keyTreeHierarchical.getSelection()); @@ -185,39 +187,41 @@ public boolean performOk() { keyTreeExpanded.getSelection()); prefs.setValue(MsgEditorPreferences.FIELD_TAB_INSERTS, fieldTabInserts.getSelection()); -// prefs.setValue(MsgEditorPreferences.EDITOR_TREE_HIDDEN, -// noTreeInEditor.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)); - + 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.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 99d2d62a..ff802eb4 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 @@ -40,176 +40,168 @@ /** * 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; - +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$ + 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$ + 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$ - + 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$ + 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$ + 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. + /** + * 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"; - + 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$ + 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$ + 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$ + 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$ + 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$ + 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$ + 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$ + 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$ + 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$ + 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$ - + 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$ + 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$ + 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$ - + 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$ + 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 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$ + 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$ + 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$ + 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$ + 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$ + 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$ - + 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$ + 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$ - + 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 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. */ + + /** + * 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. */ + + /** + * 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 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. */ @@ -220,33 +212,36 @@ private MsgEditorPreferences() { public static MsgEditorPreferences getInstance() { return INSTANCE; } - - + public IPropertiesSerializerConfig getSerializerConfig() { - return serializerConfig; - } + return serializerConfig; + } - public IPropertiesDeserializerConfig getDeserializerConfig() { - return deserializerConfig; - } + 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() { @@ -255,60 +250,65 @@ public boolean isKeyTreeExpanded() { /** * 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. + + // /** + // * 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_* + * @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); @@ -317,6 +317,7 @@ public void setPropertiesFilter(int 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() { @@ -325,67 +326,76 @@ public boolean getForceNewLineType() { /** * 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); + 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. + * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR. */ public int getReportMissingValuesLevel() { - return PREFS.getInt(REPORT_MISSING_VALUES_LEVEL); + 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. + * 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.) + * + * @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. + * VALIDATION_MESSAGE_WARNING or VALIDATION_MESSAGE_ERROR. */ public int getReportSimilarValuesLevel() { - return PREFS.getInt(REPORT_SIM_VALUES_LEVEL); + 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() { @@ -393,8 +403,8 @@ public boolean getReportSimilarValuesWordCompare() { } /** - * Gets whether to use the Levensthein method when reporting similar - * values. + * Gets whether to use the Levensthein method when reporting similar values. + * * @return <code>true</code> if using Levensthein method */ public boolean getReportSimilarValuesLevensthein() { @@ -403,7 +413,8 @@ public boolean getReportSimilarValuesLevensthein() { /** * Gets the minimum precision level to use for determining when to report - * similarities. + * similarities. + * * @return precision */ public double getReportSimilarValuesPrecision() { @@ -412,14 +423,16 @@ public double getReportSimilarValuesPrecision() { /** * 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() { @@ -428,304 +441,322 @@ public boolean getKeepEmptyFields() { /** * @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> + * <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 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; + 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. + * 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 AbstractMessagesEditor) { - //the editor was loaded. reload it: - AbstractMessagesEditor meToReload = (AbstractMessagesEditor)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); -// } - + + /** + * 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 AbstractMessagesEditor) { + // the editor was loaded. reload it: + AbstractMessagesEditor meToReload = (AbstractMessagesEditor) 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java index f4120356..94cc2ac3 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java @@ -17,10 +17,10 @@ /** * Initializes default preferences. + * * @author Pascal Essiembre ([email protected]) */ -public class PreferenceInitializer extends - AbstractPreferenceInitializer { +public class PreferenceInitializer extends AbstractPreferenceInitializer { /** * Constructor. @@ -34,30 +34,33 @@ public PreferenceInitializer() { * #initializeDefaultPreferences() */ public void initializeDefaultPreferences() { - Preferences prefs = MessagesEditorPlugin.getDefault().getPluginPreferences(); + Preferences prefs = MessagesEditorPlugin.getDefault() + .getPluginPreferences(); - //General + // 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.LOADING_ONLY_FRAGMENT_RESOURCES, + false); prefs.setDefault(MsgEditorPreferences.PROPERTIES_DISPLAYED_FILTER, - IMessagesEditorChangeListener.SHOW_ALL); - - //Formatting + 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.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); @@ -66,34 +69,41 @@ public void initializeDefaultPreferences() { prefs.setDefault(MsgEditorPreferences.WRAP_LINE_LENGTH, 80); prefs.setDefault(MsgEditorPreferences.WRAP_INDENT_LENGTH, 8); - prefs.setDefault(MsgEditorPreferences.NEW_LINE_STYLE, + 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); + 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); - + 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$ + + // 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$ + + // 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.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 bf144a93..e610cf31 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 @@ -22,19 +22,21 @@ * @author Alexej Strelzow */ public class PropertiesDeserializerConfig implements - IPropertiesDeserializerConfig { // Moved from MsgEditorPreferences, to make it more flexible. + IPropertiesDeserializerConfig { // Moved from MsgEditorPreferences, to + // make it more flexible. /** MsgEditorPreferences. */ - private static final Preferences PREFS = - MessagesEditorPlugin.getDefault().getPluginPreferences(); + private static final Preferences PREFS = MessagesEditorPlugin.getDefault() + .getPluginPreferences(); PropertiesDeserializerConfig() { - ConfigurationManager.getInstance().setDeserializerConfig(this); + 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() { 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 06a0db9c..ee975d7f 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 @@ -22,18 +22,19 @@ * @author Alexej Strelzow */ public class PropertiesSerializerConfig implements IPropertiesSerializerConfig { - // Moved from MsgEditorPreferences, to make it more flexible. + // Moved from MsgEditorPreferences, to make it more flexible. /** MsgEditorPreferences. */ - private static final Preferences PREFS = - MessagesEditorPlugin.getDefault().getPluginPreferences(); - + private static final Preferences PREFS = MessagesEditorPlugin.getDefault() + .getPluginPreferences(); + PropertiesSerializerConfig() { - ConfigurationManager.getInstance().setSerializerConfig(this); + ConfigurationManager.getInstance().setSerializerConfig(this); } - + /** * Gets whether to escape unicode characters when generating file. + * * @return <code>true</code> if escaping */ public boolean isUnicodeEscapeEnabled() { @@ -42,8 +43,8 @@ public boolean isUnicodeEscapeEnabled() { /** * Gets the new line type to use when overwriting system (or Eclipse) - * default new line type when generating file. Use constants to this - * effect. + * default new line type when generating file. Use constants to this effect. + * * @return new line type */ public int getNewLineStyle() { @@ -52,6 +53,7 @@ public int getNewLineStyle() { /** * Gets how many blank lines should separate groups when generating file. + * * @return how many blank lines between groups */ public int getGroupSepBlankLineCount() { @@ -60,6 +62,7 @@ public int getGroupSepBlankLineCount() { /** * Gets whether to print "Generated By..." comment when generating file. + * * @return <code>true</code> if we print it */ public boolean isShowSupportEnabled() { @@ -68,6 +71,7 @@ public boolean isShowSupportEnabled() { /** * Gets whether keys should be grouped when generating file. + * * @return <code>true</code> if keys should be grouped */ public boolean isGroupKeysEnabled() { @@ -75,8 +79,9 @@ public boolean isGroupKeysEnabled() { } /** - * Gets whether escaped unicode "alpha" characters should be uppercase - * when generating file. + * Gets whether escaped unicode "alpha" characters should be uppercase when + * generating file. + * * @return <code>true</code> if uppercase */ public boolean isUnicodeEscapeUppercase() { @@ -86,6 +91,7 @@ public boolean isUnicodeEscapeUppercase() { /** * Gets the number of character after which lines should be wrapped when * generating file. + * * @return number of characters */ public int getWrapLineLength() { @@ -94,6 +100,7 @@ public int getWrapLineLength() { /** * Gets whether lines should be wrapped if too big when generating file. + * * @return <code>true</code> if wrapped */ public boolean isWrapLinesEnabled() { @@ -103,6 +110,7 @@ public boolean isWrapLinesEnabled() { /** * Gets whether wrapped lines should be aligned with equal sign when * generating file. + * * @return <code>true</code> if aligned */ public boolean isWrapAlignEqualsEnabled() { @@ -112,6 +120,7 @@ public boolean isWrapAlignEqualsEnabled() { /** * Gets the number of spaces to use for indentation of wrapped lines when * generating file. + * * @return number of spaces */ public int getWrapIndentLength() { @@ -119,16 +128,19 @@ public int getWrapIndentLength() { } /** - * Gets whether there should be spaces around equals signs when generating + * 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); + 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() { @@ -137,6 +149,7 @@ public boolean isNewLineNice() { /** * Gets how many level deep keys should be grouped when generating file. + * * @return how many level deep */ public int getGroupLevelDepth() { @@ -145,6 +158,7 @@ public int getGroupLevelDepth() { /** * Gets key group separator. + * * @return key group separator. */ public String getGroupLevelSeparator() { @@ -153,6 +167,7 @@ public String getGroupLevelSeparator() { /** * Gets whether equals signs should be aligned when generating file. + * * @return <code>true</code> if equals signs should be aligned */ public boolean isAlignEqualsEnabled() { @@ -162,14 +177,17 @@ public boolean isAlignEqualsEnabled() { /** * 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); + 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() { diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java index a2014782..1180acad 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java @@ -26,17 +26,18 @@ /** * 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. */ @@ -45,120 +46,123 @@ public ReportingPrefPage() { } /** - * @see org.eclipse.jface.preference.PreferencePage#createContents( - * org.eclipse.swt.widgets.Composite) + * @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(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$ + 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)); + 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$ + 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)); - + prefs.getInt(MsgEditorPreferences.REPORT_DUPL_VALUES_LEVEL)); + // Report similar values? field = createFieldComposite(composite); - gridData = new GridData(); - gridData.grabExcessHorizontalSpace = true; - field.setLayoutData(gridData); + gridData = new GridData(); + gridData.grabExcessHorizontalSpace = true; + field.setLayoutData(gridData); - new Label(field, SWT.NONE).setText( - MessagesEditorPlugin.getString("prefs.perform.simVals")); //$NON-NLS-1$ + 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)); + 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$ - + 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$ - + 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$ + 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.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$ + 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); + 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() @@ -180,37 +184,39 @@ public boolean performOk() { 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))); + 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; + /* 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.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 36008896..576f862c 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 @@ -22,128 +22,133 @@ 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. */ + /** + * 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 + * + * @param locale + * the resource locale + * @param serializer + * resource serializer + * @param deserializer + * resource deserializer + * @param textEditor + * the editor */ - public EclipsePropertiesEditorResource( - Locale locale, + public EclipsePropertiesEditorResource(Locale locale, PropertiesSerializer serializer, - PropertiesDeserializer deserializer, - TextEditor textEditor) { + 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); - + // 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); -// } -// }); + // 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(); + return textEditor.getDocumentProvider() + .getDocument(textEditor.getEditorInput()).get(); } /** - * @see org.eclipse.babel.core.bundle.resource.TextResource#setText( - * java.lang.String) + * @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); - } -// } -// }); + /* + * 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); + } + // } + // }); } /** @@ -152,7 +157,7 @@ public void setText(final String content) { public Object getSource() { return textEditor; } - + public IResource getResource() { IEditorInput input = textEditor.getEditorInput(); if (input instanceof IFileEditorInput) { @@ -160,35 +165,35 @@ public IResource getResource() { } 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; + 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. + * @param resourceLocationLabel + * The label of the location of the edited resource. */ public void setResourceLocationLabel(String resourceLocationLabel) { - _resourceLocationLabel = resourceLocationLabel; + _resourceLocationLabel = resourceLocationLabel; } - + /** - * Called before this object will be discarded. - * Nothing to do: we were not listening to changes to this file ourselves. + * 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. + // nothing to do. } - } 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 ee9d1f39..e05f634a 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 @@ -22,79 +22,79 @@ /** * @author Pascal Essiembre - * + * */ public class FileMarkerStrategy implements IValidationMarkerStrategy { - /** - * @see org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy#markFailed(org.eclipse.core.resources.IResource, org.eclipse.babel.core.bundle.checks.IBundleEntryCheck) + * @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) { if (event.getCheck() instanceof MissingValueCheck) { - MessagesBundle bundle = (MessagesBundle) event.getBundleGroup().getMessagesBundle(event.getLocale()); + 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())); - + // 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()) + String duplicates = BabelUtils + .join(((DuplicateValueCheck) event.getCheck()) .getDuplicateKeys(), ", "); - MessagesBundle bundle = (MessagesBundle) event.getBundleGroup().getMessagesBundle(event.getLocale()); + 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())); + // 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, + 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); + // 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); + // 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. + * 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? - } + 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.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java index 7e05bd8b..8da937ef 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java @@ -10,10 +10,9 @@ ******************************************************************************/ package org.eclipse.babel.editor.resource.validator; - /** * @author Pascal Essiembre - * + * */ public interface IValidationMarkerStrategy { 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 ad58478f..72422115 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 @@ -17,53 +17,49 @@ import org.eclipse.babel.core.message.internal.MessagesBundleGroup; import org.eclipse.babel.editor.preferences.MsgEditorPreferences; - /** * @author Pascal Essiembre - * + * */ -public class MessagesBundleGroupValidator { - - //TODO Re-think... ?? +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]; + 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 (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(); - } + 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.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 b49e1ded..df34cb92 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 @@ -15,56 +15,60 @@ import org.eclipse.babel.core.message.checks.IMessageCheck; import org.eclipse.babel.core.message.internal.MessagesBundleGroup; - /** * @author Pascal Essiembre - * + * */ public class ValidationFailureEvent { private final MessagesBundleGroup messagesBundleGroup; private final Locale locale; private final String key; -// private final IResource resource; + // private final IResource resource; private final IMessageCheck check; + /** * @param messagesBundleGroup * @param locale * @param key * @param resource - * @param check not null + * @param check + * not null */ - /*default*/ ValidationFailureEvent( - final MessagesBundleGroup messagesBundleGroup, - final Locale locale, + /* default */ValidationFailureEvent( + final MessagesBundleGroup messagesBundleGroup, final Locale locale, final String key, -// final IResource resource, + // final IResource resource, final IMessageCheck check) { super(); this.messagesBundleGroup = messagesBundleGroup; this.locale = locale; this.key = key; -// this.resource = resource; + // 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 */ @@ -72,6 +76,4 @@ public Locale getLocale() { return locale; } - - } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java index 0a503b08..3ba1a290 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java @@ -15,9 +15,9 @@ public interface IKeyTreeContributor { - void contribute(final TreeViewer treeViewer); + void contribute(final TreeViewer treeViewer); - IKeyTreeNode getKeyTreeNode(String key); + IKeyTreeNode getKeyTreeNode(String key); - IKeyTreeNode[] getRootKeyItems(); + IKeyTreeNode[] getRootKeyItems(); } 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 index f8becca2..f52f0656 100644 --- 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 @@ -21,16 +21,16 @@ */ public abstract class AbstractRenameKeyAction extends AbstractTreeAction { - - public static final String INSTANCE_CLASS = "org.eclipse.babel.editor.tree.actions.RenameKeyAction"; - - public AbstractRenameKeyAction(AbstractMessagesEditor 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 + public static final String INSTANCE_CLASS = "org.eclipse.babel.editor.tree.actions.RenameKeyAction"; + + public AbstractRenameKeyAction(AbstractMessagesEditor 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() */ 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 6da6ecd0..ddc8b1c2 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 @@ -20,71 +20,73 @@ import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.widgets.Shell; - /** * @author Pascal Essiembre - * + * */ public abstract class AbstractTreeAction extends Action { -// private static final KeyTreeNode[] EMPTY_TREE_NODES = new KeyTreeNode[]{}; - + // private static final KeyTreeNode[] EMPTY_TREE_NODES = new + // KeyTreeNode[]{}; + protected final TreeViewer treeViewer; protected final AbstractMessagesEditor editor; - + /** * */ - public AbstractTreeAction( - AbstractMessagesEditor editor, TreeViewer treeViewer) { + public AbstractTreeAction(AbstractMessagesEditor editor, + TreeViewer treeViewer) { super(); this.treeViewer = treeViewer; this.editor = editor; } + /** * */ - public AbstractTreeAction( - AbstractMessagesEditor editor, TreeViewer treeViewer, int style) { + public AbstractTreeAction(AbstractMessagesEditor editor, + TreeViewer treeViewer, int style) { super("", style); this.treeViewer = treeViewer; this.editor = editor; } protected KeyTreeNode getNodeSelection() { - IStructuredSelection selection = - (IStructuredSelection) treeViewer.getSelection(); + 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); + // + // 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 AbstractMessagesEditor getEditor() { return editor; } - + protected Shell getShell() { return treeViewer.getTree().getShell(); } 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 92f2104e..663a72c6 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 @@ -30,10 +30,10 @@ public class AddKeyAction extends AbstractTreeAction { * */ public AddKeyAction(AbstractMessagesEditor 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 } /** @@ -41,26 +41,26 @@ public AddKeyAction(AbstractMessagesEditor editor, TreeViewer treeViewer) { */ @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 fb50222a..81eadbe8 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 @@ -17,7 +17,7 @@ /** * @author Pascal Essiembre - * + * */ public class CollapseAllAction extends AbstractTreeAction { @@ -25,12 +25,13 @@ public class CollapseAllAction extends AbstractTreeAction { * @param editor * @param treeViewer */ - public CollapseAllAction(AbstractMessagesEditor editor, TreeViewer treeViewer) { + public CollapseAllAction(AbstractMessagesEditor 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 + setImageDescriptor(UIUtils + .getImageDescriptor(UIUtils.IMAGE_COLLAPSE_ALL)); + setToolTipText("Collapse all"); // TODO put tooltip } /** 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 6d6a0601..ab62966d 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 @@ -22,7 +22,7 @@ /** * @author Pascal Essiembre - * + * */ public class DeleteKeyAction extends AbstractTreeAction { @@ -32,17 +32,17 @@ public class DeleteKeyAction extends AbstractTreeAction { public DeleteKeyAction(AbstractMessagesEditor 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); + 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) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.action.Action#run() */ public void run() { @@ -51,18 +51,18 @@ public void run() { String msgHead = null; String msgBody = null; if (getContentProvider().hasChildren(node)) { - msgHead = MessagesEditorPlugin.getString( - "dialog.delete.head.multiple"); //$NON-NLS-1$ + 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$ + 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); + MessageBox msgBox = new MessageBox(getShell(), SWT.ICON_QUESTION + | SWT.OK | SWT.CANCEL); msgBox.setMessage(msgBody); msgBox.setText(msgHead); if (msgBox.open() == SWT.OK) { @@ -70,10 +70,10 @@ public void run() { KeyTreeNode[] nodesToDelete = getBranchNodes(node); for (int i = 0; i < nodesToDelete.length; i++) { KeyTreeNode nodeToDelete = nodesToDelete[i]; - messagesBundleGroup.removeMessages(nodeToDelete.getMessageKey()); + messagesBundleGroup + .removeMessages(nodeToDelete.getMessageKey()); } } } - - + } 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 9f7add33..119e4347 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 @@ -17,7 +17,7 @@ /** * @author Pascal Essiembre - * + * */ public class ExpandAllAction extends AbstractTreeAction { @@ -28,9 +28,8 @@ public class ExpandAllAction extends AbstractTreeAction { public ExpandAllAction(AbstractMessagesEditor 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 + setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_EXPAND_ALL)); + setToolTipText("Expand All"); // TODO put tooltip } /** 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 c0229c56..22df9687 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 @@ -20,7 +20,7 @@ /** * @author Pascal Essiembre - * + * */ public class FlatModelAction extends AbstractTreeAction { @@ -31,18 +31,19 @@ public class FlatModelAction extends AbstractTreeAction { public FlatModelAction(AbstractMessagesEditor 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 + 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); + KeyTreeContentProvider contentProvider = (KeyTreeContentProvider) treeViewer + .getContentProvider(); + contentProvider.setTreeType(TreeType.Flat); } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RefactorKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RefactorKeyAction.java index 34632e64..d85c913e 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RefactorKeyAction.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RefactorKeyAction.java @@ -24,30 +24,36 @@ */ public class RefactorKeyAction extends AbstractTreeAction { - /** - * Constructor. - * @param editor The {@link MessagesEditor} - * @param treeViewer The {@link TreeViewer} - */ - public RefactorKeyAction(AbstractMessagesEditor editor, TreeViewer treeViewer) { - super(editor, treeViewer); - setText(MessagesEditorPlugin.getString("key.refactor") + " ..."); //$NON-NLS-1$ - setImageDescriptor(UIUtils.getImageDescriptor(UIUtils.IMAGE_REFACTORING)); - setToolTipText("Refactor the name of the key"); - } + /** + * Constructor. + * + * @param editor + * The {@link MessagesEditor} + * @param treeViewer + * The {@link TreeViewer} + */ + public RefactorKeyAction(AbstractMessagesEditor editor, + TreeViewer treeViewer) { + super(editor, treeViewer); + setText(MessagesEditorPlugin.getString("key.refactor") + " ..."); //$NON-NLS-1$ + setImageDescriptor(UIUtils + .getImageDescriptor(UIUtils.IMAGE_REFACTORING)); + setToolTipText("Refactor the name of the key"); + } - /** - * @see org.eclipse.jface.action.Action#run() - */ - @Override - public void run() { - KeyTreeNode node = getNodeSelection(); + /** + * @see org.eclipse.jface.action.Action#run() + */ + @Override + public void run() { + KeyTreeNode node = getNodeSelection(); - String key = node.getMessageKey(); - String bundleId = node.getMessagesBundleGroup().getResourceBundleId(); - String projectName = node.getMessagesBundleGroup().getProjectName(); + String key = node.getMessageKey(); + String bundleId = node.getMessagesBundleGroup().getResourceBundleId(); + String projectName = node.getMessagesBundleGroup().getProjectName(); - RBManager.getRefactorService().openRefactorDialog(projectName, bundleId, key, null); + RBManager.getRefactorService().openRefactorDialog(projectName, + bundleId, key, null); - } + } } 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 dd5a90fe..6bceab16 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 @@ -20,7 +20,7 @@ /** * @author Pascal Essiembre - * + * */ public class TreeModelAction extends AbstractTreeAction { @@ -31,9 +31,9 @@ public class TreeModelAction extends AbstractTreeAction { public TreeModelAction(AbstractMessagesEditor 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 + setImageDescriptor(UIUtils + .getImageDescriptor(UIUtils.IMAGE_LAYOUT_HIERARCHICAL)); + setToolTipText("Display as in a Tree"); // TODO put tooltip setChecked(true); } @@ -41,7 +41,8 @@ public TreeModelAction(AbstractMessagesEditor editor, TreeViewer treeViewer) { * @see org.eclipse.jface.action.Action#run() */ public void run() { - KeyTreeContentProvider contentProvider = (KeyTreeContentProvider)treeViewer.getContentProvider(); - contentProvider.setTreeType(TreeType.Tree); + KeyTreeContentProvider contentProvider = (KeyTreeContentProvider) treeViewer + .getContentProvider(); + contentProvider.setTreeType(TreeType.Tree); } } 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 index ff039893..afec5a35 100644 --- 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 @@ -22,19 +22,19 @@ 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 Viewer viewer; private TreeType treeType; - + /** - * @param treeType + * @param treeType * */ public KeyTreeContentProvider(TreeType treeType) { @@ -42,103 +42,102 @@ public KeyTreeContentProvider(TreeType treeType) { } /** - * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren( - * java.lang.Object) + * @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); + return keyTreeModel.getChildren(parentNode); case Flat: - return new KeyTreeNode[0]; - default: - // Should not happen - return new KeyTreeNode[0]; + return new KeyTreeNode[0]; + default: + // Should not happen + return new KeyTreeNode[0]; } } /** * @see org.eclipse.jface.viewers.ITreeContentProvider# - * getParent(java.lang.Object) + * getParent(java.lang.Object) */ public Object getParent(Object element) { KeyTreeNode node = (KeyTreeNode) element; switch (treeType) { case Tree: - return keyTreeModel.getParent(node); + return keyTreeModel.getParent(node); case Flat: - return keyTreeModel; - default: - // Should not happen - return null; + return keyTreeModel; + default: + // Should not happen + return null; } } /** * @see org.eclipse.jface.viewers.ITreeContentProvider# - * hasChildren(java.lang.Object) + * 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; + return false; + default: + // Should not happen + return false; } } /** * @see org.eclipse.jface.viewers.IStructuredContentProvider# - * getElements(java.lang.Object) + * getElements(java.lang.Object) */ public Object[] getElements(Object inputElement) { - switch (treeType) { + 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(); + 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]; + // Should not happen + return new KeyTreeNode[0]; } } /** * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ - public void dispose() {} + public void dispose() { + } /** - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged( - * org.eclipse.jface.viewers.Viewer, - * java.lang.Object, java.lang.Object) + * @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 TreeType getTreeType() { + return treeType; + } - public void setTreeType(TreeType treeType) { - if (this.treeType != treeType) { - this.treeType = treeType; - viewer.refresh(); - } - } + 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 index 6f939963..c56efae5 100644 --- 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 @@ -52,14 +52,14 @@ /** * @author Pascal Essiembre - * + * */ public class KeyTreeContributor implements IKeyTreeContributor { - private AbstractMessagesEditor editor; + private AbstractMessagesEditor editor; private AbstractKeyTreeModel treeModel; private TreeType treeType; - + /** * */ @@ -74,160 +74,162 @@ public KeyTreeContributor(final AbstractMessagesEditor editor) { * */ public void contribute(final TreeViewer treeViewer) { - - KeyTreeContentProvider contentProvider = new KeyTreeContentProvider(treeType); - treeViewer.setContentProvider(contentProvider); - ColumnViewerToolTipSupport.enableFor (treeViewer); - treeViewer.setLabelProvider(new KeyTreeLabelProvider(editor, treeModel, contentProvider)); + + 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}; + ViewerFilter[] filters = { onlyUnusedAndMissingKeysFilter }; treeViewer.setFilters(filters); -// IKeyBindingService service = editor.getSite().getKeyBindingService(); -// service.setScopes(new String[]{"org.eclilpse.babel.editor.editor.tree"}); - + // 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(); - - treeViewer.setColumnProperties(new String[]{"column1"}); - treeViewer.setCellEditors(new CellEditor[] {new TextCellEditor(treeViewer.getTree())} ); + + treeViewer.setColumnProperties(new String[] { "column1" }); + treeViewer.setCellEditors(new CellEditor[] { new TextCellEditor( + treeViewer.getTree()) }); } private class OnlyUnsuedAndMissingKey extends ViewerFilter implements - AbstractKeyTreeModel.IKeyTreeNodeLeafFilter { + AbstractKeyTreeModel.IKeyTreeNodeLeafFilter { /* * (non-Javadoc) * - * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, - * java.lang.Object, java.lang.Object) + * @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); - } + 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; - } - } - - } + * @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 + * + * @param treeViewer + * tree viewer */ private void contributeMarkers(final TreeViewer treeViewer) { editor.getMarkers().addObserver(new Observer() { public void update(Observable o, Object arg) { - Display display = treeViewer.getTree().getDisplay(); - // [RAP] only refresh tree viewer in this UIThread - if (display.equals(Display.getCurrent())) { - display.asyncExec(new Runnable(){ - public void run() { - treeViewer.refresh(); - } - }); - } + Display display = treeViewer.getTree().getDisplay(); + // [RAP] only refresh tree viewer in this UIThread + if (display.equals(Display.getCurrent())) { + display.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); -// } -// }); - } - + // 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 + * + * @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(); + IStructuredSelection selection = (IStructuredSelection) treeViewer + .getSelection(); Object element = selection.getFirstElement(); if (treeViewer.isExpandable(element)) { if (treeViewer.getExpandedState(element)) { @@ -242,57 +244,65 @@ public void mouseDoubleClick(MouseEvent event) { /** * Contributes key synchronization between editor and tree selected keys. - * @param treeViewer tree viewer + * + * @param treeViewer + * tree viewer */ private void contributeModelChanges(final TreeViewer treeViewer) { final IKeyTreeModelListener keyTreeListener = new IKeyTreeModelListener() { - //TODO be smarter about refreshes. + // TODO be smarter about refreshes. public void nodeAdded(KeyTreeNode node) { - Display.getDefault().asyncExec(new Runnable(){ - public void run() { - treeViewer.refresh(true); - } - }); + Display.getDefault().asyncExec(new Runnable() { + public void run() { + treeViewer.refresh(true); + } + }); }; -// public void nodeChanged(KeyTreeNode node) { -// 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); - } - }); + 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) { + 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(); + + public void showOnlyUnusedAndMissingChanged(int hideEverythingElse) { + treeViewer.refresh(); } }); } /** * Contributes key synchronization between editor and tree selected keys. - * @param treeViewer tree viewer + * + * @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(); + 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()); + KeyTreeNode node = (KeyTreeNode) selection + .getFirstElement(); + System.out.println("viewer key/hash:" + + node.getMessageKey() + "/" + node.hashCode()); editor.setSelectedKey(node.getMessageKey()); } else { editor.setSelectedKey(null); @@ -302,35 +312,35 @@ public void widgetSelected(SelectionEvent e) { // changes in editor selected key updates the tree editor.addChangeListener(new MessagesEditorChangeAdapter() { public void selectedKeyChanged(String oldKey, String newKey) { - ITreeContentProvider provider = - (ITreeContentProvider) treeViewer.getContentProvider(); + 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(); - } + 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 + * + * @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); @@ -342,27 +352,28 @@ private void contributeActions(final TreeViewer treeViewer) { final IAction deleteAction = new DeleteKeyAction(editor, treeViewer); menuManager.add(deleteAction); // Rename - //final IAction renameAction = new RenameKeyAction(editor, treeViewer); + // final IAction renameAction = new RenameKeyAction(editor, treeViewer); AbstractRenameKeyAction renameKeyAction = null; try { - Class<?> clazz = Class - .forName(AbstractRenameKeyAction.INSTANCE_CLASS); - Constructor<?> cons = clazz.getConstructor(AbstractMessagesEditor.class, TreeViewer.class); - renameKeyAction = (AbstractRenameKeyAction) cons - .newInstance(editor, treeViewer); + Class<?> clazz = Class + .forName(AbstractRenameKeyAction.INSTANCE_CLASS); + Constructor<?> cons = clazz.getConstructor( + AbstractMessagesEditor.class, TreeViewer.class); + renameKeyAction = (AbstractRenameKeyAction) cons.newInstance( + editor, treeViewer); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } final IAction renameAction = renameKeyAction; menuManager.add(renameAction); - + // Refactor final IAction refactorAction = new RefactorKeyAction(editor, treeViewer); menuManager.add(refactorAction); - + menuManager.update(true); tree.setMenu(menu); - + // Bind actions to tree tree.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { @@ -374,9 +385,9 @@ public void keyReleased(KeyEvent event) { } }); } - - private KeyTreeNode findKeyTreeNode( - ITreeContentProvider provider, Object[] nodes, String key) { + + 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)) { @@ -393,10 +404,10 @@ private KeyTreeNode findKeyTreeNode( public IKeyTreeNode getKeyTreeNode(String key) { return getKeyTreeNode(key, null); } - + // TODO, think about a hashmap private IKeyTreeNode getKeyTreeNode(String key, IKeyTreeNode node) { - if (node == null) { + if (node == null) { for (IKeyTreeNode ktn : treeModel.getRootNodes()) { String id = ktn.getMessageKey(); if (key.equals(id)) { @@ -421,5 +432,5 @@ private IKeyTreeNode getKeyTreeNode(String key, IKeyTreeNode node) { 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 index a51f6925..8dd3a5a6 100644 --- 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 @@ -35,146 +35,151 @@ /** * Label provider for key tree viewer. + * * @author Pascal Essiembre */ -public class KeyTreeLabelProvider - extends ColumnLabelProvider implements IFontProvider, IColorProvider { +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 AbstractMessagesEditor 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. + * 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. + * selection because such a change would cause the content provider to do a + * full refresh anyway. */ private KeyTreeContentProvider contentProvider; - /** + /** * */ - public KeyTreeLabelProvider( - AbstractMessagesEditor editor, + public KeyTreeLabelProvider(AbstractMessagesEditor editor, AbstractKeyTreeModel treeModel, KeyTreeContentProvider contentProvider) { super(); this.editor = editor; this.messagesBundleGroup = editor.getBundleGroup(); - this.contentProvider = contentProvider; + 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#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. - */ + } + } + + /** + * @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(); + return node.getName(); case Flat: - return node.getMessageKey(); - default: - // Should not happen - return "error"; + 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; - } + } + + 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 - } + public void dispose() { + // TODO imageRegistry.dispose(); could do if version 3.1 + } /** * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object) @@ -196,9 +201,10 @@ public Color getForeground(Object element) { public Color getBackground(Object element) { return null; } - + /** - * Generates an image based on icon flags. + * Generates an image based on icon flags. + * * @param iconFlags * @return generated image */ @@ -213,7 +219,7 @@ private Image generateImage(int iconFlags) { } else { image = getRegistryImage("keyDefault.png"); //$NON-NLS-1$ } - + // Add warning icon if ((iconFlags & BADGE_WARNING) != 0) { image = overlayImage(image, "warning.gif", //$NON-NLS-1$ @@ -225,18 +231,19 @@ private Image generateImage(int 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 + + 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(); + image = new OverlayImageIcon(baseImage, + getRegistryImage(imageName), location).createImage(); imageRegistry.put(imageKey, image); } return image; @@ -253,8 +260,8 @@ private Image getRegistryImage(String imageName) { private boolean isOneChildrenMarked(IKeyTreeNode parentNode) { MessagesEditorMarkers markers = editor.getMarkers(); - IKeyTreeNode[] childNodes = - editor.getKeyTreeModel().getChildren(parentNode); + IKeyTreeNode[] childNodes = editor.getKeyTreeModel().getChildren( + parentNode); for (int i = 0; i < childNodes.length; i++) { IKeyTreeNode node = childNodes[i]; if (markers.isMarked(node.getMessageKey())) { @@ -266,6 +273,5 @@ private boolean isOneChildrenMarked(IKeyTreeNode parentNode) { } return false; } - } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java index d9bd6317..ba9b24b9 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java @@ -37,50 +37,53 @@ public class OverlayImageIcon extends CompositeImageDescriptor { /** * 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 + * + * @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, + this.imgSize = new Point(baseImage.getImageData().width, baseImage.getImageData().height); } /** * @see org.eclipse.jface.resource.CompositeImageDescriptor - * #drawCompositeImage(int, int) + * #drawCompositeImage(int, int) */ protected void drawCompositeImage(int width, int height) { // Draw the base image - drawImage(baseImage.getImageData(), 0, 0); + 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; - + 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; + } } 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 e6a4f9ab..205fb3d5 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 @@ -60,90 +60,69 @@ /** * 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$ + 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$ + 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$ + 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$ + 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$ + 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$ + 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$ + public static final String IMAGE_RENAME = "rename.gif"; //$NON-NLS-1$ /** Name of "view left" icon. */ /** Name of refactoring icon. */ - public static final String IMAGE_REFACTORING = "refactoring.png"; //$NON-NLS-1$ - public static final String IMAGE_VIEW_LEFT = "viewLeft.gif"; //$NON-NLS-1$ + public static final String IMAGE_REFACTORING = "refactoring.png"; //$NON-NLS-1$ + 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$ + 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$ + 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$ + 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.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$ - - + 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.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 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()); + // 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. + * 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. * @@ -172,78 +151,82 @@ public int compare(Locale l1, Locale l2) { }; Collections.sort(localesList, comp); for (int i = 0; i < locales.length; i++) { - locales[i] = localesList.get(i); + locales[i] = localesList.get(i); } } - + /** * @param locale - * @return true if the locale is selected by the local-filter defined in the rpeferences + * @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; + 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. + * 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. + * @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()]; + 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); + filtered[k] = result.get(k); } - return filtered; + return filtered; } /** @@ -254,28 +237,34 @@ private UIUtils() { } /** - * 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 + * 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? + // 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 + * 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? + // 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); @@ -285,24 +274,30 @@ public static Font createFont(Control control, int style, int relSize) { } /** - * 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 + * 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 + * 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(); + 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); @@ -313,31 +308,39 @@ public static Font createFont(int style, int relSize) { /** * Creates a cursor matching given style. - * @param style style to apply to the new font + * + * @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(); + Display display = MessagesEditorPlugin.getDefault().getWorkbench() + .getDisplay(); return new Cursor(display, style); } - + /** * Gets a system color. - * @param colorId SWT constant + * + * @param colorId + * SWT constant * @return system color */ public static Color getSystemColor(int colorId) { - return MessagesEditorPlugin.getDefault().getWorkbench() - .getDisplay().getSystemColor(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 + * + * @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$ @@ -348,78 +351,86 @@ public static int getWidthInChars(Control control, int numOfChars) { /** * 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 + * + * @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 + * + * @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) { + public static void showErrorDialog(Shell shell, CoreException exception, + String msgKey) { exception.printStackTrace(); - ErrorDialog.openError( - shell, - MessagesEditorPlugin.getString(msgKey), - exception.getLocalizedMessage(), - exception.getStatus()); + 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 + * + * @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) { + public static void showErrorDialog(Shell shell, Exception exception, + String msgKey) { exception.printStackTrace(); - IStatus status = new Status( - IStatus.ERROR, - MessagesEditorPlugin.PLUGIN_ID, - 0, + 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); + ErrorDialog.openError(shell, MessagesEditorPlugin.getString(msgKey), + exception.getLocalizedMessage(), status); } - + /** * Gets a locale, null-safe, display name. - * @param locale locale to get 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 MessagesEditorPlugin + .getString("editor.i18nentry.rootlocale.label"); //$NON-NLS-1$ } return locale.getDisplayName(); } /** * Gets an image descriptor. - * @param name image name + * + * @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 installURL = MessagesEditorPlugin.getDefault().getBundle() + .getEntry("/"); //$NON-NLS-1$ URL url = new URL(installURL, iconPath + name); return ImageDescriptor.createFromURL(url); } catch (MalformedURLException e) { @@ -427,165 +438,193 @@ public static ImageDescriptor getImageDescriptor(String name) { return ImageDescriptor.getMissingImageDescriptor(); } } - + /** * Gets an image. - * @param imageName image name + * + * @param imageName + * image name * @return image */ public static Image getImage(String imageName) { Image image = null; - try { - // [RAP] In RAP multiple displays could exist (multiple user), - // therefore image needs to be created every time with the current display - Method getImageRAP = Class.forName("org.eclipse.babel.editor.util.UIUtilsRAP"). - getMethod("getImage", String.class); - image = (Image) getImageRAP.invoke(null, imageName); - } catch (Exception e) { - // RAP fragment not running --> invoke rcp version - image = getImageRCP(imageName); - } - - return image; + try { + // [RAP] In RAP multiple displays could exist (multiple user), + // therefore image needs to be created every time with the current + // display + Method getImageRAP = Class.forName( + "org.eclipse.babel.editor.util.UIUtilsRAP").getMethod( + "getImage", String.class); + image = (Image) getImageRAP.invoke(null, imageName); + } catch (Exception e) { + // RAP fragment not running --> invoke rcp version + image = getImageRCP(imageName); + } + + return image; } - + /** - * Gets an image from image registry or creates a new one if it the first time. - * @param imageName image name - * @return image - */ - private static Image getImageRCP(String 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); - } - return image; - } + * Gets an image from image registry or creates a new one if it the first + * time. + * + * @param imageName + * image name + * @return image + */ + private static Image getImageRCP(String 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); + } + 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; + Image image = UIUtils.getImage(UIUtils.IMAGE_KEY); + return image; } - + /** - * @return Image for the icon which indicates a key that has missing translations + * @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; + 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; + 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 + * @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; + 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 + * @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; + 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 + * @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; + 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 + * + * @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){ + public static 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; } - + /** * 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. + * 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. + * + * @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 { - 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); - 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; + 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 { + 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); + 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.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 eafa7ff0..b6de9381 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 @@ -10,8 +10,6 @@ ******************************************************************************/ package org.eclipse.babel.editor.views; - - import org.eclipse.babel.editor.internal.AbstractMessagesEditor; import org.eclipse.babel.editor.tree.actions.CollapseAllAction; import org.eclipse.babel.editor.tree.actions.ExpandAllAction; @@ -24,200 +22,204 @@ import org.eclipse.ui.IActionBars; import org.eclipse.ui.views.contentoutline.ContentOutlinePage; - /** - * This outline provides a view for the property keys coming with - * with a ResourceBundle + * This outline provides a view for the property keys coming with with a + * ResourceBundle */ public class MessagesBundleGroupOutline extends ContentOutlinePage { private final AbstractMessagesEditor editor; - - public MessagesBundleGroupOutline(AbstractMessagesEditor editor) { - super(); + + public MessagesBundleGroupOutline(AbstractMessagesEditor editor) { + super(); this.editor = editor; - } - - - /** - * {@inheritDoc} - */ - public void createControl(Composite parent) { - super.createControl(parent); - + } + + /** + * {@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 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 ); + 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 - + + // 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 */ -// + } + // + // + // /** + // * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java index 9a30bf71..caffc0e8 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java @@ -18,6 +18,7 @@ /** * A button that when clicked, will execute the given action. + * * @author Pascal Essiembre ([email protected]) */ public class ActionButton extends Composite { diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java index 53586471..c7302c2a 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java @@ -35,6 +35,7 @@ /** * Composite for dynamically selecting a locale from a list of available * locales. + * * @author Pascal Essiembre ([email protected]) */ public class LocaleSelector extends Composite { @@ -42,7 +43,7 @@ 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; @@ -50,10 +51,11 @@ public class LocaleSelector extends Composite { private Text countryText; private Text variantText; - /** * Constructor. - * @param parent parent composite + * + * @param parent + * parent composite */ public LocaleSelector(Composite parent) { super(parent, SWT.NONE); @@ -62,25 +64,24 @@ public LocaleSelector(Composite parent) { availableLocales = Locale.getAvailableLocales(); Arrays.sort(availableLocales, new Comparator<Locale>() { public int compare(Locale locale1, Locale locale2) { - return Collator.getInstance().compare( - locale1.getDisplayName(), + 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$ - + selectionGroup + .setText(MessagesEditorPlugin.getString("selector.title")); //$NON-NLS-1$ + // Set locales drop-down GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 3; @@ -97,7 +98,7 @@ public void widgetSelected(SelectionEvent e) { langText.setText(""); //$NON-NLS-1$ countryText.setText(""); //$NON-NLS-1$ } else { - Locale locale = availableLocales[index -1]; + Locale locale = availableLocales[index - 1]; langText.setText(locale.getLanguage()); countryText.setText(locale.getCountry()); } @@ -126,8 +127,7 @@ public void focusLost(FocusEvent e) { countryText.setLayoutData(gd); countryText.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { - countryText.setText( - countryText.getText().toUpperCase()); + countryText.setText(countryText.getText().toUpperCase()); setLocaleOnlocalesCombo(); } }); @@ -142,7 +142,7 @@ public void focusLost(FocusEvent e) { setLocaleOnlocalesCombo(); } }); - + // Labels gd = new GridData(); gd.horizontalAlignment = GridData.CENTER; @@ -153,28 +153,27 @@ public void focusLost(FocusEvent e) { gd = new GridData(); gd.horizontalAlignment = GridData.CENTER; Label lblCountry = new Label(selectionGroup, SWT.NULL); - lblCountry.setText(MessagesEditorPlugin.getString( - "selector.country")); //$NON-NLS-1$ + 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.setText(MessagesEditorPlugin.getString("selector.variant")); //$NON-NLS-1$ lblVariant.setLayoutData(gd); } /** - * Gets the selected locale. Default locale is represented by a + * 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) { @@ -189,10 +188,8 @@ public Locale getSelectedLocale() { /** * Sets an available locale on the available locales combo box. */ - /*default*/ void setLocaleOnlocalesCombo() { - Locale locale = new Locale( - langText.getText(), - countryText.getText(), + /* default */void setLocaleOnlocalesCombo() { + Locale locale = new Locale(langText.getText(), countryText.getText(), variantText.getText()); int index = -1; for (int i = 0; i < availableLocales.length; i++) { @@ -207,23 +204,25 @@ public Locale getSelectedLocale() { localesCombo.clearSelection(); } } - + /** * Adds a modify listener. - * @param listener modify listener + * + * @param listener + * modify listener */ public void addModifyListener(final ModifyListener listener) { - langText.addModifyListener(new ModifyListener(){ + langText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { listener.modifyText(e); } }); - countryText.addModifyListener(new ModifyListener(){ + countryText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { listener.modifyText(e); } }); - variantText.addModifyListener(new ModifyListener(){ + variantText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { listener.modifyText(e); } 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 2be5cce2..4e0678a8 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 @@ -24,13 +24,13 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; - /** - * 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>. + * 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 { @@ -40,7 +40,7 @@ public class NullableText extends Composite { private final Color nullColor; private boolean isnull; - + private KeyListener keyListener = new KeyAdapter() { public void keyPressed(KeyEvent e) { if (SWT.BS == e.character) { @@ -49,13 +49,14 @@ public void keyPressed(KeyEvent e) { } } } + public void keyReleased(KeyEvent e) { if (text.getText().length() > 0) { renderNormal(); } } }; - + /** * Constructor. */ @@ -66,8 +67,8 @@ public NullableText(Composite parent, int style) { text.setData("REDO", new Stack<String>()); defaultColor = text.getBackground(); nullColor = UIUtils.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW); - - GridLayout gridLayout = new GridLayout(1, false); + + GridLayout gridLayout = new GridLayout(1, false); gridLayout.horizontalSpacing = 0; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; @@ -82,7 +83,7 @@ public NullableText(Composite parent, int style) { public void setOrientation(int orientation) { text.setOrientation(orientation); } - + public void setText(String text) { isnull = text == null; if (isnull) { @@ -95,13 +96,14 @@ public void setText(String text) { Stack<String> undoCache = (Stack<String>) this.text.getData("UNDO"); undoCache.push(this.text.getText()); } + public String getText() { if (isnull) { return null; } return this.text.getText(); } - + /** * @see org.eclipse.swt.widgets.Control#setEnabled(boolean) */ @@ -111,95 +113,95 @@ public void setEnabled(boolean enabled) { } private void initComponents() { - GridData gridData = new GridData( - GridData.FILL, GridData.FILL, true, true); + 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(); -// } + // try { + // text.setBackgroundImage(UIUtils.getImage("null.bmp")); + // } catch (Throwable t) { + // t.printStackTrace(); + // } } else { - text.setBackground(UIUtils.getSystemColor( - SWT.COLOR_WIDGET_BACKGROUND)); -// text.setBackgroundImage(null); + 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.setBackground(UIUtils + .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } -// text.setBackgroundImage(null); + // text.setBackgroundImage(null); } /** - * @see org.eclipse.swt.widgets.Control#addFocusListener( - * org.eclipse.swt.events.FocusListener) + * @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) + * @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) + * @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) + * @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. + * @param editable + * true if editable false otherwise. If never called it is + * editable by default. */ 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 -// -// } -// -// } - + + // 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 index 5a797dcb..8965166d 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java @@ -12,8 +12,8 @@ public interface IResourceBundleWizard { - void setBundleId(String rbName); + void setBundleId(String rbName); - void setDefaultPath(String pathName); + void setDefaultPath(String pathName); } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java index 0d5597b9..43dde1a1 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java @@ -43,9 +43,10 @@ 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. + * 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: droy $ $Revision: 1.2 $ $Date: 2012/07/18 20:13:09 $ */ @@ -54,9 +55,10 @@ 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 + * contains the path of the folder in which the resource file will be + * created */ private Text containerText; /** @@ -64,33 +66,36 @@ public class ResourceBundleNewWizardPage extends WizardPage { */ 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 + * + * @param selection + * workbench selection */ - public ResourceBundleNewWizardPage(ISelection selection, String defaultPath, String defaultRBName) { + 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; + + if (!defaultPath.isEmpty()) + this.defaultPath = defaultPath; + if (!defaultRBName.isEmpty()) + this.defaultRBName = defaultRBName; } /** @@ -104,23 +109,23 @@ public void createControl(Composite parent) { layout.verticalSpacing = 20; GridData gd = new GridData(GridData.FILL_HORIZONTAL); container.setLayoutData(gd); - - // Bundle name + location + + // Bundle name + location createTopComposite(container); - // Locales + // Locales createBottomComposite(container); - - + initialize(); dialogChanged(); setControl(container); } - /** * Creates the bottom part of this wizard, which is the locales to add. - * @param parent parent container + * + * @param parent + * parent container */ private void createBottomComposite(Composite parent) { Composite container = new Composite(parent, SWT.NULL); @@ -130,21 +135,22 @@ private void createBottomComposite(Composite parent) { 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 + * Creates the bottom part of this wizard where selected locales are stored. + * + * @param parent + * parent container */ private void createBottomSelectedLocalesComposite(Composite parent) { @@ -156,27 +162,29 @@ private void createBottomSelectedLocalesComposite(Composite parent) { 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); + 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); + removeButton.setEnabled(bundleLocalesList.getSelectionIndices().length != 0); setAddButtonState(); } }); - // add a single Locale so that the bundleLocalesList isn't empty on startup + // 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 + * + * @param parent + * parent container */ private void createBottomButtonsComposite(Composite parent) { Composite container = new Composite(parent, SWT.NULL); @@ -189,8 +197,7 @@ private void createBottomButtonsComposite(Composite parent) { 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.setText(MessagesEditorPlugin.getString("editor.wiz.add")); //$NON-NLS-1$ addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { bundleLocalesList.add(getSelectedLocaleAsString()); @@ -202,40 +209,43 @@ public void widgetSelected(SelectionEvent event) { 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.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()); + 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 + * 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(){ + 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 + * 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); @@ -245,11 +255,10 @@ private void createTopComposite(Composite parent) { 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$ + label.setText(MessagesEditorPlugin.getString("editor.wiz.folder")); //$NON-NLS-1$ containerText = new Text(container, SWT.BORDER | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); @@ -260,18 +269,16 @@ public void modifyText(ModifyEvent e) { } }); Button button = new Button(container, SWT.PUSH); - button.setText(MessagesEditorPlugin.getString( - "editor.wiz.browse")); //$NON-NLS-1$ + 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$ + label.setText(MessagesEditorPlugin.getString("editor.wiz.bundleName")); //$NON-NLS-1$ fileText = new Text(container, SWT.BORDER | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); @@ -284,121 +291,117 @@ public void modifyText(ModifyEvent e) { 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. + * 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; + 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) + 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; + container = (IContainer) obj; } else { - container = ((IResource)obj).getParent(); + container = ((IResource) obj).getParent(); } - containerText.setText(container.getFullPath(). - toPortableString()); - } + containerText.setText(container.getFullPath() + .toPortableString()); + } } - + fileText.setText(defaultRBName); } - + /** - * Uses the standard container selection dialog to - * choose the new value for the container field. + * 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$ + /* 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()); + containerText.setText(((Path) result[0]).toOSString()); } } } - + /** * Ensures that both text fields and the Locale field are set. */ - /*default*/ void dialogChanged() { + /* default */void dialogChanged() { String container = getContainerName(); String fileName = getFileName(); if (container.length() == 0) { - updateStatus(MessagesEditorPlugin.getString( - "editor.wiz.error.container")); //$NON-NLS-1$ + 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$ + 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$ + 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$ + 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$ + 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; + 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; + String errormessage = MessagesEditorPlugin + .getString("editor.wiz.error.projectnotexist"); + errormessage = String + .format(errormessage, pathContainer.segment(0)); + updateStatus(errormessage); //$NON-NLS-1$ + return; } - + updateStatus(null); } @@ -409,67 +412,73 @@ private void updateStatus(String message) { /** * 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. + * Sets the "add" button state. */ - /*default*/ void setAddButtonState() { - addButton.setEnabled(bundleLocalesList.indexOf( - getSelectedLocaleAsString()) == -1); + /* default */void setAddButtonState() { + addButton.setEnabled(bundleLocalesList + .indexOf(getSelectedLocaleAsString()) == -1); } - + /** * Gets the user selected locales. + * * @return locales */ - /*default*/ String[] getLocaleStrings() { + /* default */String[] getLocaleStrings() { return bundleLocalesList.getItems(); } - + /** * Gets a string representation of selected locale. + * * @return string representation of selected locale */ - /*default*/ String getSelectedLocaleAsString() { + /* 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); + /* 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 false; } return resource.exists(); } - + public void setDefaultRBName(String name) { - defaultRBName = name; + defaultRBName = name; } - + public void setDefaultPath(String path) { - defaultPath = 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 index b0710490..760b97cc 100644 --- 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 @@ -45,17 +45,18 @@ /** * 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 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 { +public class ResourceBundleWizard extends Wizard implements INewWizard, + IResourceBundleWizard { private ResourceBundleNewWizardPage page; private ISelection selection; - + private String defaultRbName = ""; private String defaultPath = ""; @@ -66,56 +67,59 @@ public ResourceBundleWizard() { super(); setNeedsProgressMonitor(true); } - + /** * Adding the page to the wizard. */ public void addPages() { - page = new ResourceBundleNewWizardPage(selection, defaultPath, defaultRbName); + 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. + * 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; - } - + // 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 { + public void run(IProgressMonitor monitor) + throws InvocationTargetException { try { monitor.worked(1); - monitor.setTaskName(MessagesEditorPlugin.getString( - "editor.wiz.creating")); //$NON-NLS-1$ + monitor.setTaskName(MessagesEditorPlugin + .getString("editor.wiz.creating")); //$NON-NLS-1$ IFile file = null; - for (int i = 0; i < locales.length; i++) { + for (int i = 0; i < locales.length; i++) { String fileName = baseName; - if (locales[i].equals( - ResourceBundleNewWizardPage.DEFAULT_LOCALE)) { + if (locales[i] + .equals(ResourceBundleNewWizardPage.DEFAULT_LOCALE)) { fileName += ".properties"; //$NON-NLS-1$ } else { fileName += "_" + locales[i] //$NON-NLS-1$ - + ".properties"; //$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$ + 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() { @@ -142,69 +146,79 @@ public void run() { return false; } catch (InvocationTargetException e) { Throwable realException = e.getTargetException(); - MessageDialog.openError(getShell(), + 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(); + /* default */boolean folderExists(String path) { + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(path)); if (resource == null) { - return false; + return false; } else { - return resource.exists(); + 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. + * 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$ + /* 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; - } + 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; - } + 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; + 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 { @@ -219,75 +233,81 @@ public void run() { } 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; + /* 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; + 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$ + 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. + * 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) { + public void init(IWorkbench workbench, IStructuredSelection structSelection) { this.selection = structSelection; } - public void setBundleId(String rbName) { - defaultRbName = rbName; - } + public void setBundleId(String rbName) { + defaultRbName = rbName; + } - public void setDefaultPath(String pathName) { - defaultPath = pathName; - } + 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/OpenLocalizationEditorHandler.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java index 38fcfdfe..e82c1510 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.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; @@ -22,21 +22,25 @@ public class OpenLocalizationEditorHandler extends AbstractHandler { - public OpenLocalizationEditorHandler() { - } + 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; - } + /* + * @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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java index e24f669d..837e505e 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.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.dialogs; @@ -38,160 +38,170 @@ 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); - } + 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java index 9f4adf72..5345127f 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.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.dialogs; @@ -20,54 +20,61 @@ 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"); - } + private Text textWidget; + private String text; + private boolean readOnly; - 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(); - } + 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.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 46f1a2b1..5be8dada 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 @@ -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.dialogs; @@ -52,359 +52,382 @@ 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(); - } + 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java index 835ec5fd..10dfa09b 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java @@ -1,19 +1,19 @@ /******************************************************************************* - * 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.dialogs; public class FilterOptions { - public boolean filterPlugins; - public String[] pluginPatterns; - public boolean keysWithMissingEntriesOnly; + public boolean filterPlugins; + public String[] pluginPatterns; + public boolean keysWithMissingEntriesOnly; } diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java index 3281cc40..6c6ab5d9 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.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.dialogs; @@ -23,90 +23,98 @@ 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; - } - + 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.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 b5cd32f4..5643d484 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 @@ -106,1063 +106,1063 @@ @SuppressWarnings("restriction") public class LocalizationEditor extends EditorPart { - private final class LocalizationLabelProvider extends ColumnLabelProvider { - - private final Object columnConfig; - - public LocalizationLabelProvider(Object columnConfig) { - this.columnConfig = columnConfig; - } - - @Override - 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() - */ - @Override - 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); - 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("")) { - 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); - 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); - 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); - 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]); - 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); - 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)" }); - 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\">&nbsp;</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 MyFormToolkit toolkit = new MyFormToolkit(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() { - @Override - 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("")) { - 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(@SuppressWarnings("rawtypes") 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()]); - } + private final class LocalizationLabelProvider extends ColumnLabelProvider { + + private final Object columnConfig; + + public LocalizationLabelProvider(Object columnConfig) { + this.columnConfig = columnConfig; + } + + @Override + 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() + */ + @Override + 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); + 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("")) { + 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); + 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); + 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); + 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]); + 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); + 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)" }); + 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\">&nbsp;</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 MyFormToolkit toolkit = new MyFormToolkit(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() { + @Override + 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("")) { + 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(@SuppressWarnings("rawtypes") 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java index e64c9275..69675ccc 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.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; @@ -15,65 +15,66 @@ import org.eclipse.ui.IMemento; import org.eclipse.ui.IPersistableElement; -public class LocalizationEditorInput implements IEditorInput, IPersistableElement { +public class LocalizationEditorInput implements IEditorInput, + IPersistableElement { - public LocalizationEditorInput() { - } + public LocalizationEditorInput() { + } - /* - * @see org.eclipse.ui.IEditorInput#exists() - */ - public boolean exists() { - return true; - } + /* + * @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#getImageDescriptor() + */ + public ImageDescriptor getImageDescriptor() { + return ImageDescriptor.getMissingImageDescriptor(); + } - /* - * @see org.eclipse.ui.IEditorInput#getName() - */ - public String getName() { - return "Localization Editor"; - } + /* + * @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#getPersistable() + */ + public IPersistableElement getPersistable() { + return this; + } - /* - * @see org.eclipse.ui.IEditorInput#getToolTipText() - */ - public String getToolTipText() { - return getName(); - } + /* + * @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.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) { + } - /* - * @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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java index e17907ed..2dd0d1a6 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.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; @@ -16,16 +16,17 @@ public class LocalizationEditorInputFactory implements IElementFactory { - public static final String FACTORY_ID = "org.eclipse.pde.nls.ui.LocalizationEditorInputFactory"; //$NON-NLS-1$ + public static final String FACTORY_ID = "org.eclipse.pde.nls.ui.LocalizationEditorInputFactory"; //$NON-NLS-1$ - public LocalizationEditorInputFactory() { - } + public LocalizationEditorInputFactory() { + } - /* - * @see org.eclipse.ui.IElementFactory#createElement(org.eclipse.ui.IMemento) - */ - public IAdaptable createElement(IMemento memento) { - return new LocalizationEditorInput(); - } + /* + * @see + * org.eclipse.ui.IElementFactory#createElement(org.eclipse.ui.IMemento) + */ + public IAdaptable createElement(IMemento memento) { + return new LocalizationEditorInput(); + } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java index ea0f364c..0e55482e 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java @@ -25,147 +25,153 @@ import org.eclipse.jdt.core.IJarEntryResource; /** - * A <code>ResourceBundle</code> represents a single <code>.properties</code> file. + * 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. + * 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()]); - } + 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java index 8c38b291..0309b8e7 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java @@ -1,25 +1,25 @@ /******************************************************************************* - * 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; public abstract class ResourceBundleElement { - private final ResourceBundleElement parent; + private final ResourceBundleElement parent; - public ResourceBundleElement(ResourceBundleElement parent) { - this.parent = parent; - } - - public ResourceBundleElement getParent() { - return parent; - } + public ResourceBundleElement(ResourceBundleElement parent) { + this.parent = parent; + } + + public ResourceBundleElement getParent() { + return parent; + } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java index 3f5dbbac..aa179990 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.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; @@ -20,113 +20,116 @@ /** * 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. + * 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; - } + /** + * 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java index 9e45141e..660f23e1 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.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; @@ -15,50 +15,50 @@ import org.eclipse.core.runtime.CoreException; /** - * A <code>ResourceBundleKey</code> represents a key used in one or more bundles of - * a {@link ResourceBundleFamily}. + * 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; + 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 ResourceBundleKey(ResourceBundleFamily parent, String key) { + super(parent); + this.key = key; + } - public ResourceBundleFamily getFamily() { - return getParent(); - } + /* + * @see org.eclipse.nls.ui.model.ResourceBundleElement#getParent() + */ + @Override + public ResourceBundleFamily getParent() { + return (ResourceBundleFamily) super.getParent(); + } - public String getName() { - return key; - } + public ResourceBundleFamily getFamily() { + return getParent(); + } - public String getValue(Locale locale) throws CoreException { - ResourceBundle bundle = getFamily().getBundle(locale); - if (bundle == null) - return null; - return bundle.getString(key); - } + public String getName() { + return key; + } - public boolean hasValue(Locale locale) throws CoreException { - return getValue(locale) != null; - } + public String getValue(Locale locale) throws CoreException { + ResourceBundle bundle = getFamily().getBundle(locale); + if (bundle == null) + return null; + return bundle.getString(key); + } - /* - * @see java.lang.Object#toString() - */ - public String toString() { - return "ResourceBundleKey {" + 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java index 11074f9d..df3b846c 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java @@ -1,29 +1,29 @@ /******************************************************************************* - * 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; public class ResourceBundleKeyList { - private final ResourceBundleKey[] keys; + private final ResourceBundleKey[] keys; - public ResourceBundleKeyList(ResourceBundleKey[] keys) { - this.keys = keys; - } + public ResourceBundleKeyList(ResourceBundleKey[] keys) { + this.keys = keys; + } - public ResourceBundleKey getKey(int index) { - return keys[index]; - } + public ResourceBundleKey getKey(int index) { + return keys[index]; + } - public int getSize() { - return keys.length; - } + public int getSize() { + return keys.length; + } } 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 e6addce3..c03c9774 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 @@ -54,12 +54,12 @@ public class ResourceBundleModel extends ResourceBundleElement { private HashSet<Locale> loadedLocales = new HashSet<Locale>(); public ResourceBundleModel(IProgressMonitor monitor) { - super(null); - try { - populateFromWorkspace(monitor); - } catch (CoreException e) { - MessagesEditorPlugin.log(e); - } + super(null); + try { + populateFromWorkspace(monitor); + } catch (CoreException e) { + MessagesEditorPlugin.log(e); + } } /** @@ -68,32 +68,32 @@ public ResourceBundleModel(IProgressMonitor monitor) { * @return all resource bundle families contained in this model */ public ResourceBundleFamily[] getFamilies() { - return bundleFamilies.toArray(new ResourceBundleFamily[bundleFamilies - .size()]); + 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()]); + 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()]); + 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()); + return getFamiliesForProjectName(project.getName()); } /** @@ -107,27 +107,27 @@ public ResourceBundleFamily[] getFamiliesForProject(IProject project) { * @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()]); + 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()]); } /** @@ -138,13 +138,13 @@ public ResourceBundleKey[] getAllKeys() throws CoreException { * @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); + ResourceBundleFamily[] families = getFamilies(); + for (ResourceBundleFamily family : families) { + ResourceBundle bundle = family.getBundle(locale); + if (bundle != null) + bundle.load(); + } + loadedLocales.add(locale); } /** @@ -155,16 +155,16 @@ public void loadBundles(Locale locale) throws CoreException { * 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); + 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); } /** @@ -172,401 +172,401 @@ public void unloadBundles(Locale locale) { * @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; - - 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 - } - - 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); - } - } - } - } - - // 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); - } - } - - } - } 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), - 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); - } - } + 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; + + 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 + } + + 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); + } + } + } + } + + // 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); + } + } + + } + } 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), + 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()]); + 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); - } - } - } + 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'; + 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); + 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); + 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; + 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$ + 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$ + 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; + 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$ + 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); + return str1 == null && str2 == null || str1 != null + && str1.equals(str2); } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java index b543fae6..436a3583 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.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.parser; @@ -18,245 +18,244 @@ */ public class CharArraySource implements IScannerSource { - private char[] cbuf; + private char[] cbuf; - /** The end position of this source. */ - private int end; + /** The end position of this source. */ + private int end; - private int[] lineEnds = new int[2048]; + 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 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; + /** The number of the current line. (Line numbers are one-based.) */ + int currentLineNumber = 1; - protected CharArraySource() { - } + protected CharArraySource() { + } - /** - * Constructs a scanner source from a char array. - */ - public CharArraySource(char[] cbuf) { - this.cbuf = cbuf; - this.end = cbuf.length; - } + /** + * 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]; - } - } + /** + * 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#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#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 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() + */ + 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 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 scanner.IScannerSource#unreadChar() + */ + public void unreadChar() { + currentPosition--; + } - /* - * @see core.IScannerSource#hasMoreChars() - */ - public boolean hasMoreChars() { - return currentPosition < end; - } + /* + * @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 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 core.IScannerSource#isAtLineBegin() + */ + public boolean isAtLineBegin() { + return currentPosition == lineEnds[currentLineNumber - 1]; + } - /* - * @see scanner.IScannerSource#getCurrentLineNumber() - */ - public int getCurrentLineNumber() { - return currentLineNumber; - } + /* + * @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#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#getLineEnds() + */ + public int[] getLineEnds() { + return lineEnds; + } - /* - * @see scanner.IScannerSource#length() - */ - public int length() { - return cbuf.length; - } + /* + * @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; + } - /** - * 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#length() + */ + public int length() { + return cbuf.length; + } - /* - * @see scanner.IScannerSource#toString(int, int) - */ - public String toString(int beginIndex, int endIndex) { - return new String(cbuf, beginIndex, endIndex - beginIndex); - } + /** + * 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); + } - /** - * 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 scanner.IScannerSource#toString(int, int) + */ + public String toString(int beginIndex, int endIndex) { + return new String(cbuf, beginIndex, endIndex - beginIndex); + } - /* - * @see java.lang.Object#toString() - */ - public String toString() { - return "Line=" + getCurrentLineNumber() + ", Column=" + getCurrentColumnNumber(); //$NON-NLS-1$ //$NON-NLS-2$ - } + /** + * 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; + } - private static char hexDigit(int digit) { - return "0123456789abcdef".charAt(digit); //$NON-NLS-1$ - } + /* + * @see java.lang.Object#toString() + */ + public String toString() { + return "Line=" + getCurrentLineNumber() + ", Column=" + getCurrentColumnNumber(); //$NON-NLS-1$ //$NON-NLS-2$ + } - 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); - } + 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java index 8cbf616a..b1f422c4 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java @@ -1,139 +1,149 @@ /******************************************************************************* - * 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.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); + /** + * 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java index 40ce1b35..72db6bd1 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.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.parser; @@ -15,66 +15,73 @@ */ public class LexicalErrorException extends RuntimeException { - private int lineNumber; - private int columnNumber; + 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); - } + /** + * 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 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; - } + /** + * @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 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; - } + /** + * 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$ - } + 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$ - } + private static char hexDigit(int digit) { + return "0123456789abcdef".charAt(digit); //$NON-NLS-1$ + } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java index 94d5bf2c..fd900c98 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.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.parser; @@ -15,42 +15,43 @@ 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); - } + 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java index 19ae7c03..7688666b 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java +++ b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.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.parser; @@ -24,299 +24,309 @@ */ 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(); - } - } - + 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.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java index 3866f6c6..48640d98 100644 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java +++ b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.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.nls.ui.tests; @@ -18,48 +18,44 @@ public class PropertiesTest extends TestCase { - private Properties properties; - - public void test() throws IOException { - String input = " # a comment line\r\n" - + "key1=value1\r\n" - + "key2=a value \\\r\n" - + " on two lines\r\n" - + "key3=a value \\\r\n" - + " " - + " with an empty line in between\r\n"; - properties = readProperties(input); - assertValue("value1", "key1"); - assertValue("a value on two lines", "key2"); - assertValue("a value with an empty line in between", "key3"); - } - - public void testKeysWithWhitespace() throws IOException { - String input = "" - + "key1\t=key with tab\r\n" - + "key\\ 2 =key with escaped space\r\n" - + "key 3 =key with space\r\n"; - properties = readProperties(input); - assertValue("key with tab", "key1"); - assertValue("key with escaped space", "key 2"); - assertValue("3 =key with space", "key"); - } - - public void testKeysWithMissingValue() throws IOException { - String input = "" + "keyWithoutValue\r\n" + "key=value\r\n"; - properties = readProperties(input); - assertValue("", "keyWithoutValue"); - assertValue("value", "key"); - } - - private void assertValue(String expected, String key) { - assertEquals(expected, properties.get(key)); - } - - private Properties readProperties(String input) throws IOException { - Properties properties = new Properties(); - properties.load(new ByteArrayInputStream(input.getBytes())); - return properties; - } + private Properties properties; + + public void test() throws IOException { + String input = " # a comment line\r\n" + "key1=value1\r\n" + + "key2=a value \\\r\n" + " on two lines\r\n" + + "key3=a value \\\r\n" + " " + + " with an empty line in between\r\n"; + properties = readProperties(input); + assertValue("value1", "key1"); + assertValue("a value on two lines", "key2"); + assertValue("a value with an empty line in between", "key3"); + } + + public void testKeysWithWhitespace() throws IOException { + String input = "" + "key1\t=key with tab\r\n" + + "key\\ 2 =key with escaped space\r\n" + + "key 3 =key with space\r\n"; + properties = readProperties(input); + assertValue("key with tab", "key1"); + assertValue("key with escaped space", "key 2"); + assertValue("3 =key with space", "key"); + } + + public void testKeysWithMissingValue() throws IOException { + String input = "" + "keyWithoutValue\r\n" + "key=value\r\n"; + properties = readProperties(input); + assertValue("", "keyWithoutValue"); + assertValue("value", "key"); + } + + private void assertValue(String expected, String key) { + assertEquals(expected, properties.get(key)); + } + + private Properties readProperties(String input) throws IOException { + Properties properties = new Properties(); + properties.load(new ByteArrayInputStream(input.getBytes())); + return properties; + } } diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java index 65ee097b..b6d731ba 100644 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java +++ b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.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.nls.ui.tests; @@ -21,64 +21,58 @@ public class RawBundleTest extends TestCase { - private RawBundle rawBundle; + private RawBundle rawBundle; - public void test() throws IOException { - String input = " # a comment line\r\n" - + "key1=value1\r\n" - + "key2=a value \\\r\n" - + " on two lines\r\n" - + "key3=a value \\\r\n" - + " " - + " with an empty line in between\r\n"; - rawBundle = readRawBundle(input); - assertRawData("key1=value1\r\n", "key1"); - assertRawData("key2=a value \\\r\n" + " on two lines\r\n", "key2"); - assertRawData("key3=a value \\\r\n" + " " + " with an empty line in between\r\n", "key3"); - } + public void test() throws IOException { + String input = " # a comment line\r\n" + "key1=value1\r\n" + + "key2=a value \\\r\n" + " on two lines\r\n" + + "key3=a value \\\r\n" + " " + + " with an empty line in between\r\n"; + rawBundle = readRawBundle(input); + assertRawData("key1=value1\r\n", "key1"); + assertRawData("key2=a value \\\r\n" + " on two lines\r\n", "key2"); + assertRawData("key3=a value \\\r\n" + " " + + " with an empty line in between\r\n", "key3"); + } - public void testKeysWithWhitespace() throws IOException { - String input = "" - + "key1\t=key with tab\r\n" - + "key\\ 2 =key with escaped space\r\n" - + "key 3 =key with space\r\n"; - rawBundle = readRawBundle(input); - assertRawData("key1\t=key with tab\r\n", "key1"); - assertRawData("key\\ 2 =key with escaped space\r\n", "key 2"); - assertRawData("key 3 =key with space\r\n", "key"); - } + public void testKeysWithWhitespace() throws IOException { + String input = "" + "key1\t=key with tab\r\n" + + "key\\ 2 =key with escaped space\r\n" + + "key 3 =key with space\r\n"; + rawBundle = readRawBundle(input); + assertRawData("key1\t=key with tab\r\n", "key1"); + assertRawData("key\\ 2 =key with escaped space\r\n", "key 2"); + assertRawData("key 3 =key with space\r\n", "key"); + } - public void testKeysWithMissingValue() throws IOException { - String input = "keyWithoutValue\r\n" + "key=value\r\n"; - rawBundle = readRawBundle(input); - assertRawData("keyWithoutValue\r\n", "keyWithoutValue"); - assertRawData("key=value\r\n", "key"); - } + public void testKeysWithMissingValue() throws IOException { + String input = "keyWithoutValue\r\n" + "key=value\r\n"; + rawBundle = readRawBundle(input); + assertRawData("keyWithoutValue\r\n", "keyWithoutValue"); + assertRawData("key=value\r\n", "key"); + } - public void testPut() throws IOException { - String input = "" + "key1=value1\r\n" + "key3=value3\r\n"; - rawBundle = readRawBundle(input); - rawBundle.put("key2", "value2"); - rawBundle.put("key4", "value4"); - rawBundle.put("key0", "value0\\\t"); - StringWriter stringWriter = new StringWriter(); - rawBundle.writeTo(stringWriter); - assertEquals("" - + "key0=value0\\\\\\t\r\n" - + "key1=value1\r\n" - + "key2=value2\r\n" - + "key3=value3\r\n" - + "key4=value4\r\n", stringWriter.toString()); + public void testPut() throws IOException { + String input = "" + "key1=value1\r\n" + "key3=value3\r\n"; + rawBundle = readRawBundle(input); + rawBundle.put("key2", "value2"); + rawBundle.put("key4", "value4"); + rawBundle.put("key0", "value0\\\t"); + StringWriter stringWriter = new StringWriter(); + rawBundle.writeTo(stringWriter); + assertEquals("" + "key0=value0\\\\\\t\r\n" + "key1=value1\r\n" + + "key2=value2\r\n" + "key3=value3\r\n" + "key4=value4\r\n", + stringWriter.toString()); - } - - private void assertRawData(String expected, String key) { - EntryLine entryLine = rawBundle.getEntryLine(key); - assertEquals(expected, entryLine.getRawData()); - } + } - private RawBundle readRawBundle(String input) throws IOException { - return RawBundle.createFrom(new StringReader(input)); - } + private void assertRawData(String expected, String key) { + EntryLine entryLine = rawBundle.getEntryLine(key); + assertEquals(expected, entryLine.getRawData()); + } + + private RawBundle readRawBundle(String input) throws IOException { + return RawBundle.createFrom(new StringReader(input)); + } } 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 c3fdae77..1453eab2 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 @@ -40,11 +40,11 @@ public Activator() { * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { - if (path.indexOf("icons/") < 0) { - path = "icons/" + path; - } + if (path.indexOf("icons/") < 0) { + path = "icons/" + path; + } - return imageDescriptorFromPlugin(PLUGIN_ID, path); + return imageDescriptorFromPlugin(PLUGIN_ID, path); } /* @@ -56,8 +56,8 @@ public static ImageDescriptor getImageDescriptor(String path) { */ @Override public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; + super.start(context); + plugin = this; } /* @@ -69,11 +69,11 @@ public void start(BundleContext context) throws Exception { */ @Override public void stop(BundleContext context) throws Exception { - // save state of ResourceBundleManager - ResourceBundleManager.saveManagerState(); + // save state of ResourceBundleManager + ResourceBundleManager.saveManagerState(); - plugin = null; - super.stop(context); + plugin = null; + super.stop(context); } /** @@ -82,7 +82,7 @@ public void stop(BundleContext context) throws Exception { * @return the shared instance */ public static Activator getDefault() { - return plugin; + return plugin; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java index 05abe449..0700ff51 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java @@ -90,7 +90,7 @@ public class ResourceBundleManager { public static final String NATURE_ID = "org.eclipse.babel.tapiji.tools.core.ui.nature"; public static final String BUILDER_ID = Activator.PLUGIN_ID - + ".I18NBuilder"; + + ".I18NBuilder"; /* Host project */ private IProject project = null; @@ -102,717 +102,717 @@ public class ResourceBundleManager { // 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); - } - }); + 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; + // 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); + RBManager instance = RBManager.getInstance(project); - Set<Locale> locales = new HashSet<Locale>(); - IMessagesBundleGroup group = instance - .getMessagesBundleGroup(bundleName); - if (group == null) { - return locales; - } + 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; + 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$ + 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); + return RBManager.getInstance(project).containsMessagesBundleGroup( + bundleName); } protected void unloadResource(String bundleName, IResource resource) { - // TODO implement more efficient - unloadResourceBundle(bundleName); - // loadResourceBundle(bundleName); + // TODO implement more efficient + unloadResourceBundle(bundleName); + // loadResourceBundle(bundleName); } public static String getResourceBundleId(IResource resource) { - String packageFragment = ""; + String packageFragment = ""; - IJavaElement propertyFile = JavaCore.create(resource.getParent()); - if (propertyFile != null && propertyFile instanceof IPackageFragment) { - packageFragment = ((IPackageFragment) propertyFile) - .getElementName(); - } + IJavaElement propertyFile = JavaCore.create(resource.getParent()); + if (propertyFile != null && propertyFile instanceof IPackageFragment) { + packageFragment = ((IPackageFragment) propertyFile) + .getElementName(); + } - return (packageFragment.length() > 0 ? packageFragment + "." : "") - + getResourceBundleName(resource); + return (packageFragment.length() > 0 ? packageFragment + "." : "") + + getResourceBundleName(resource); } public void addBundleResource(IResource resource) { - if (resource.isDerived()) { - return; - } + if (resource.isDerived()) { + return; + } - String bundleName = getResourceBundleId(resource); - Set<IResource> res; + String bundleName = getResourceBundleId(resource); + Set<IResource> res; - if (!resources.containsKey(bundleName)) { - res = new HashSet<IResource>(); - } else { - res = resources.get(bundleName); - } + 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)); + 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); + // 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); + unloadResourceBundle(bundleName); + resources.remove(bundleName); + // allBundles.remove(bundleName); + listeners.remove(bundleName); } public void unloadResourceBundle(String name) { - RBManager instance = RBManager.getInstance(project); - instance.deleteMessagesBundleGroup(name); + RBManager instance = RBManager.getInstance(project); + instance.deleteMessagesBundleGroup(name); } public IMessagesBundleGroup getResourceBundle(String name) { - RBManager instance = RBManager.getInstance(project); - return instance.getMessagesBundleGroup(name); + RBManager instance = RBManager.getInstance(project); + return instance.getMessagesBundleGroup(name); } public Collection<IResource> getResourceBundles(String bundleName) { - return resources.get(bundleName); + return resources.get(bundleName); } public List<String> getResourceBundleNames() { - List<String> returnList = new ArrayList<String>(); + List<String> returnList = new ArrayList<String>(); - Iterator<String> it = resources.keySet().iterator(); - while (it.hasNext()) { - returnList.add(it.next()); - } - return returnList; + 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; + 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; - } - } + for (IResource res : resources.get(bundleName)) { + if (res.getName().equalsIgnoreCase(file)) { + resource = res; + break; + } + } - return resource; + return resource; } public void fireResourceBundleChangedEvent(String bundleName, - ResourceBundleChangedEvent event) { - List<IResourceBundleChangedListener> l = listeners.get(bundleName); + ResourceBundleChangedEvent event) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); - if (l == null) { - return; - } + if (l == null) { + return; + } - for (IResourceBundleChangedListener listener : l) { - listener.resourceBundleChanged(event); - } + 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); + 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); + 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())); + 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) { - } + 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; + return project; } public List<String> getResourceBundleIdentifiers() { - List<String> returnList = new ArrayList<String>(); + 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()); - } + // 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; + return returnList; } public static List<String> getAllResourceBundleNames() { - List<String> returnList = new ArrayList<String>(); + 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; + 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; + 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 ""; - } + 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); - } + 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); + // 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())); - } - } + 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); - } + 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)); + 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); - } + 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)); + 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; + 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; + 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; + 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; + 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); + return allBundles.get(resourceBundle); } public void registerResourceExclusionListener( - IResourceExclusionListener listener) { - exclusionListeners.add(listener); + IResourceExclusionListener listener) { + exclusionListeners.add(listener); } public void unregisterResourceExclusionListener( - IResourceExclusionListener listener) { - exclusionListeners.remove(listener); + IResourceExclusionListener listener) { + exclusionListeners.remove(listener); } public boolean isResourceExclusionListenerRegistered( - IResourceExclusionListener listener) { - return exclusionListeners.contains(listener); + IResourceExclusionListener listener) { + return exclusionListeners.contains(listener); } public static void unregisterResourceExclusionListenerFromAllManagers( - IResourceExclusionListener excludedResource) { - for (ResourceBundleManager mgr : rbmanager.values()) { - mgr.unregisterResourceExclusionListener(excludedResource); - } + IResourceExclusionListener excludedResource) { + for (ResourceBundleManager mgr : rbmanager.values()) { + mgr.unregisterResourceExclusionListener(excludedResource); + } } public void addResourceBundleEntry(String resourceBundleId, String key, - Locale locale, String message) throws ResourceBundleException { + Locale locale, String message) throws ResourceBundleException { - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup bundleGroup = instance - .getMessagesBundleGroup(resourceBundleId); - IMessage entry = bundleGroup.getMessage(key, locale); + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup bundleGroup = instance + .getMessagesBundleGroup(resourceBundleId); + IMessage entry = bundleGroup.getMessage(key, locale); - if (entry == null) { - DirtyHack.setFireEnabled(false); + if (entry == null) { + DirtyHack.setFireEnabled(false); - IMessagesBundle messagesBundle = bundleGroup - .getMessagesBundle(locale); - IMessage m = MessageFactory.createMessage(key, locale); - m.setText(message); - messagesBundle.addMessage(m); + IMessagesBundle messagesBundle = bundleGroup + .getMessagesBundle(locale); + IMessage m = MessageFactory.createMessage(key, locale); + m.setText(message); + messagesBundle.addMessage(m); - FileUtils.writeToFile(messagesBundle); - instance.fireResourceChanged(messagesBundle); + FileUtils.writeToFile(messagesBundle); + instance.fireResourceChanged(messagesBundle); - DirtyHack.setFireEnabled(true); + DirtyHack.setFireEnabled(true); - // notify the PropertyKeySelectionTree - instance.fireEditorChanged(); - } + // notify the PropertyKeySelectionTree + instance.fireEditorChanged(); + } } public void saveResourceBundle(String resourceBundleId, - IMessagesBundleGroup newBundleGroup) throws ResourceBundleException { + IMessagesBundleGroup newBundleGroup) throws ResourceBundleException { - // RBManager.getInstance(). + // RBManager.getInstance(). } public void removeResourceBundleEntry(String resourceBundleId, - List<String> keys) throws ResourceBundleException { + List<String> keys) throws ResourceBundleException { - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup messagesBundleGroup = instance - .getMessagesBundleGroup(resourceBundleId); + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup messagesBundleGroup = instance + .getMessagesBundleGroup(resourceBundleId); - DirtyHack.setFireEnabled(false); + DirtyHack.setFireEnabled(false); - for (String key : keys) { - messagesBundleGroup.removeMessages(key); - } + for (String key : keys) { + messagesBundleGroup.removeMessages(key); + } - instance.writeToFile(messagesBundleGroup); + instance.writeToFile(messagesBundleGroup); - DirtyHack.setFireEnabled(true); + DirtyHack.setFireEnabled(true); - // notify the PropertyKeySelectionTree - instance.fireEditorChanged(); + // notify the PropertyKeySelectionTree + instance.fireEditorChanged(); } public boolean isResourceExisting(String bundleId, String key) { - boolean keyExists = false; - IMessagesBundleGroup bGroup = getResourceBundle(bundleId); + boolean keyExists = false; + IMessagesBundleGroup bGroup = getResourceBundle(bundleId); - if (bGroup != null) { - keyExists = bGroup.isKey(key); - } + if (bGroup != null) { + keyExists = bGroup.isKey(key); + } - return keyExists; + return keyExists; } public static void rebuildProject(IResource resource) { - try { - resource.touch(null); - } catch (CoreException e) { - Logger.logError(e); - } + 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; + 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(); + IExtensionPoint extp = Platform.getExtensionRegistry() + .getExtensionPoint( + "org.eclipse.babel.tapiji.tools.core" + ".stateLoader"); + IConfigurationElement[] elements = extp.getConfigurationElements(); - if (elements.length != 0) { - try { - return (IStateLoader) elements[0] - .createExecutableExtension("class"); - } catch (CoreException e) { - e.printStackTrace(); - } - } - return null; + if (elements.length != 0) { + try { + return (IStateLoader) elements[0] + .createExecutableExtension("class"); + } catch (CoreException e) { + e.printStackTrace(); + } + } + return null; } public static void saveManagerState() { - stateLoader.saveState(); + stateLoader.saveState(); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java index 0cd1afcd..f767964a 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java @@ -25,40 +25,40 @@ public class RBAuditor extends I18nResourceAuditor { @Override public void audit(IResource resource) { - if (RBFileUtils.isResourceBundleFile(resource)) { - ResourceBundleManager.getManager(resource.getProject()) - .addBundleResource(resource); - } + if (RBFileUtils.isResourceBundleFile(resource)) { + ResourceBundleManager.getManager(resource.getProject()) + .addBundleResource(resource); + } } @Override public String[] getFileEndings() { - return new String[] { "properties" }; + return new String[] { "properties" }; } @Override public List<ILocation> getConstantStringLiterals() { - return new ArrayList<ILocation>(); + return new ArrayList<ILocation>(); } @Override public List<ILocation> getBrokenResourceReferences() { - return new ArrayList<ILocation>(); + return new ArrayList<ILocation>(); } @Override public List<ILocation> getBrokenBundleReferences() { - return new ArrayList<ILocation>(); + return new ArrayList<ILocation>(); } @Override public String getContextId() { - return "resource_bundle"; + return "resource_bundle"; } @Override public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { - return null; + return null; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java index 66fe8b55..3ef31509 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java @@ -21,43 +21,43 @@ import org.eclipse.core.runtime.CoreException; public class ResourceBundleDetectionVisitor implements IResourceVisitor, - IResourceDeltaVisitor { + IResourceDeltaVisitor { private IProject project = null; public ResourceBundleDetectionVisitor(IProject project) { - this.project = 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; - } + 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(); + IResource resource = delta.getResource(); - if (RBFileUtils.isResourceBundleFile(resource)) { - // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); - return false; - } + if (RBFileUtils.isResourceBundleFile(resource)) { + // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); + return false; + } - return true; + return true; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java index 61fe27ba..0f73345e 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java @@ -28,29 +28,29 @@ public class ResourceFinder implements IResourceVisitor, IResourceDeltaVisitor { Set<String> supportedExtensions = null; public ResourceFinder(Set<String> ext) { - javaResources = new ArrayList<IResource>(); - supportedExtensions = 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; + 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; + return javaResources; } @Override public boolean visit(IResourceDelta delta) throws CoreException { - visit(delta.getResource()); - return true; + visit(delta.getResource()); + return true; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java index 3f3c7c19..313140e6 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java @@ -33,102 +33,102 @@ public class BuilderPropertyChangeListener implements IPropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent event) { - if (event.getNewValue().equals(true) && isTapiJIPropertyp(event)) - rebuild(); + 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; + 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); + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { + @Override + public void run() { + IMarker[] marker; + try { + marker = workspace.getRoot().findMarkers(markertype, true, + IResource.DEPTH_INFINITE); - for (IMarker m : marker) { - if (m.exists()) { - if (m.getAttribute("cause", -1) == cause) - m.delete(); - if (cause == -1) - m.getResource().deleteMarkers(markertype, true, - IResource.DEPTH_INFINITE); - } - } - } catch (CoreException e) { - } - } - }); + for (IMarker m : marker) { + if (m.exists()) { + if (m.getAttribute("cause", -1) == cause) + m.delete(); + if (cause == -1) + m.getResource().deleteMarkers(markertype, true, + IResource.DEPTH_INFINITE); + } + } + } catch (CoreException e) { + } + } + }); } private void rebuild() { - final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - new Job("Audit source files") { - @Override - protected IStatus run(IProgressMonitor monitor) { - try { - for (IResource res : workspace.getRoot().members()) { - final IProject p = (IProject) res; - try { - p.build(I18nBuilder.FULL_BUILD, - I18nBuilder.BUILDER_ID, null, monitor); - } catch (CoreException e) { - Logger.logError(e); - } - } - } catch (CoreException e) { - Logger.logError(e); - } - return Status.OK_STATUS; - } + new Job("Audit source files") { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + for (IResource res : workspace.getRoot().members()) { + final IProject p = (IProject) res; + try { + p.build(I18nBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, monitor); + } catch (CoreException e) { + Logger.logError(e); + } + } + } catch (CoreException e) { + Logger.logError(e); + } + return Status.OK_STATUS; + } - }.schedule(); + }.schedule(); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java index 0b1cc8c3..59f277be 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java @@ -38,43 +38,43 @@ public class ExtensionManager { private static Set<String> supportedFileEndings = new HashSet<String>(); public static List<I18nAuditor> getRegisteredI18nAuditors() { - if (extensions == null) { - extensions = new ArrayList<I18nAuditor>(); + if (extensions == null) { + extensions = new ArrayList<I18nAuditor>(); - // init default auditors - extensions.add(new RBAuditor()); + // init default auditors + extensions.add(new RBAuditor()); - // lookup registered auditor extensions - IConfigurationElement[] config = Platform - .getExtensionRegistry() - .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID); + // lookup registered auditor extensions + IConfigurationElement[] config = Platform + .getExtensionRegistry() + .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID); - try { - for (IConfigurationElement e : config) { - addExtensionPlugIn((I18nAuditor) e - .createExecutableExtension("class")); - } - } catch (CoreException ex) { - Logger.logError(ex); - } - } + try { + for (IConfigurationElement e : config) { + addExtensionPlugIn((I18nAuditor) e + .createExecutableExtension("class")); + } + } catch (CoreException ex) { + Logger.logError(ex); + } + } - // init builder property change listener - if (propertyChangeListener == null) { - propertyChangeListener = new BuilderPropertyChangeListener(); - TapiJIPreferences.addPropertyChangeListener(propertyChangeListener); - } + // init builder property change listener + if (propertyChangeListener == null) { + propertyChangeListener = new BuilderPropertyChangeListener(); + TapiJIPreferences.addPropertyChangeListener(propertyChangeListener); + } - return extensions; + return extensions; } public static Set<String> getSupportedFileEndings() { - return supportedFileEndings; + return supportedFileEndings; } private static void addExtensionPlugIn(I18nAuditor extension) { - I18nAuditor a = extension; - extensions.add(a); - supportedFileEndings.addAll(Arrays.asList(a.getFileEndings())); + I18nAuditor a = extension; + extensions.add(a); + supportedFileEndings.addAll(Arrays.asList(a.getFileEndings())); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java index 40bc2f38..3ba57eeb 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java @@ -47,419 +47,419 @@ public class I18nBuilder extends IncrementalProjectBuilder { public static final String BUILDER_ID = ResourceBundleManager.BUILDER_ID; public static I18nAuditor getI18nAuditorByContext(String contextId) - throws NoSuchResourceAuditorException { - for (I18nAuditor auditor : ExtensionManager.getRegisteredI18nAuditors()) { - if (auditor.getContextId().equals(contextId)) { - return auditor; - } - } - throw new NoSuchResourceAuditorException(); + 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; + 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; + 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); - } + 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); - } - } + 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); - } + 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()); + 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(); + 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); - } + 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); - } + 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); + throws InterruptedException { + monitor.worked(progress); - if (monitor.isCanceled()) { - throw new OperationCanceledException(); - } + if (monitor.isCanceled()) { + throw new OperationCanceledException(); + } - if (isInterrupted()) { - throw new InterruptedException(); - } + if (isInterrupted()) { + throw new InterruptedException(); + } } @Override protected void clean(IProgressMonitor monitor) throws CoreException { - // TODO Auto-generated method stub - super.clean(monitor); + // 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); - } + 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); - } + // 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 index 21f78413..7e9fbea6 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java @@ -33,110 +33,110 @@ public class InternationalizationNature implements IProjectNature { @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(); + 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); + I18nBuilder.removeBuilderFromProject(project); } @Override public IProject getProject() { - return project; + return project; } @Override public void setProject(IProject project) { - this.project = 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); - } + 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(); + 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; - } + 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); - } + 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 index da1fad4a..11f84bf3 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java @@ -20,32 +20,32 @@ import org.eclipse.ui.IMarkerResolutionGenerator2; public class ViolationResolutionGenerator implements - IMarkerResolutionGenerator2 { + IMarkerResolutionGenerator2 { @Override public boolean hasResolutions(IMarker marker) { - return true; + return true; } @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.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 bf119685..56974777 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 @@ -31,85 +31,85 @@ import org.eclipse.swt.graphics.Image; public class ExcludedResource implements ILabelDecorator, - IResourceExclusionListener { + IResourceExclusionListener { private static final String ENTRY_SUFFIX = "[no i18n]"; private static final Image OVERLAY_IMAGE_ON = ImageUtils - .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON); + .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON); private static final Image OVERLAY_IMAGE_OFF = ImageUtils - .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF); + .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; + 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); + label_provider_listener.add(listener); } @Override public void dispose() { - ResourceBundleManager - .unregisterResourceExclusionListenerFromAllManagers(this); + ResourceBundleManager + .unregisterResourceExclusionListenerFromAllManagers(this); } @Override public boolean isLabelProperty(Object element, String property) { - return false; + return false; } @Override public void removeListener(ILabelProviderListener listener) { - label_provider_listener.remove(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); + 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; - } + 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; + if (decorate(element)) { + return text + " " + ENTRY_SUFFIX; + } else + return text; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java index c592586f..1cf552c7 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 @@ -47,122 +47,122 @@ public class AddLanguageDialoge extends Dialog { private Text variant; public AddLanguageDialoge(Shell parentShell) { - super(parentShell); - 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); + 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); + initDescription(titelArea); + initCombo(dialogArea); + initTextArea(dialogArea); - titelArea.pack(); - dialogArea.pack(); - parent.pack(); + titelArea.pack(); + dialogArea.pack(); + parent.pack(); - return dialogArea; + 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."); + 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 - } - }); + 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); + 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()); + locale = new Locale(language.getText(), country.getText(), + variant.getText()); - super.okPressed(); + super.okPressed(); } public Locale getSelectedLanguage() { - return locale; + 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 cda61c0d..17f050a6 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 @@ -25,43 +25,43 @@ public class CreatePatternDialoge extends Dialog { 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); + 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)); + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout(1, true)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); - Label descriptionLabel = new Label(composite, SWT.NONE); - descriptionLabel.setText("Enter a regular expression:"); + Label descriptionLabel = new Label(composite, SWT.NONE); + descriptionLabel.setText("Enter a regular expression:"); - patternText = new Text(composite, SWT.WRAP | SWT.MULTI); - GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false); - gData.widthHint = 400; - gData.heightHint = 60; - patternText.setLayoutData(gData); - patternText.setText(pattern); + patternText = new Text(composite, SWT.WRAP | SWT.MULTI); + GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false); + gData.widthHint = 400; + gData.heightHint = 60; + patternText.setLayoutData(gData); + patternText.setText(pattern); - return composite; + return composite; } @Override protected void okPressed() { - pattern = patternText.getText(); + pattern = patternText.getText(); - super.okPressed(); + super.okPressed(); } public String getPattern() { - return pattern; + 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 fa66c12c..30d4f3f9 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 @@ -66,416 +66,416 @@ public class CreateResourceBundleEntryDialog extends TitleAreaDialog { public class DialogConfiguration { - String projectName; + String projectName; - String preselectedKey; - String preselectedMessage; - String preselectedBundle; - String preselectedLocale; + String preselectedKey; + String preselectedMessage; + String preselectedBundle; + String preselectedLocale; - public String getProjectName() { - return projectName; - } + public String getProjectName() { + return projectName; + } - public void setProjectName(String projectName) { - this.projectName = projectName; - } + public void setProjectName(String projectName) { + this.projectName = projectName; + } - public String getPreselectedKey() { - return preselectedKey; - } + public String getPreselectedKey() { + return preselectedKey; + } - public void setPreselectedKey(String preselectedKey) { - this.preselectedKey = preselectedKey; - } + public void setPreselectedKey(String preselectedKey) { + this.preselectedKey = preselectedKey; + } - public String getPreselectedMessage() { - return preselectedMessage; - } + public String getPreselectedMessage() { + return preselectedMessage; + } - public void setPreselectedMessage(String preselectedMessage) { - this.preselectedMessage = preselectedMessage; - } + public void setPreselectedMessage(String preselectedMessage) { + this.preselectedMessage = preselectedMessage; + } - public String getPreselectedBundle() { - return preselectedBundle; - } + public String getPreselectedBundle() { + return preselectedBundle; + } - public void setPreselectedBundle(String preselectedBundle) { - this.preselectedBundle = preselectedBundle; - } + public void setPreselectedBundle(String preselectedBundle) { + this.preselectedBundle = preselectedBundle; + } - public String getPreselectedLocale() { - return preselectedLocale; - } + public String getPreselectedLocale() { + return preselectedLocale; + } - public void setPreselectedLocale(String preselectedLocale) { - this.preselectedLocale = preselectedLocale; - } + public void setPreselectedLocale(String preselectedLocale) { + this.preselectedLocale = preselectedLocale; + } } public CreateResourceBundleEntryDialog(Shell parentShell) { - super(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(); + 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; + return selectedRB; } public String getSelectedKey() { - return selectedKey; + return selectedKey; } @Override protected Control createDialogArea(Composite parent) { - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - constructRBSection(dialogArea); - constructDefaultSection(dialogArea); - initContent(); - return dialogArea; + 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(); + 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(); - } - }); + 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); + 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)); + 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)); + 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); - } + 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"); + 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"); + // 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); + // 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(this.getErrorMessage() == null); - cancelButton.setEnabled(true); + 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(this.getErrorMessage() == null); + 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 14b637dd..c868bc06 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 @@ -29,96 +29,96 @@ public class FragmentProjectSelectionDialog extends ListDialog { 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); + List<IProject> fragmentprojects) { + super(parent); + this.hostproject = hostproject; + this.allProjects = new ArrayList<IProject>(fragmentprojects); + allProjects.add(0, hostproject); - init(); + 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.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); + this.setInput(allProjects); } public IProject getSelectedProject() { - Object[] selection = this.getResult(); - if (selection != null && selection.length > 0) - return (IProject) selection[0]; - return null; + 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 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 dispose() { + // TODO Auto-generated method stub - } + } - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub - } + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // TODO Auto-generated method stub + } } class 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 - - } + @Override + public Image getImage(Object element) { + return PlatformUI.getWorkbench().getSharedImages() + .getImage(ISharedImages.IMG_OBJ_PROJECT); + } + + @Override + public String getText(Object element) { + IProject p = ((IProject) element); + String text = p.getName(); + if (p.equals(hostproject)) + text += " [host project]"; + else + text += " [fragment project]"; + return text; + } + + @Override + public void addListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void dispose() { + // TODO Auto-generated method stub + + } + + @Override + public boolean isLabelProperty(Object element, String property) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void removeListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub + + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java index ac9fce7f..ae46d9b7 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 @@ -29,73 +29,73 @@ public class GenerateBundleAccessorDialog extends TitleAreaDialog { private Text packageName; public GenerateBundleAccessorDialog(Shell parentShell) { - super(parentShell); + super(parentShell); } @Override protected Control createDialogArea(Composite parent) { - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - constructBASection(dialogArea); - // constructDefaultSection (dialogArea); - initContent(); - return dialogArea; + 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); + 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)); + 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"); + bundleAccessor.setText("BundleAccessor"); + packageName.setText("a.b"); } /* @@ -139,8 +139,8 @@ protected void initContent() { @Override protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Create Resource-Bundle Accessor"); + 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/KeyRefactoringDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringDialog.java index 859262f1..474ce755 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringDialog.java @@ -33,323 +33,329 @@ import org.eclipse.swt.widgets.Text; /** - * The dialog between the user and the system. System wants to know - * what the new name of the selected key is. + * The dialog between the user and the system. System wants to know what the new + * name of the selected key is. * * @author Alexej Strelzow */ public class KeyRefactoringDialog extends TitleAreaDialog { - /*** Dialog Model ***/ - private DialogConfiguration config; - private String selectedKey = ""; - private String selectedLocale = ""; - - public static final String ALL_LOCALES = "All available"; - - /** GUI */ - private Button okButton; - private Button cancelButton; - - private Label projectLabel; - private Label resourceBundleLabel; - private Label oldKeyLabel; - private Label newKeyLabel; - private Label languageLabel; - - private Text oldKeyText; - private Text newKeyText; - private Text projectText; - private Text resourceBundleText; - private Combo languageCombo; - - /** - * Meta data for the dialog. - * - * @author Alexej Strelzow - */ - public class DialogConfiguration { - - String projectName; - String preselectedKey; - String preselectedBundle; - - String newKey; - String selectedLocale; - - 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 getPreselectedBundle() { - return preselectedBundle; - } - - public void setPreselectedBundle(String preselectedBundle) { - this.preselectedBundle = preselectedBundle; - } - - public String getNewKey() { - return newKey; - } - - public void setNewKey(String newKey) { - this.newKey = newKey; - } - - public String getSelectedLocale() { - return selectedLocale; - } - - public void setSelectedLocale(String selectedLocale) { - this.selectedLocale = selectedLocale; - } - } - - /** - * Constructor. - * @param parentShell The parent's shell - */ - public KeyRefactoringDialog(Shell parentShell) { - super(parentShell); - } - - /** - * {@inheritDoc} - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - initContent(); - - return super.createDialogArea(parent); - } - - private void initContent() { - ResourceBundleManager manager = ResourceBundleManager.getManager(config.getProjectName()); - // Retrieve available locales for the selected resource-bundle - Set<Locale> locales = manager.getProvidedLocales(config.getPreselectedBundle()); - - String displayName = ResourceBundleManager.defaultLocaleTag; - - // if only 1 locale available, then set this locale - if (locales.size() == 1) { - Locale l = locales.iterator().next(); - languageCombo.add(l == null ? displayName : l.getDisplayName()); - } else { - languageCombo.add(ALL_LOCALES); - for (Locale l : locales) { - displayName = l == null ? ResourceBundleManager.defaultLocaleTag - : l.getDisplayName(); - languageCombo.add(displayName); - - } - } - - languageCombo.select(0); - selectedLocale = languageCombo.getItem(0); - newKeyText.setFocus(); - - languageCombo.addModifyListener(new ModifyListener() { - - /** - * {@inheritDoc} - */ - @Override - public void modifyText(ModifyEvent e) { - selectedLocale = languageCombo.getText(); - validate(); - } - }); - - } - - /** - * Initializes the layout - * @param parent The parent - */ - private void initLayout(Composite parent) { - final GridLayout layout = new GridLayout(1, true); - parent.setLayout(layout); - - GridLayout gl = new GridLayout(2, true); - GridData gd = new GridData(SWT.CENTER, SWT.CENTER, true, true); - - Composite master = new Composite(parent, SWT.NONE); - master.setLayout(gl); - master.setLayoutData(gd); - - projectLabel = new Label(master, SWT.NONE); - projectLabel.setText("Project:"); - - projectText = new Text(master, SWT.BORDER); - projectText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - projectText.setText(config.getProjectName()); - projectText.setEnabled(false); - - resourceBundleLabel = new Label(master, SWT.NONE); - resourceBundleLabel.setText("Resource-Bundle:"); - - resourceBundleText = new Text(master, SWT.BORDER); - resourceBundleText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - resourceBundleText.setText(config.getPreselectedBundle()); - resourceBundleText.setEnabled(false); - - languageLabel = new Label(master, SWT.NONE); - languageLabel.setText("Language (Country):"); - - languageCombo = new Combo(master, SWT.BORDER); - languageCombo.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - - oldKeyLabel = new Label(master, SWT.NONE); - oldKeyLabel.setText("Old key name:"); - - oldKeyText = new Text(master, SWT.BORDER); - oldKeyText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - oldKeyText.setText(config.getPreselectedKey()); - oldKeyText.setEnabled(false); - - newKeyLabel = new Label(master, SWT.NONE); - newKeyLabel.setText("New key name:"); - - newKeyText = new Text(master, SWT.BORDER); - newKeyText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - - newKeyText.addModifyListener(new ModifyListener() { - - @Override - public void modifyText(ModifyEvent e) { - selectedKey = newKeyText.getText(); - validate(); - } - }); - } - - /** - * @param config Sets the config - */ - public void setDialogConfiguration(DialogConfiguration config) { - this.config = config; - } - - /** - * {@inheritDoc} - */ - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Key refactoring"); - } - - /** - * {@inheritDoc} - */ - @Override - public void create() { - // TODO Auto-generated method stub - super.create(); - this.setTitle("Key refactoring"); - this.setMessage("Please, specify the name of the new key. \r\n" + - "The new value will automatically replace the old ones."); - } - - /** - * @return The config - */ - public DialogConfiguration getConfig() { - return this.config; - } - - /** - * Validates all inputs of the CreateResourceBundleEntryDialog - */ - protected void validate() { - // Check Resource-Bundle ids - boolean keyValid = false; - boolean localeValid = true; - boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey); - - String resourceBundle = config.getPreselectedBundle(); - - ResourceBundleManager manager = ResourceBundleManager - .getManager(config.getProjectName()); - - - if (!ALL_LOCALES.equals(selectedLocale)) { - localeValid = LocaleUtils.containsLocaleByDisplayName( - manager.getProvidedLocales(resourceBundle), selectedLocale); - } - - if (!manager.isResourceExisting(resourceBundle, selectedKey)) { - keyValid = 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 (!localeValid) { - errorMessage = "The specified Locale does not exist for the selected Resource-Bundle."; - }else { - if (okButton != null) - okButton.setEnabled(true); - } - - setErrorMessage(errorMessage); - if (okButton != null && errorMessage != null) { - okButton.setEnabled(false); - } else { - this.config.setNewKey(selectedKey); - this.config.setSelectedLocale(selectedLocale); - } - } - - /** - * {@inheritDoc} - */ - @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); - } - + /*** Dialog Model ***/ + private DialogConfiguration config; + private String selectedKey = ""; + private String selectedLocale = ""; + + public static final String ALL_LOCALES = "All available"; + + /** GUI */ + private Button okButton; + private Button cancelButton; + + private Label projectLabel; + private Label resourceBundleLabel; + private Label oldKeyLabel; + private Label newKeyLabel; + private Label languageLabel; + + private Text oldKeyText; + private Text newKeyText; + private Text projectText; + private Text resourceBundleText; + private Combo languageCombo; + + /** + * Meta data for the dialog. + * + * @author Alexej Strelzow + */ + public class DialogConfiguration { + + String projectName; + String preselectedKey; + String preselectedBundle; + + String newKey; + String selectedLocale; + + 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 getPreselectedBundle() { + return preselectedBundle; + } + + public void setPreselectedBundle(String preselectedBundle) { + this.preselectedBundle = preselectedBundle; + } + + public String getNewKey() { + return newKey; + } + + public void setNewKey(String newKey) { + this.newKey = newKey; + } + + public String getSelectedLocale() { + return selectedLocale; + } + + public void setSelectedLocale(String selectedLocale) { + this.selectedLocale = selectedLocale; + } + } + + /** + * Constructor. + * + * @param parentShell + * The parent's shell + */ + public KeyRefactoringDialog(Shell parentShell) { + super(parentShell); + } + + /** + * {@inheritDoc} + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite dialogArea = (Composite) super.createDialogArea(parent); + initLayout(dialogArea); + initContent(); + + return super.createDialogArea(parent); + } + + private void initContent() { + ResourceBundleManager manager = ResourceBundleManager.getManager(config + .getProjectName()); + // Retrieve available locales for the selected resource-bundle + Set<Locale> locales = manager.getProvidedLocales(config + .getPreselectedBundle()); + + String displayName = ResourceBundleManager.defaultLocaleTag; + + // if only 1 locale available, then set this locale + if (locales.size() == 1) { + Locale l = locales.iterator().next(); + languageCombo.add(l == null ? displayName : l.getDisplayName()); + } else { + languageCombo.add(ALL_LOCALES); + for (Locale l : locales) { + displayName = l == null ? ResourceBundleManager.defaultLocaleTag + : l.getDisplayName(); + languageCombo.add(displayName); + + } + } + + languageCombo.select(0); + selectedLocale = languageCombo.getItem(0); + newKeyText.setFocus(); + + languageCombo.addModifyListener(new ModifyListener() { + + /** + * {@inheritDoc} + */ + @Override + public void modifyText(ModifyEvent e) { + selectedLocale = languageCombo.getText(); + validate(); + } + }); + + } + + /** + * Initializes the layout + * + * @param parent + * The parent + */ + private void initLayout(Composite parent) { + final GridLayout layout = new GridLayout(1, true); + parent.setLayout(layout); + + GridLayout gl = new GridLayout(2, true); + GridData gd = new GridData(SWT.CENTER, SWT.CENTER, true, true); + + Composite master = new Composite(parent, SWT.NONE); + master.setLayout(gl); + master.setLayoutData(gd); + + projectLabel = new Label(master, SWT.NONE); + projectLabel.setText("Project:"); + + projectText = new Text(master, SWT.BORDER); + projectText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, + true, true, 1, 1)); + projectText.setText(config.getProjectName()); + projectText.setEnabled(false); + + resourceBundleLabel = new Label(master, SWT.NONE); + resourceBundleLabel.setText("Resource-Bundle:"); + + resourceBundleText = new Text(master, SWT.BORDER); + resourceBundleText.setLayoutData(new GridData(GridData.FILL, + GridData.FILL, true, true, 1, 1)); + resourceBundleText.setText(config.getPreselectedBundle()); + resourceBundleText.setEnabled(false); + + languageLabel = new Label(master, SWT.NONE); + languageLabel.setText("Language (Country):"); + + languageCombo = new Combo(master, SWT.BORDER); + languageCombo.setLayoutData(new GridData(GridData.FILL, GridData.FILL, + true, true, 1, 1)); + + oldKeyLabel = new Label(master, SWT.NONE); + oldKeyLabel.setText("Old key name:"); + + oldKeyText = new Text(master, SWT.BORDER); + oldKeyText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, + true, true, 1, 1)); + oldKeyText.setText(config.getPreselectedKey()); + oldKeyText.setEnabled(false); + + newKeyLabel = new Label(master, SWT.NONE); + newKeyLabel.setText("New key name:"); + + newKeyText = new Text(master, SWT.BORDER); + newKeyText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, + true, true, 1, 1)); + + newKeyText.addModifyListener(new ModifyListener() { + + @Override + public void modifyText(ModifyEvent e) { + selectedKey = newKeyText.getText(); + validate(); + } + }); + } + + /** + * @param config + * Sets the config + */ + public void setDialogConfiguration(DialogConfiguration config) { + this.config = config; + } + + /** + * {@inheritDoc} + */ + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Key refactoring"); + } + + /** + * {@inheritDoc} + */ + @Override + public void create() { + // TODO Auto-generated method stub + super.create(); + this.setTitle("Key refactoring"); + this.setMessage("Please, specify the name of the new key. \r\n" + + "The new value will automatically replace the old ones."); + } + + /** + * @return The config + */ + public DialogConfiguration getConfig() { + return this.config; + } + + /** + * Validates all inputs of the CreateResourceBundleEntryDialog + */ + protected void validate() { + // Check Resource-Bundle ids + boolean keyValid = false; + boolean localeValid = true; + boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey); + + String resourceBundle = config.getPreselectedBundle(); + + ResourceBundleManager manager = ResourceBundleManager.getManager(config + .getProjectName()); + + if (!ALL_LOCALES.equals(selectedLocale)) { + localeValid = LocaleUtils.containsLocaleByDisplayName( + manager.getProvidedLocales(resourceBundle), selectedLocale); + } + + if (!manager.isResourceExisting(resourceBundle, selectedKey)) { + keyValid = 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 (!localeValid) { + errorMessage = "The specified Locale does not exist for the selected Resource-Bundle."; + } else { + if (okButton != null) + okButton.setEnabled(true); + } + + setErrorMessage(errorMessage); + if (okButton != null && errorMessage != null) { + okButton.setEnabled(false); + } else { + this.config.setNewKey(selectedKey); + this.config.setSelectedLocale(selectedLocale); + } + } + + /** + * {@inheritDoc} + */ + @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/KeyRefactoringSummaryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringSummaryDialog.java index 70d65be1..7d94563d 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringSummaryDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringSummaryDialog.java @@ -31,122 +31,129 @@ */ public class KeyRefactoringSummaryDialog extends KeyRefactoringDialog { - /** Dialog Model */ - private List<String> changeSet; - - /** GUI */ - private Button okButton; - - private Label changesLabel; - private Text changesText; - - - /** - * Constructor. - * @param parentShell The parent's shell - */ - public KeyRefactoringSummaryDialog(Shell parentShell) { - super(parentShell); - } - - /** - * {@inheritDoc} - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite dialogArea = new Composite(parent, SWT.NONE); //(Composite) super.createDialogArea(parent); - final GridLayout layout = new GridLayout(1, true); - dialogArea.setLayout(layout); - dialogArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); - initLayout(dialogArea); - - return dialogArea; - } - - /** - * Initializes the layout - * @param parent The parent - */ - private void initLayout(Composite parent) { - changesLabel = new Label(parent, SWT.NONE); - changesLabel.setText("Changes:"); - - changesText = new Text(parent, SWT.BORDER | SWT.MULTI); - changesText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); - changesText.setEditable(false); - changesText.setText(getChangeSetText()); - } - - /** - * @return The text to display (changes) - */ - private String getChangeSetText() { - - StringBuilder sb = new StringBuilder(); - - for (String s : changeSet) { - sb.append(s + "\r\n"); - } - - return sb.toString(); - } - - /** - * @param changeSet The change set of the refactoring operation, which contains - * Resource: line number - */ - public void setChangeSet(List<String> changeSet) { - this.changeSet = changeSet; - } - - /** - * {@inheritDoc} - */ - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Key refactoring summary"); - } - - /** - * {@inheritDoc} - */ - @Override - protected void okPressed() { - setReturnCode(OK); - close(); - } - - /** - * {@inheritDoc} - */ - @Override - public void create() { - super.create(); - DialogConfiguration config = getConfig(); - this.setTitle("Summary of the key refactoring: " + config.getPreselectedKey() + " -> " + - config.getNewKey()); - this.setMessage("The resource bundle " + config.getPreselectedBundle() + " and " + - changeSet.size() + " files of the project " + config.getProjectName() + - " have been successfully modified."); - } - - /** - * {@inheritDoc} - */ - @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(); - } - }); - - okButton.setEnabled(true); - } - + /** Dialog Model */ + private List<String> changeSet; + + /** GUI */ + private Button okButton; + + private Label changesLabel; + private Text changesText; + + /** + * Constructor. + * + * @param parentShell + * The parent's shell + */ + public KeyRefactoringSummaryDialog(Shell parentShell) { + super(parentShell); + } + + /** + * {@inheritDoc} + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite dialogArea = new Composite(parent, SWT.NONE); // (Composite) + // super.createDialogArea(parent); + final GridLayout layout = new GridLayout(1, true); + dialogArea.setLayout(layout); + dialogArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, + 1, 1)); + initLayout(dialogArea); + + return dialogArea; + } + + /** + * Initializes the layout + * + * @param parent + * The parent + */ + private void initLayout(Composite parent) { + changesLabel = new Label(parent, SWT.NONE); + changesLabel.setText("Changes:"); + + changesText = new Text(parent, SWT.BORDER | SWT.MULTI); + changesText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, + 1, 1)); + changesText.setEditable(false); + changesText.setText(getChangeSetText()); + } + + /** + * @return The text to display (changes) + */ + private String getChangeSetText() { + + StringBuilder sb = new StringBuilder(); + + for (String s : changeSet) { + sb.append(s + "\r\n"); + } + + return sb.toString(); + } + + /** + * @param changeSet + * The change set of the refactoring operation, which contains + * Resource: line number + */ + public void setChangeSet(List<String> changeSet) { + this.changeSet = changeSet; + } + + /** + * {@inheritDoc} + */ + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Key refactoring summary"); + } + + /** + * {@inheritDoc} + */ + @Override + protected void okPressed() { + setReturnCode(OK); + close(); + } + + /** + * {@inheritDoc} + */ + @Override + public void create() { + super.create(); + DialogConfiguration config = getConfig(); + this.setTitle("Summary of the key refactoring: " + + config.getPreselectedKey() + " -> " + config.getNewKey()); + this.setMessage("The resource bundle " + config.getPreselectedBundle() + + " and " + changeSet.size() + " files of the project " + + config.getProjectName() + " have been successfully modified."); + } + + /** + * {@inheritDoc} + */ + @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(); + } + }); + + okButton.setEnabled(true); + } + } 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 2106194a..baca62af 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 @@ -67,396 +67,396 @@ public class QueryResourceBundleEntryDialog extends TitleAreaDialog { 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; + 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; + 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(); + // 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); + 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); + 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(); - // } + 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; - } - } + 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); + 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); + 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"); + 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"); + // 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); + 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); + // 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); + 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; + return selectedRB; } public String getSelectedResource() { - return selectedKey; + return selectedKey; } public Locale getSelectedLocale() { - return selectedLocale; + 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 b9a8d818..1f260a34 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 @@ -28,96 +28,96 @@ public class RemoveLanguageDialoge extends ListDialog { private IProject project; public RemoveLanguageDialoge(IProject project, Shell shell) { - super(shell); - this.project = project; + super(shell); + this.project = project; - initDialog(); + 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.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; + 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 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 dispose() { + // TODO Auto-generated method stub - } + } - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // TODO Auto-generated method stub - } + } } class RBLabelProvider implements ILabelProvider { - @Override - public Image getImage(Object element) { - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - } - - @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 - - } + @Override + public Image getImage(Object element) { + return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); + } + + @Override + public String getText(Object element) { + Locale l = ((Locale) element); + String text = l.getDisplayName(); + if (text == null || text.equals("")) + text = "default"; + else + text += " - " + l.getLanguage() + " " + l.getCountry() + " " + + l.getVariant(); + return text; + } + + @Override + public void addListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void dispose() { + // TODO Auto-generated method stub + + } + + @Override + public boolean isLabelProperty(Object element, String property) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void removeListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub + + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java index 9d2895a8..3879c118 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 @@ -66,409 +66,409 @@ public class ResourceBundleEntrySelectionDialog extends TitleAreaDialog { private String selectedKey = ""; public ResourceBundleEntrySelectionDialog(Shell parentShell) { - super(parentShell); + super(parentShell); } @Override protected Control createDialogArea(Composite parent) { - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - constructSearchSection(dialogArea); - initContent(); - return dialogArea; + 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(); + // 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); + 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); + 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(); - // } + 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; - } - } + 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); + 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); + 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"); + 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"); + // 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); + 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); + // 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); + 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; + return selectedRB; } public String getSelectedResource() { - return selectedKey; + return selectedKey; } public Locale getSelectedLocale() { - return selectedLocale; + return selectedLocale; } public void setProjectName(String projectName) { - this.projectName = projectName; + this.projectName = projectName; } public void setBundleName(String bundleName) { - this.bundleName = bundleName; + this.bundleName = bundleName; - if (preselectedRB.isEmpty()) { - preselectedRB = this.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 de01395f..1e27d912 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 @@ -29,93 +29,93 @@ public class ResourceBundleSelectionDialog extends ListDialog { private IProject project; public ResourceBundleSelectionDialog(Shell parent, IProject project) { - super(parent); - this.project = project; + super(parent); + this.project = project; - initDialog(); + 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()); + 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; + 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 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 dispose() { + // TODO Auto-generated method stub - } + } - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // TODO Auto-generated method stub - } + } } class RBLabelProvider implements ILabelProvider { - @Override - public Image getImage(Object element) { - // TODO Auto-generated method stub - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - } + @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 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 addListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub - } + } - @Override - public void dispose() { - // TODO Auto-generated method stub + @Override + public void dispose() { + // TODO Auto-generated method stub - } + } - @Override - public boolean isLabelProperty(Object element, String property) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean isLabelProperty(Object element, String property) { + // TODO Auto-generated method stub + return false; + } - @Override - public void removeListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub + @Override + public void removeListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub - } + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java index 61b9615f..afa72c92 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java @@ -64,10 +64,10 @@ public abstract class I18nAuditor { * resource */ public boolean isResourceOfType(IResource resource) { - for (String ending : getFileEndings()) { - if (resource.getFileExtension().equalsIgnoreCase(ending)) - return true; - } - return false; + 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/I18nResourceAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java index ac69fc0f..04bb77a7 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java @@ -98,10 +98,10 @@ public abstract class I18nResourceAuditor extends I18nAuditor { * resource */ public boolean isResourceOfType(IResource resource) { - for (String ending : getFileEndings()) { - if (resource.getFileExtension().equalsIgnoreCase(ending)) - return true; - } - return false; + for (String ending : getFileEndings()) { + if (resource.getFileExtension().equalsIgnoreCase(ending)) + return true; + } + return false; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java index d79d4be9..c9b8729c 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 @@ -24,18 +24,18 @@ public PropertiesFileFilter() { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { - if (debugEnabled) - return true; + if (debugEnabled) + return true; - if (element.getClass().getSimpleName().equals("CompilationUnit")) - return false; + if (element.getClass().getSimpleName().equals("CompilationUnit")) + return false; - if (!(element instanceof IFile)) - return true; + if (!(element instanceof IFile)) + return true; - IFile file = (IFile) element; + IFile file = (IFile) element; - return file.getFileExtension().equalsIgnoreCase("properties"); + return file.getFileExtension().equalsIgnoreCase("properties"); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java index 6c6ec3fc..22a9f008 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 @@ -21,27 +21,27 @@ public class MarkerUpdater implements IMarkerUpdater { @Override public String getMarkerType() { - return "org.eclipse.core.resources.problemmarker"; + return "org.eclipse.core.resources.problemmarker"; } @Override public String[] getAttribute() { - // TODO Auto-generated method stub - return null; + // 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; - } + 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/memento/ResourceBundleManagerStateLoader.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java index 65b92112..a5353e0d 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java @@ -49,26 +49,26 @@ public class ResourceBundleManagerStateLoader implements IStateLoader { @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); - } + excludedResources = new HashSet<IResourceDescriptor>(); + FileReader reader = null; + try { + reader = new FileReader(FileUtils.getRBManagerStateFile()); + loadManagerState(XMLMemento.createReadRoot(reader)); + } catch (Exception e) { + Logger.logError(e); + } } 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); - } + 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); + } } /** @@ -76,7 +76,7 @@ private void loadManagerState(XMLMemento memento) { */ @Override public Set<IResourceDescriptor> getExcludedResources() { - return excludedResources; + return excludedResources; } /** @@ -84,37 +84,37 @@ public Set<IResourceDescriptor> getExcludedResources() { */ @Override public void saveState() { - if (excludedResources == null) { - return; - } - XMLMemento memento = XMLMemento - .createWriteRoot(TAG_INTERNATIONALIZATION); - IMemento exclChild = memento.createChild(TAG_EXCLUDED); + 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); - } - } + Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); + while (itExcl.hasNext()) { + IResourceDescriptor desc = itExcl.next(); + IMemento resDesc = exclChild.createChild(TAG_RES_DESC); + resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName()); + resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath()); + resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath()); + resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId()); + } + FileWriter writer = null; + try { + writer = new FileWriter(FileUtils.getRBManagerStateFile()); + memento.save(writer); + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + if (writer != null) { + writer.close(); + } + } catch (Exception e) { + Logger.logError(e); + } + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java index 64053b4a..34149f07 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 @@ -65,369 +65,369 @@ public InternationalizationMenu() { } public InternationalizationMenu(String id) { - super(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); - } - }); + 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; - } + 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); + 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"); - } + 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; + 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; + 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; + 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); - } + 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); - } + 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"); - } + 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; + 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) { - } + 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); + 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); - } - - }); - - } - } + 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 - */); + 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); - } - }); - } - - } - } + final IProject project = getSelectedProjects().iterator().next(); + RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project, + new Shell(Display.getCurrent())); + + if (dialog.open() == InputDialog.OK) { + final Locale locale = dialog.getSelectedLanguage(); + if (locale != null) { + if (MessageDialog.openConfirm(Display.getCurrent() + .getActiveShell(), "Confirm", + "Do you really want remove all properties-files for " + + locale.getDisplayName() + "?")) { + BusyIndicator.showWhile(Display.getCurrent(), + new Runnable() { + @Override + public void run() { + RBFileUtils.removeLanguageFromProject( + project, locale); + } + }); + } + + } + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java index d7493305..c972b124 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java @@ -26,7 +26,7 @@ import org.eclipse.ui.IWorkbenchPreferencePage; public class BuilderPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { + IWorkbenchPreferencePage { private static final int INDENT = 20; private Button checkSameValueButton; @@ -39,118 +39,118 @@ public class BuilderPreferencePage extends PreferencePage implements @Override public void init(IWorkbench workbench) { - setPreferenceStore(Activator.getDefault().getPreferenceStore()); + 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; + 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)); + 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(); + 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); + 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); + GridLayout indentLayout = new GridLayout(1, false); + indentLayout.marginWidth = marginWidth; + indentLayout.marginHeight = marginHeight; + indentLayout.verticalSpacing = 0; + composite.setLayout(indentLayout); - return composite; + return composite; } protected void setRBAudits() { - boolean selected = rbAuditButton.getSelection(); - checkMissingValueButton.setEnabled(selected); - checkSameValueButton.setEnabled(selected); - checkMissingLanguageButton.setEnabled(selected); + boolean selected = rbAuditButton.getSelection(); + checkMissingValueButton.setEnabled(selected); + checkSameValueButton.setEnabled(selected); + checkMissingLanguageButton.setEnabled(selected); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java index 541f8043..42a56c57 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java @@ -16,19 +16,19 @@ public class CheckItem { String name; public CheckItem(String item, boolean checked) { - this.name = item; - this.checked = checked; + this.name = item; + this.checked = checked; } public String getName() { - return name; + return name; } public boolean getChecked() { - return checked; + return checked; } public boolean equals(CheckItem item) { - return name.equals(item.getName()); + return name.equals(item.getName()); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java index aa382f14..4f25e422 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java @@ -36,7 +36,7 @@ import org.eclipse.ui.IWorkbenchPreferencePage; public class FilePreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { + IWorkbenchPreferencePage { private Table table; protected Object dialoge; @@ -46,182 +46,182 @@ public class FilePreferencePage extends PreferencePage implements @Override public void init(IWorkbench workbench) { - setPreferenceStore(Activator.getDefault().getPreferenceStore()); + 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; + 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(); + IPreferenceStore prefs = getPreferenceStore(); - table.removeAll(); + table.removeAll(); - List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs - .getDefaultString(TapiJIPreferences.NON_RB_PATTERN)); - for (CheckItem s : patterns) { - toTableItem(table, s); - } + 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())); - } + 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)); + prefs.setValue(TapiJIPreferences.NON_RB_PATTERN, + TapiJIPreferences.convertListToString(patterns)); - return super.performOk(); + 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; + TableItem item = new TableItem(table, SWT.NONE); + item.setText(s.getName()); + item.setChecked(s.getChecked()); + return item; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java index 107e777a..ab346aaa 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java @@ -21,24 +21,24 @@ import org.eclipse.ui.IWorkbenchPreferencePage; public class TapiHomePreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { + IWorkbenchPreferencePage { @Override public void init(IWorkbench workbench) { - // TODO Auto-generated method stub + // 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)); + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout(1, true)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - Label description = new Label(composite, SWT.WRAP); - description.setText("See sub-pages for settings."); + Label description = new Label(composite, SWT.WRAP); + description.setText("See sub-pages for settings."); - return parent; + return parent; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java index b22c86e3..520e4920 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java @@ -20,27 +20,27 @@ public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer { public TapiJIPreferenceInitializer() { - // TODO Auto-generated constructor stub + // 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); + IPreferenceStore prefs = Activator.getDefault().getPreferenceStore(); + + // ResourceBundle-Settings + List<CheckItem> patterns = new LinkedList<CheckItem>(); + patterns.add(new CheckItem("^(.)*/build\\.properties", true)); + patterns.add(new CheckItem("^(.)*/config\\.properties", true)); + patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true)); + prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN, + TapiJIPreferences.convertListToString(patterns)); + + // Builder + prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true); + prefs.setDefault(TapiJIPreferences.AUDIT_RB, true); + prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true); + prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false); + prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java index e8035f11..47b8cc58 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java @@ -30,95 +30,95 @@ public class TapiJIPreferences implements IConfiguration { public static final String NON_RB_PATTERN = "NoRBPattern"; private static final IPreferenceStore PREF = Activator.getDefault() - .getPreferenceStore(); + .getPreferenceStore(); private static final String DELIMITER = ";"; private static final String ATTRIBUTE_DELIMITER = ":"; @Override public boolean getAuditSameValue() { - return PREF.getBoolean(AUDIT_SAME_VALUE); + return PREF.getBoolean(AUDIT_SAME_VALUE); } @Override public boolean getAuditMissingValue() { - return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY); + return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY); } @Override public boolean getAuditMissingLanguage() { - return PREF.getBoolean(AUDIT_MISSING_LANGUAGE); + return PREF.getBoolean(AUDIT_MISSING_LANGUAGE); } @Override public boolean getAuditRb() { - return PREF.getBoolean(AUDIT_RB); + return PREF.getBoolean(AUDIT_RB); } @Override public boolean getAuditResource() { - return PREF.getBoolean(AUDIT_RESOURCE); + return PREF.getBoolean(AUDIT_RESOURCE); } @Override public String getNonRbPattern() { - return PREF.getString(NON_RB_PATTERN); + return PREF.getString(NON_RB_PATTERN); } public static List<CheckItem> getNonRbPatternAsList() { - return convertStringToList(PREF.getString(NON_RB_PATTERN)); + 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; + 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(); + 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); + IPropertyChangeListener listener) { + Activator.getDefault().getPreferenceStore() + .addPropertyChangeListener(listener); } public static void removePropertyChangeListener( - IPropertyChangeListener listener) { - Activator.getDefault().getPreferenceStore() - .removePropertyChangeListener(listener); + IPropertyChangeListener listener) { + Activator.getDefault().getPreferenceStore() + .removePropertyChangeListener(listener); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java index 2e8ee6ed..ebef566c 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java @@ -46,156 +46,156 @@ public class CreateResourceBundle implements IMarkerResolution2 { 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; + 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 + "'"; + return "Creates a new Resource-Bundle with the id '" + key + "'"; } @Override public Image getImage() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public String getLabel() { - return "Create Resource-Bundle '" + key + "'"; + return "Create Resource-Bundle '" + key + "'"; } @Override public void run(IMarker marker) { - runAction(); + 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); - } + // 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 index 14a3f30a..2de8a6f0 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java @@ -35,68 +35,68 @@ public class CreateResourceBundleEntry implements IMarkerResolution2 { private String bundleId; public CreateResourceBundleEntry(String key, String bundleId) { - this.key = key; - this.bundleId = bundleId; + this.key = key; + this.bundleId = bundleId; } @Override public String getDescription() { - return "Creates a new Resource-Bundle entry for the property-key '" - + key + "'"; + return "Creates a new Resource-Bundle entry for the property-key '" + + key + "'"; } @Override public Image getImage() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public String getLabel() { - return "Create Resource-Bundle entry for '" + key + "'"; + 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(); + 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(); + 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()); + 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()); + 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); + 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); - } - } + if (dialog.open() != InputDialog.OK) { + return; + } + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java index d4d389c8..e3751ca9 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java @@ -29,51 +29,51 @@ public class IncludeResource implements IMarkerResolution2 { private Set<IResource> bundleResources; public IncludeResource(String bundleName, Set<IResource> bundleResources) { - this.bundleResources = bundleResources; - this.bundleName = bundleName; + 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 public Image getImage() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public String getLabel() { - return "Include excluded Resource-Bundle '" + bundleName + "'"; + 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) { - } + 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 index 151a8546..ae220db5 100644 --- 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 @@ -25,166 +25,166 @@ 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); - } + /** 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 index 858644a4..e7b66d4b 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java @@ -27,8 +27,8 @@ public class FontUtils { * @return system color */ public static Color getSystemColor(int colorId) { - return Activator.getDefault().getWorkbench().getDisplay() - .getSystemColor(colorId); + return Activator.getDefault().getWorkbench().getDisplay() + .getSystemColor(colorId); } /** @@ -42,8 +42,8 @@ public static Color getSystemColor(int colorId) { * @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); + // TODO consider dropping in favor of control-less version? + return createFont(control, style, 0); } /** @@ -59,13 +59,13 @@ public static Font createFont(Control control, int style) { * @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); + // 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); } /** @@ -77,7 +77,7 @@ public static Font createFont(Control control, int style, int relSize) { * @return newly created font */ public static Font createFont(int style) { - return createFont(style, 0); + return createFont(style, 0); } /** @@ -91,12 +91,12 @@ public static Font createFont(int style) { * @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); + Display display = Activator.getDefault().getWorkbench().getDisplay(); + FontData[] fontData = display.getSystemFont().getFontData(); + for (int i = 0; i < fontData.length; i++) { + fontData[i].setHeight(fontData[i].getHeight() + relSize); + fontData[i].setStyle(style); + } + return new Font(display, fontData); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java index 409e3743..62e8ddfd 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java @@ -17,47 +17,47 @@ 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"; + /** 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(); + /** Image registry. */ + private static final ImageRegistry imageRegistry = new ImageRegistry(); - /** - * Constructor. - */ - private ImageUtils() { - super(); - } + /** + * 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.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java index ecadce35..c4809c98 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java @@ -34,21 +34,21 @@ 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); - } - } + 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(); - } + 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; + return file; } /** @@ -61,58 +61,58 @@ private static IFile createFile(IContainer container, String fileName, * @param locale */ public static void addLanguageToResourceBundle(IProject project, - final String rbId, final Locale locale) { - ResourceBundleManager rbManager = ResourceBundleManager - .getManager(project); + final String rbId, final Locale locale) { + ResourceBundleManager rbManager = ResourceBundleManager + .getManager(project); - if (rbManager.getProvidedLocales(rbId).contains(locale)) { - return; - } + if (rbManager.getProvidedLocales(rbId).contains(locale)) { + return; + } - final IResource file = rbManager.getRandomFile(rbId); - final IContainer c = ResourceUtils.getCorrespondingFolders( - file.getParent(), project); + final IResource file = rbManager.getRandomFile(rbId); + final IContainer c = ResourceUtils.getCorrespondingFolders( + file.getParent(), project); - new Job("create new propertfile") { - @Override - protected IStatus run(IProgressMonitor monitor) { - try { - String newFilename = ResourceBundleManager - .getResourceBundleName(file); - if (locale.getLanguage() != null - && !locale.getLanguage().equalsIgnoreCase( - ResourceBundleManager.defaultLocaleTag) - && !locale.getLanguage().equals("")) { - newFilename += "_" + locale.getLanguage(); - } - if (locale.getCountry() != null - && !locale.getCountry().equals("")) { - newFilename += "_" + locale.getCountry(); - } - if (locale.getVariant() != null - && !locale.getCountry().equals("")) { - newFilename += "_" + locale.getVariant(); - } - newFilename += ".properties"; + 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(); + 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(); } /** @@ -124,14 +124,14 @@ protected IStatus run(IProgressMonitor monitor) { * @param locale */ public static void addLanguageToProject(IProject project, Locale locale) { - ResourceBundleManager rbManager = ResourceBundleManager - .getManager(project); + 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); - } + // Audit if all resourecbundles provide this locale. if not - add new + // file + for (String rbId : rbManager.getResourceBundleIdentifiers()) { + addLanguageToResourceBundle(project, rbId, locale); + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java index 6f0bb4f4..6544b7a8 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java @@ -18,33 +18,33 @@ 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; + 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; + String displayName) { + for (Locale l : locales) { + String name = l == null ? ResourceBundleManager.defaultLocaleTag + : l.getDisplayName(); + if (name.equals(displayName) + || (name.trim().length() == 0 && displayName + .equals(ResourceBundleManager.defaultLocaleTag))) { + return true; + } + } + + return false; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java index 5f8ff62d..9c4d0089 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java @@ -45,45 +45,45 @@ public class RBFileUtils extends Action { * 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; + 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; } /** @@ -91,21 +91,21 @@ public static boolean isResourceBundleFile(IResource file) { * @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; + 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; } /** @@ -116,20 +116,20 @@ public static Set<String> getResourceBundleIds(IContainer container) { */ // 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; + 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; } /** @@ -141,31 +141,31 @@ public static String getCorrespondingResourceBundleId(IFile file) { * @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(); + 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(); } /** @@ -177,12 +177,12 @@ protected IStatus run(IProgressMonitor monitor) { * @return */ public static void removeLanguageFromProject(IProject project, Locale locale) { - ResourceBundleManager rbManager = ResourceBundleManager - .getManager(project); + ResourceBundleManager rbManager = ResourceBundleManager + .getManager(project); - for (String rbId : rbManager.getResourceBundleIdentifiers()) { - removeFileFromResourceBundle(project, rbId, locale); - } + for (String rbId : rbManager.getResourceBundleIdentifiers()) { + removeFileFromResourceBundle(project, rbId, locale); + } } @@ -190,60 +190,60 @@ public static void removeLanguageFromProject(IProject project, Locale 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; + 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(); + 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; + 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 index d43d8401..2aa36fb8 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java @@ -25,56 +25,56 @@ public class ResourceUtils { private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*"; public static boolean isValidResourceKey(String key) { - boolean isValid = false; + boolean isValid = false; - if (key != null && key.trim().length() > 0) { - isValid = key.matches(REGEXP_RESOURCE_KEY); - } + if (key != null && key.trim().length() > 0) { + isValid = key.matches(REGEXP_RESOURCE_KEY); + } - return isValid; + 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; + 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; + boolean result = false; - if (res.getType() == IResource.FILE && !res.isDerived() - && res.getFileExtension().equalsIgnoreCase("java")) { - result = true; - } + if (res.getType() == IResource.FILE && !res.isDerived() + && res.getFileExtension().equalsIgnoreCase("java")) { + result = true; + } - return result; + return result; } public static boolean isJSPResource(IResource res) { - boolean result = false; + boolean result = false; - if (res.getType() == IResource.FILE - && !res.isDerived() - && (res.getFileExtension().equalsIgnoreCase("jsp") || res - .getFileExtension().equalsIgnoreCase("xhtml"))) { - result = true; - } + if (res.getType() == IResource.FILE + && !res.isDerived() + && (res.getFileExtension().equalsIgnoreCase("jsp") || res + .getFileExtension().equalsIgnoreCase("xhtml"))) { + result = true; + } - return result; + return result; } /** @@ -85,17 +85,17 @@ public static boolean isJSPResource(IResource res) { * @return List of */ public static List<IContainer> getCorrespondingFolders( - IContainer baseFolder, List<IProject> targetProjects) { - List<IContainer> correspondingFolder = new ArrayList<IContainer>(); + 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); - } - } + for (IProject p : targetProjects) { + IContainer c = getCorrespondingFolders(baseFolder, p); + if (c.exists()) { + correspondingFolder.add(c); + } + } - return correspondingFolder; + return correspondingFolder; } /** @@ -106,15 +106,15 @@ public static List<IContainer> getCorrespondingFolders( * 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; - } + IProject targetProject) { + IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo( + baseFolder.getProject().getFullPath()); + + if (!relativ_folder.isEmpty()) { + return targetProject.getFolder(relativ_folder); + } else { + return targetProject; + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java index a91ca06e..07e865e9 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,7 +54,7 @@ import org.eclipse.ui.progress.UIJob; public class MessagesView extends ViewPart implements - IResourceBundleChangedListener { + IResourceBundleChangedListener { /** * The ID of the view as specified by the extension. @@ -95,447 +95,447 @@ public MessagesView() { * it. */ public void createPartControl(Composite parent) { - this.parent = parent; - - initLayout(parent); - initSearchBar(parent); - initMessagesTree(parent); - makeActions(); - hookContextMenu(); - contributeToActionBars(); - initListener(parent); + this.parent = parent; + + initLayout(parent); + initSearchBar(parent); + initMessagesTree(parent); + makeActions(); + hookContextMenu(); + contributeToActionBars(); + initListener(parent); } protected void initListener(Composite parent) { - filter.addModifyListener(new ModifyListener() { + filter.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - treeViewer.setSearchString(filter.getText()); - } - }); + @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); + 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(); + // 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(); + 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); + 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(); + 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(); + 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); - } + 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()); + 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()); + 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.removeAll(); + manager.add(selectResourceBundle); + manager.add(enableFuzzyMatching); + manager.add(editable); + manager.add(new Separator()); - manager.add(contextDependentMenu); - 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); - } + 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(); + 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)); + 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); + 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) { - } + 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); + super.init(site, memento); - // init Viewstate - viewState = new MessagesViewState(null, null, false, null); - viewState.init(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: - // 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); - } + try { + if (!event.getBundle().equals(treeViewer.getResourceBundle())) + return; + + switch (event.getType()) { + 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) { - } + try { + super.dispose(); + treeViewer.dispose(); + ResourceBundleManager + .getManager(viewState.getSelectedProjectName()) + .unregisterResourceBundleChangeListener( + viewState.getSelectedBundleId(), this); + } catch (Exception e) { + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java index 6c7a2d4f..0d82c933 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java @@ -42,176 +42,176 @@ public class MessagesViewState { private boolean editable; public void saveState(IMemento memento) { - try { - if (memento == null) - return; + 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 (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); - } + if (sortings != null) { + sortings.saveState(memento); + } - IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING); - memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled); + IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING); + memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled); - IMemento memMatchingPrec = memento - .createChild(TAG_MATCHING_PRECISION); - memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision); + IMemento memMatchingPrec = memento + .createChild(TAG_MATCHING_PRECISION); + memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision); - selectedProjectName = selectedProjectName != null ? selectedProjectName - : ""; - selectedBundleId = selectedBundleId != null ? selectedBundleId : ""; + selectedProjectName = selectedProjectName != null ? selectedProjectName + : ""; + selectedBundleId = selectedBundleId != null ? selectedBundleId : ""; - IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT); - memSP.putString(TAG_VALUE, selectedProjectName); + 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 memSB = memento.createChild(TAG_SELECTED_BUNDLE); + memSB.putString(TAG_VALUE, selectedBundleId); - IMemento memSStr = memento.createChild(TAG_SEARCH_STRING); - memSStr.putString(TAG_VALUE, searchString); + 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) { + 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); + 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; + boolean fuzzyMatchingEnabled, String selectedBundleId) { + super(); + this.visibleLocales = visibleLocales; + this.sortings = sortings; + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + this.selectedBundleId = selectedBundleId; } public List<Locale> getVisibleLocales() { - return visibleLocales; + return visibleLocales; } public void setVisibleLocales(List<Locale> visibleLocales) { - this.visibleLocales = visibleLocales; + this.visibleLocales = visibleLocales; } public SortInfo getSortings() { - return sortings; + return sortings; } public void setSortings(SortInfo sortings) { - this.sortings = sortings; + this.sortings = sortings; } public boolean isFuzzyMatchingEnabled() { - return fuzzyMatchingEnabled; + return fuzzyMatchingEnabled; } public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) { - this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; } public void setSelectedBundleId(String selectedBundleId) { - this.selectedBundleId = selectedBundleId; + this.selectedBundleId = selectedBundleId; } public void setSelectedProjectName(String selectedProjectName) { - this.selectedProjectName = selectedProjectName; + this.selectedProjectName = selectedProjectName; } public void setSearchString(String searchString) { - this.searchString = searchString; + this.searchString = searchString; } public String getSelectedBundleId() { - return selectedBundleId; + return selectedBundleId; } public String getSelectedProjectName() { - return selectedProjectName; + return selectedProjectName; } public String getSearchString() { - return searchString; + return searchString; } public boolean isEditable() { - return editable; + return editable; } public void setEditable(boolean editable) { - this.editable = editable; + this.editable = editable; } public float getMatchingPrecision() { - return matchingPrecision; + return matchingPrecision; } public void setMatchingPrecision(float value) { - this.matchingPrecision = value; + this.matchingPrecision = value; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java index f49fa2b9..70760968 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 @@ -25,7 +25,7 @@ import org.eclipse.ui.PlatformUI; public class ResourceBundleEntry extends ContributionItem implements - ISelectionChangedListener { + ISelectionChangedListener { private PropertyKeySelectionTree parentView; private ISelection selection; @@ -41,104 +41,105 @@ public ResourceBundleEntry() { } public ResourceBundleEntry(PropertyKeySelectionTree view, - ISelection selection) { - this.selection = selection; - this.legalSelection = !selection.isEmpty(); - this.parentView = view; - parentView.addSelectionChangedListener(this); + 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 refactoring the currently selected entry - refactorItem = new MenuItem(menu, SWT.NONE, index + 2); - refactorItem.setText("Refactor ..."); - refactorItem.setImage(UIUtils.getImageDescriptor(UIUtils.IMAGE_REFACTORING).createImage()); - refactorItem.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - parentView.refactorSelectedItem(); - } - - @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(); - } + // 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 refactoring the currently selected entry + refactorItem = new MenuItem(menu, SWT.NONE, index + 2); + refactorItem.setText("Refactor ..."); + refactorItem.setImage(UIUtils.getImageDescriptor( + UIUtils.IMAGE_REFACTORING).createImage()); + refactorItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.refactorSelectedItem(); + } + + @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); - refactorItem.setEnabled(legalSelection); - removeItem.setEnabled(legalSelection); - } catch (Exception e) { - // silent catch - } + try { + editItem.setEnabled(legalSelection); + refactorItem.setEnabled(legalSelection); + removeItem.setEnabled(legalSelection); + } catch (Exception e) { + // silent catch + } } @Override public void selectionChanged(SelectionChangedEvent event) { - legalSelection = !event.getSelection().isEmpty(); - // enableMenuItems (); + legalSelection = !event.getSelection().isEmpty(); + // enableMenuItems (); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java index 07442358..0ede994a 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java @@ -26,40 +26,40 @@ public class SortInfo { private List<Locale> visibleLocales; public void setDESC(boolean dESC) { - DESC = dESC; + DESC = dESC; } public boolean isDESC() { - return DESC; + return DESC; } public void setColIdx(int colIdx) { - this.colIdx = colIdx; + this.colIdx = colIdx; } public int getColIdx() { - return colIdx; + return colIdx; } public void setVisibleLocales(List<Locale> visibleLocales) { - this.visibleLocales = visibleLocales; + this.visibleLocales = visibleLocales; } public List<Locale> getVisibleLocales() { - return visibleLocales; + 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); + 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); + IMemento mCI = memento.getChild(TAG_SORT_INFO); + if (mCI == null) + return; + colIdx = mCI.getInteger(TAG_COLUMN_INDEX); + DESC = mCI.getBoolean(TAG_ORDER); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java index 3033bada..7416afb1 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 @@ -36,145 +36,145 @@ public class KeyTreeItemDropTarget extends DropTargetAdapter { private final TreeViewer target; public KeyTreeItemDropTarget(TreeViewer viewer) { - super(); - this.target = viewer; + super(); + this.target = viewer; } public void dragEnter(DropTargetEvent event) { - // if (((DropTarget)event.getSource()).getControl() instanceof Tree) - // event.detail = DND.DROP_MOVE; + // 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); - } + 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(); + IMessagesBundleGroup group) { + String key = children.getMessageKey(); - for (IKeyTreeNode childs : children.getChildren()) { - remBundleEntries(childs, group); - } + for (IKeyTreeNode childs : children.getChildren()) { + remBundleEntries(childs, group); + } - group.removeMessagesAddParentKey(key); + 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); - } - } - }); + Display.getDefault().asyncExec(new Runnable() { + public void run() { + try { + + if (TextTransfer.getInstance().isSupportedType( + event.currentDataType)) { + String newKeyPrefix = ""; + + if (event.item instanceof TreeItem + && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { + IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item) + .getData(); + newKeyPrefix = targetTreeNode.getMessageKey(); + } + + String message = (String) event.data; + String oldKey = message.replaceAll("\"", ""); + + String[] keyArr = (oldKey).split("\\."); + String key = keyArr[keyArr.length - 1]; + + ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target + .getContentProvider(); + IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target + .getInput(); + + // key gets dropped into it's parent node + if (oldKey.equals(newKeyPrefix + "." + key)) + return; // TODO: give user feedback + + // prevent cycle loop if key gets dropped into its child + // node + if (newKeyPrefix.contains(oldKey)) + return; // TODO: give user feedback + + // source node already exists in target + IKeyTreeNode targetTreeNode = keyTree + .getChild(newKeyPrefix); + for (IKeyTreeNode targetChild : targetTreeNode + .getChildren()) { + if (targetChild.getName().equals(key)) + return; // TODO: give user feedback + } + + IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey); + + IMessagesBundleGroup bundleGroup = contentProvider + .getBundle(); + + DirtyHack.setFireEnabled(false); + DirtyHack.setEditorModificationEnabled(false); // editor + // won't + // get + // dirty + + // add new bundle entries of source node + all children + addBundleEntries(newKeyPrefix, sourceTreeNode, + bundleGroup); + + // if drag & drop is move event, delete source entry + + // it's children + if (event.detail == DND.DROP_MOVE) { + remBundleEntries(sourceTreeNode, bundleGroup); + } + + // Store changes + RBManager manager = RBManager + .getInstance(((MessagesBundleGroup) bundleGroup) + .getProjectName()); + + manager.writeToFile(bundleGroup); + manager.fireEditorChanged(); // refresh the View + + target.refresh(); + } else { + event.detail = DND.DROP_NONE; + } + + } catch (Exception e) { + Logger.logError(e); + } finally { + DirtyHack.setFireEnabled(true); + DirtyHack.setEditorModificationEnabled(true); + } + } + }); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java index 0739878b..b5aa199d 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 @@ -33,84 +33,84 @@ public class KeyTreeItemTransfer extends ByteArrayTransfer { private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer(); public static KeyTreeItemTransfer getInstance() { - return transfer; + 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); - } + 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; + 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 }; + return new String[] { KEY_TREE_ITEM }; } protected int[] getTypeIds() { - return new int[] { TYPEID }; + 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; + 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); + return checkType(object); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java index d6c0094e..8329c589 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 @@ -22,8 +22,8 @@ public class MessagesDragSource implements DragSourceListener { private String bundleId; public MessagesDragSource(TreeViewer sourceView, String bundleId) { - source = sourceView; - this.bundleId = bundleId; + source = sourceView; + this.bundleId = bundleId; } @Override @@ -33,22 +33,22 @@ 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(); + String key = selectionObject.getMessageKey(); - // TODO Solve the problem that its not possible to retrieve the editor - // position of the drop event + // TODO Solve the problem that its not possible to retrieve the editor + // position of the drop event - // event.data = "(new ResourceBundle(\"" + bundleId + - // "\")).getString(\"" + key + "\")"; - event.data = "\"" + key + "\""; + // event.data = "(new ResourceBundle(\"" + bundleId + + // "\")).getString(\"" + key + "\")"; + event.data = "\"" + key + "\""; } @Override public void dragStart(DragSourceEvent event) { - event.doit = !source.getSelection().isEmpty(); + event.doit = !source.getSelection().isEmpty(); } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java index 8d0906ad..be8e81f7 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 @@ -28,48 +28,48 @@ public class MessagesDropTarget extends DropTargetAdapter { private String bundleName; public MessagesDropTarget(TreeViewer viewer, String projectName, - String bundleName) { - super(); - this.projectName = projectName; - this.bundleName = bundleName; + 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 (event.detail != DND.DROP_COPY) + return; - if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) { - // event.feedback = DND.FEEDBACK_INSERT_BEFORE; - String newKeyPrefix = ""; + if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) { + // event.feedback = DND.FEEDBACK_INSERT_BEFORE; + String newKeyPrefix = ""; - if (event.item instanceof TreeItem - && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { - newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item) - .getData()).getMessageKey(); - } + if (event.item instanceof TreeItem + && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { + newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item) + .getData()).getMessageKey(); + } - String message = (String) event.data; + String message = (String) event.data; - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix - + "." + "[Platzhalter]" - : ""); - config.setPreselectedMessage(message); - config.setPreselectedBundle(bundleName); - config.setPreselectedLocale(""); - config.setProjectName(projectName); + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + + "." + "[Platzhalter]" + : ""); + config.setPreselectedMessage(message); + config.setPreselectedBundle(bundleName); + config.setPreselectedLocale(""); + config.setProjectName(projectName); - dialog.setDialogConfiguration(config); + dialog.setDialogConfiguration(config); - if (dialog.open() != InputDialog.OK) - return; - } else - event.detail = DND.DROP_NONE; + if (dialog.open() != InputDialog.OK) + return; + } else + event.detail = DND.DROP_NONE; } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java index b8e18a39..57ee79c2 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 @@ -90,7 +90,7 @@ import org.eclipse.ui.PlatformUI; public class PropertyKeySelectionTree extends Composite implements - IResourceBundleChangedListener { + IResourceBundleChangedListener { private final int KEY_COLUMN_WEIGHT = 1; private final int LOCALE_COLUMN_WEIGHT = 1; @@ -130,703 +130,705 @@ public class PropertyKeySelectionTree extends Composite implements 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; + 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; - } + if (resourceBundle != null && resourceBundle.trim().length() > 0) { + if (locales == null) + initVisibleLocales(); + else + this.visibleLocales = locales; + } - constructWidget(); + constructWidget(); - if (resourceBundle != null && resourceBundle.trim().length() > 0) { - initTreeViewer(); - initMatchers(); - initSorters(); - treeViewer.expandAll(); - } + if (resourceBundle != null && resourceBundle.trim().length() > 0) { + initTreeViewer(); + initMatchers(); + initSorters(); + treeViewer.expandAll(); + } - hookDragAndDrop(); - registerListeners(); + hookDragAndDrop(); + registerListeners(); } @Override public void dispose() { - super.dispose(); - unregisterListeners(); + super.dispose(); + unregisterListeners(); } protected void initSorters() { - sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo); - treeViewer.setSorter(sorter); + 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(); + 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; + return fuzzyMatchingEnabled; } protected void initMatchers() { - treeViewer.resetFilters(); + treeViewer.resetFilters(); - if (fuzzyMatchingEnabled) { - matcher = new FuzzyMatcher(treeViewer); - ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision); - } else - matcher = new ExactMatcher(treeViewer); + 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); + 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); + 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); + if (visibleLocales == null) { + initVisibleLocales(); + } + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); - // update content provider - contentProvider.setLocales(visibleLocales); - contentProvider.setProjectName(manager.getProject().getName()); - contentProvider.setBundleId(resourceBundle); + // 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); + // init label provider + IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle); + labelProvider.setLocales(visibleLocales); + if (treeViewer.getLabelProvider() != labelProvider) + treeViewer.setLabelProvider(labelProvider); - // define input of treeviewer - setTreeStructure(); + // 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); + 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); + basicLayout = new TreeColumnLayout(); + this.setLayout(basicLayout); - treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE - | SWT.BORDER); - Tree tree = treeViewer.getTree(); + treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE + | SWT.BORDER); + Tree tree = treeViewer.getTree(); - if (resourceBundle != null) { - tree.setHeaderVisible(true); - tree.setLinesVisible(true); + if (resourceBundle != null) { + tree.setHeaderVisible(true); + tree.setLinesVisible(true); - // create tree-columns - constructTreeColumns(tree); - } else { - tree.setHeaderVisible(false); - tree.setLinesVisible(false); - } + // create tree-columns + constructTreeColumns(tree); + } else { + tree.setHeaderVisible(false); + tree.setLinesVisible(false); + } - makeActions(); - hookDoubleClickAction(); + makeActions(); + hookDoubleClickAction(); - // register messages table as selection provider - site.setSelectionProvider(treeViewer); + // 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)); - } - } + 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(); + 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(); + 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); + // 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() { + doubleClickAction = new Action() { - @Override - public void run() { - editSelectedItem(); - } + @Override + public void run() { + editSelectedItem(); + } - }; + }; } private void hookDoubleClickAction() { - treeViewer.addDoubleClickListener(new IDoubleClickListener() { + treeViewer.addDoubleClickListener(new IDoubleClickListener() { - public void doubleClick(DoubleClickEvent event) { - doubleClickAction.run(); - } - }); + 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); - } + this.editorListener = new MessagesEditorListener(); + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + if (manager != null) { + RBManager.getInstance(manager.getProject()) + .addMessagesEditorListener(editorListener); + } - treeViewer.getControl().addKeyListener(new KeyAdapter() { + treeViewer.getControl().addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent event) { - if (event.character == SWT.DEL && event.stateMask == 0) { - deleteSelectedItems(); - } - } - }); + 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); + 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; + treeViewer.addSelectionChangedListener(listener); + selectionChangedListener = listener; } @Override public void resourceBundleChanged(final ResourceBundleChangedEvent event) { - if (event.getType() != ResourceBundleChangedEvent.MODIFIED - || !event.getBundle().equals(this.getResourceBundle())) - return; + if (event.getType() != ResourceBundleChangedEvent.MODIFIED + || !event.getBundle().equals(this.getResourceBundle())) + return; - if (Display.getCurrent() != null) { - refreshViewer(event, true); - return; - } + if (Display.getCurrent() != null) { + refreshViewer(event, true); + return; + } - Display.getDefault().asyncExec(new Runnable() { + Display.getDefault().asyncExec(new Runnable() { - public void run() { - refreshViewer(event, true); - } - }); + public void run() { + refreshViewer(event, true); + } + }); } private void refreshViewer(ResourceBundleChangedEvent event, - boolean computeVisibleLocales) { - // manager.loadResourceBundle(resourceBundle); - if (computeVisibleLocales) { - refreshContent(event); - } + boolean computeVisibleLocales) { + // manager.loadResourceBundle(resourceBundle); + if (computeVisibleLocales) { + refreshContent(event); + } - // Display.getDefault().asyncExec(new Runnable() { - // public void run() { - treeViewer.refresh(); - // } - // }); + // Display.getDefault().asyncExec(new Runnable() { + // public void run() { + treeViewer.refresh(); + // } + // }); } public StructuredViewer getViewer() { - return this.treeViewer; + 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(); + 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); + this.refreshContent(null); - // highlight the search results - labelProvider.updateTreeViewer(treeViewer); + // highlight the search results + labelProvider.updateTreeViewer(treeViewer); } public SortInfo getSortInfo() { - if (this.sorter != null) - return this.sorter.getSortInfo(); - else - return null; + 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(); - } + 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(); + return matcher.getPattern(); } public boolean isEditable() { - return editable; + return editable; } public void setEditable(boolean editable) { - this.editable = editable; + this.editable = editable; } public List<Locale> getVisibleLocales() { - return visibleLocales; + return visibleLocales; } public String getResourceBundle() { - return resourceBundle; + 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); + 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 refactorSelectedItem() { - String key = ""; - String bundleId = ""; - 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(); - bundleId = keyTreeNode.getMessagesBundleGroup().getResourceBundleId(); - - RBManager.getRefactorService().openRefactorDialog(projectName, bundleId, key, null); - } - } - } - + String key = ""; + String bundleId = ""; + 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(); + bundleId = keyTreeNode.getMessagesBundleGroup() + .getResourceBundleId(); + + RBManager.getRefactorService().openRefactorDialog(projectName, + bundleId, key, null); + } + } + } + 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); - } + 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); - } + 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; + // 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(); - } + matchingPrecision = value; + if (matcher instanceof FuzzyMatcher) { + ((FuzzyMatcher) matcher).setMinimumSimilarity(value); + treeViewer.refresh(); + } } public float getMatchingPrecision() { - return matchingPrecision; + 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 - - } + @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 d14feb66..bd1466e9 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 @@ -61,210 +61,210 @@ public class ResourceSelector extends Composite { private StyledCellLabelProvider labelProvider; public ResourceSelector(Composite parent, int style) { - super(parent, style); + super(parent, style); - initLayout(this); - initViewer(this); + 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); + // 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); + 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); + 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; - } - }); + 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; + return displayLocale; } public void setDisplayLocale(Locale displayLocale) { - this.displayLocale = displayLocale; - updateViewer(false); + this.displayLocale = displayLocale; + updateViewer(false); } public int getDisplayMode() { - return displayMode; + return displayMode; } public void setDisplayMode(int displayMode) { - this.displayMode = displayMode; - updateViewer(true); + this.displayMode = displayMode; + updateViewer(true); } public void setResourceBundle(String resourceBundle) { - this.resourceBundle = resourceBundle; - updateViewer(true); + this.resourceBundle = resourceBundle; + updateViewer(true); } public String getResourceBundle() { - return resourceBundle; + return resourceBundle; } public void addSelectionChangedListener(IResourceSelectionListener l) { - listeners.add(l); + listeners.add(l); } public void removeSelectionChangedListener(IResourceSelectionListener l) { - listeners.remove(l); + listeners.remove(l); } private void fireSelectionChanged(ResourceSelectionEvent event) { - Iterator<IResourceSelectionListener> itResList = listeners.iterator(); - while (itResList.hasNext()) { - itResList.next().selectionChanged(event); - } + Iterator<IResourceSelectionListener> itResList = listeners.iterator(); + while (itResList.hasNext()) { + itResList.next().selectionChanged(event); + } } public void setProjectName(String projectName) { - this.projectName = projectName; + this.projectName = projectName; } public boolean isShowTree() { - return showTree; + return showTree; } public void setShowTree(boolean showTree) { - if (this.showTree != showTree) { - this.showTree = showTree; - this.treeType = showTree ? TreeType.Tree : TreeType.Flat; - updateViewer(false); - } + if (this.showTree != showTree) { + this.showTree = showTree; + this.treeType = showTree ? TreeType.Tree : TreeType.Flat; + updateViewer(false); + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java index 586ce13f..955b2a05 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 @@ -16,24 +16,24 @@ public class ResourceSelectionEvent { private String selectedKey; public ResourceSelectionEvent(String selectedKey, String selectionSummary) { - this.setSelectionSummary(selectionSummary); - this.setSelectedKey(selectedKey); + this.setSelectionSummary(selectionSummary); + this.setSelectedKey(selectedKey); } public void setSelectedKey(String key) { - selectedKey = key; + selectedKey = key; } public void setSelectionSummary(String selectionSummary) { - this.selectionSummary = selectionSummary; + this.selectionSummary = selectionSummary; } public String getSelectionSummary() { - return selectionSummary; + return selectionSummary; } public String getSelectedKey() { - return selectedKey; + 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 da604562..c2c77473 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 @@ -24,66 +24,66 @@ public class ExactMatcher extends ViewerFilter { protected StringMatcher matcher; public ExactMatcher(StructuredViewer viewer) { - this.viewer = viewer; + this.viewer = viewer; } public String getPattern() { - return pattern; + 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); - } - } + 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()); + IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element; + FilterInfo filterInfo = new FilterInfo(); + boolean selected = matcher.match(vEle.getMessageKey()); - if (selected) { - int start = -1; - while ((start = vEle.getMessageKey().toLowerCase() - .indexOf(pattern.toLowerCase(), start + 1)) >= 0) { - filterInfo.addKeyOccurrence(start, pattern.length()); - } - filterInfo.setFoundInKey(selected); - filterInfo.setFoundInKey(true); - } else - filterInfo.setFoundInKey(false); + if (selected) { + int start = -1; + while ((start = vEle.getMessageKey().toLowerCase() + .indexOf(pattern.toLowerCase(), start + 1)) >= 0) { + filterInfo.addKeyOccurrence(start, pattern.length()); + } + filterInfo.setFoundInKey(selected); + filterInfo.setFoundInKey(true); + } else + filterInfo.setFoundInKey(false); - // Iterate translations - for (Locale l : vEle.getLocales()) { - String value = vEle.getValue(l); - if (matcher.match(value)) { - filterInfo.addFoundInLocale(l); - filterInfo.addSimilarity(l, 1d); - int start = -1; - while ((start = value.toLowerCase().indexOf( - pattern.toLowerCase(), start + 1)) >= 0) { - filterInfo - .addFoundInLocaleRange(l, start, pattern.length()); - } - selected = true; - } - } + // Iterate translations + for (Locale l : vEle.getLocales()) { + String value = vEle.getValue(l); + if (matcher.match(value)) { + filterInfo.addFoundInLocale(l); + filterInfo.addSimilarity(l, 1d); + int start = -1; + while ((start = value.toLowerCase().indexOf( + pattern.toLowerCase(), start + 1)) >= 0) { + filterInfo + .addFoundInLocaleRange(l, start, pattern.length()); + } + selected = true; + } + } - vEle.setInfo(filterInfo); - return selected; + 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 e53959a3..654d4d23 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 @@ -32,63 +32,63 @@ public FilterInfo() { } public void setKeySimilarity(Double similarity) { - keySimilarity = similarity; + keySimilarity = similarity; } public Double getKeySimilarity() { - return keySimilarity; + return keySimilarity; } public void addSimilarity(Locale l, Double similarity) { - localeSimilarity.put(l, similarity); + localeSimilarity.put(l, similarity); } public Double getSimilarityLevel(Locale l) { - return localeSimilarity.get(l); + return localeSimilarity.get(l); } public void setFoundInKey(boolean foundInKey) { - this.foundInKey = foundInKey; + this.foundInKey = foundInKey; } public boolean isFoundInKey() { - return foundInKey; + return foundInKey; } public void addFoundInLocale(Locale loc) { - foundInLocales.add(loc); + foundInLocales.add(loc); } public void removeFoundInLocale(Locale loc) { - foundInLocales.remove(loc); + foundInLocales.remove(loc); } public void clearFoundInLocale() { - foundInLocales.clear(); + foundInLocales.clear(); } public boolean hasFoundInLocale(Locale l) { - return foundInLocales.contains(l); + return foundInLocales.contains(l); } public List<Region> getFoundInLocaleRanges(Locale locale) { - List<Region> reg = occurrences.get(locale); - return (reg == null ? new ArrayList<Region>() : reg); + 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); + 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; + return keyOccurrences; } public void addKeyOccurrence(int start, int length) { - keyOccurrences.add(new Region(start, 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 aee3c114..e3288015 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 @@ -24,42 +24,42 @@ public class FuzzyMatcher extends ExactMatcher { protected float minimumSimilarity = 0.75f; public FuzzyMatcher(StructuredViewer viewer) { - super(viewer); - lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer(); - ; + super(viewer); + lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer(); + ; } public double getMinimumSimilarity() { - return minimumSimilarity; + return minimumSimilarity; } public void setMinimumSimilarity(float similarity) { - this.minimumSimilarity = similarity; + this.minimumSimilarity = similarity; } @Override public boolean select(Viewer viewer, Object parentElement, Object element) { - boolean exactMatch = super.select(viewer, parentElement, element); - boolean match = exactMatch; + boolean exactMatch = super.select(viewer, parentElement, element); + boolean match = exactMatch; - IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; - FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); + IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; + FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); - for (Locale l : vkti.getLocales()) { - String value = vkti.getValue(l); - if (filterInfo.hasFoundInLocale(l)) - continue; - double dist = lvda.analyse(value, getPattern()); - if (dist >= minimumSimilarity) { - filterInfo.addFoundInLocale(l); - filterInfo.addSimilarity(l, dist); - match = true; - filterInfo.addFoundInLocaleRange(l, 0, value.length()); - } - } + 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; + 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 841f0d9d..8affc33d 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 @@ -29,7 +29,7 @@ public class StringMatcher { protected boolean fHasTrailingStar; protected String fSegments[]; // the given pattern is split into * separated - // segments + // segments /* boundary value beyond which we don't need to search in the text */ protected int fBound = 0; @@ -37,22 +37,22 @@ public class StringMatcher { protected static final char fSingleWildCard = '\u0000'; public static class Position { - int start; // inclusive + int start; // inclusive - int end; // exclusive + int end; // exclusive - public Position(int start, int end) { - this.start = start; - this.end = end; - } + public Position(int start, int end) { + this.start = start; + this.end = end; + } - public int getStart() { - return start; - } + public int getStart() { + return start; + } - public int getEnd() { - return end; - } + public int getEnd() { + return end; + } } /** @@ -79,20 +79,20 @@ public int getEnd() { * (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(); - } + boolean ignoreWildCards) { + if (pattern == null) { + throw new IllegalArgumentException(); + } + fIgnoreCase = ignoreCase; + fIgnoreWildCards = ignoreWildCards; + fPattern = pattern; + fLength = pattern.length(); + + if (fIgnoreWildCards) { + parseNoWildCards(); + } else { + parseWildCards(); + } } /** @@ -115,54 +115,54 @@ public StringMatcher(String pattern, boolean ignoreCase, * "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); + 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); } /** @@ -173,10 +173,10 @@ public StringMatcher.Position find(String text, int start, int end) { * a String object */ public boolean match(String text) { - if (text == null) { - return false; - } - return match(text, 0, text.length()); + if (text == null) { + return false; + } + return match(text, 0, text.length()); } /** @@ -193,87 +193,87 @@ public boolean match(String text) { * 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; + 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; } /** @@ -282,9 +282,9 @@ public boolean match(String text, int start, int end) { * pattern consists of a single segment. */ private void parseNoWildCards() { - fSegments = new String[1]; - fSegments[0] = fPattern; - fBound = fLength; + fSegments = new String[1]; + fSegments[0] = fPattern; + fBound = fLength; } /** @@ -296,63 +296,63 @@ private void parseNoWildCards() { * 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); + 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); } /** @@ -366,24 +366,24 @@ private void parseWildCards() { * 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; + // 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; } /** @@ -399,15 +399,15 @@ protected int posIn(String text, int start, int end) {// no wild card in * 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; + 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; } /** @@ -427,37 +427,37 @@ protected int regExpPosIn(String text, int start, int end, String p) { * 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; + 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; } /** @@ -474,23 +474,23 @@ protected boolean regExpRegionMatches(String text, int tStart, String p, */ protected int textPosIn(String text, int start, int end, String p) { - int plen = p.length(); - int max = end - plen; + 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; - } + if (!fIgnoreCase) { + int i = text.indexOf(p, start); + if (i == -1 || i > max) { + return -1; + } + return i; + } - for (int i = start; i <= max; ++i) { - if (text.regionMatches(true, i, p, 0, plen)) { - return i; - } - } + for (int i = start; i <= max; ++i) { + if (text.regionMatches(true, i, 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/provider/KeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java index 876dc352..cbc3eaed 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 @@ -23,46 +23,46 @@ * * @author Alexej Strelzow */ -public abstract class KeyTreeLabelProvider extends StyledCellLabelProvider implements - IFontProvider, IColorProvider { +public abstract class KeyTreeLabelProvider extends StyledCellLabelProvider + implements IFontProvider, IColorProvider { - public KeyTreeLabelProvider() { - setOwnerDrawEnabled(true); - } - - /** - * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object) - */ - public Font getFont(Object element) { - return null; - } + public KeyTreeLabelProvider() { + setOwnerDrawEnabled(true); + } - /** - * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object) - */ - public Color getForeground(Object element) { - return null; - } + /** + * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object) + */ + public Font getFont(Object element) { + return null; + } - /** - * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object) - */ - public Color getBackground(Object element) { - return null; - } - - public abstract String getColumnText(Object element, int columnIndex); - - public abstract Image getColumnImage(Object element, int columnIndex); + /** + * @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; + } + + public abstract String getColumnText(Object element, int columnIndex); + + public abstract Image getColumnImage(Object element, int columnIndex); + + /** + * {@inheritDoc} + */ + @Override + public void update(ViewerCell cell) { + cell.setText(getColumnText(cell.getElement(), cell.getColumnIndex())); + cell.setImage(getColumnImage(cell.getElement(), cell.getColumnIndex())); + super.update(cell); + } - /** - * {@inheritDoc} - */ - @Override - public void update(ViewerCell cell) { - cell.setText(getColumnText(cell.getElement(), cell.getColumnIndex())); - cell.setImage(getColumnImage(cell.getElement(), cell.getColumnIndex())); - super.update(cell); - } - } 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 a2dc85a3..ab0e33cb 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 @@ -45,142 +45,142 @@ public class ResKeyTreeContentProvider implements ITreeContentProvider { 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; + String bundleId, TreeType treeType) { + this.locales = locales; + this.projectName = projectName; + this.bundleId = bundleId; + this.treeType = treeType; } public void setBundleId(String bundleId) { - this.bundleId = bundleId; + this.bundleId = bundleId; } public void setProjectName(String projectName) { - this.projectName = projectName; + this.projectName = projectName; } public ResKeyTreeContentProvider() { - locales = new ArrayList<Locale>(); + locales = new ArrayList<Locale>(); } public void setLocales(List<Locale> locales) { - this.locales = 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]; - } + 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(); + 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]; - } + 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; - } + 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; - } + 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; - } + 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; + } } /** @@ -189,42 +189,42 @@ public int countChildren(Object element) { * @return key tree item */ private IKeyTreeNode getTreeSelection() { - IStructuredSelection selection = (IStructuredSelection) treeViewer - .getSelection(); - return ((IKeyTreeNode) selection.getFirstElement()); + 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; + 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; + return bundleId; } @Override public void dispose() { - // TODO Auto-generated method stub + // TODO Auto-generated method stub } public TreeType getTreeType() { - return treeType; + return treeType; } public void setTreeType(TreeType treeType) { - if (this.treeType != treeType) { - this.treeType = treeType; - if (viewer != null) { - viewer.refresh(); - } - } + 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 9b741916..54a8dac5 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 @@ -44,7 +44,7 @@ public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider { private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW); public ResKeyTreeLabelProvider(List<Locale> locales) { - this.locales = locales; + this.locales = locales; } /** @@ -52,32 +52,32 @@ public ResKeyTreeLabelProvider(List<Locale> 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; + 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; } /** @@ -85,107 +85,107 @@ public Image getColumnImage(Object element, int columnIndex) { */ @Override public String getColumnText(Object element, int columnIndex) { - if (columnIndex == 0) { - return ((IKeyTreeNode) element).getName(); - } - - if (columnIndex <= locales.size()) { - IValuedKeyTreeNode item = (IValuedKeyTreeNode) element; - String entry = item.getValue(locales.get(columnIndex - 1)); - if (entry != null) { - return entry; - } - } - return ""; + if (columnIndex == 0) { + return ((IKeyTreeNode) element).getName(); + } + + 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; + this.searchEnabled = enabled; } public boolean isSearchEnabled() { - return this.searchEnabled; + return this.searchEnabled; } public void setLocales(List<Locale> visibleLocales) { - locales = visibleLocales; + locales = visibleLocales; } protected boolean isMatchingToPattern(Object element, int columnIndex) { - boolean matching = false; + boolean matching = false; - if (element instanceof IValuedKeyTreeNode) { - IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; + if (element instanceof IValuedKeyTreeNode) { + IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; - if (vkti.getInfo() == null) - return false; + if (vkti.getInfo() == null) + return false; - FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); + FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); - if (columnIndex == 0) { - matching = filterInfo.isFoundInKey(); - } else { - matching = filterInfo.hasFoundInLocale(locales - .get(columnIndex - 1)); - } - } + if (columnIndex == 0) { + matching = filterInfo.isFoundInKey(); + } else { + matching = filterInfo.hasFoundInLocale(locales + .get(columnIndex - 1)); + } + } - return matching; + return matching; } protected boolean isSearchEnabled(Object element) { - return (element instanceof IValuedKeyTreeNode && searchEnabled); + return (element instanceof IValuedKeyTreeNode && searchEnabled); } public void updateTreeViewer(TreeViewer treeViewer) { - for (TreeItem item : treeViewer.getTree().getItems()) { - Rectangle bounds = item.getBounds(); - ViewerCell cell = treeViewer.getCell(new Point(bounds.x, bounds.y)); - ViewerRow viewerRow = cell.getViewerRow(); + for (TreeItem item : treeViewer.getTree().getItems()) { + Rectangle bounds = item.getBounds(); + ViewerCell cell = treeViewer.getCell(new Point(bounds.x, bounds.y)); + ViewerRow viewerRow = cell.getViewerRow(); - for (int i = 0; i < viewerRow.getColumnCount(); i++) { - updateCell(viewerRow.getCell(i)); - } - } + for (int i = 0; i < viewerRow.getColumnCount(); i++) { + updateCell(viewerRow.getCell(i)); + } + } } private void updateCell(ViewerCell cell) { - Object element = cell.getElement(); - int columnIndex = cell.getColumnIndex(); - - if (isSearchEnabled(element)) { - if (isMatchingToPattern(element, columnIndex)) { - List<StyleRange> styleRanges = new ArrayList<StyleRange>(); - FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element) - .getInfo(); - - if (columnIndex > 0) { - for (Region reg : filterInfo.getFoundInLocaleRanges(locales - .get(columnIndex - 1))) { - styleRanges.add(new StyleRange(reg.getOffset(), reg - .getLength(), black, info_color, SWT.BOLD)); - } - } else { - // check if the pattern has been found within the key - // section - if (filterInfo.isFoundInKey()) { - for (Region reg : filterInfo.getKeyOccurrences()) { - StyleRange sr = new StyleRange(reg.getOffset(), - reg.getLength(), black, info_color, - SWT.BOLD); - styleRanges.add(sr); - } - } - } - cell.setStyleRanges(styleRanges - .toArray(new StyleRange[styleRanges.size()])); - } else { - cell.setForeground(gray); - } - } else if (columnIndex == 0) { - super.update(cell); - } + Object element = cell.getElement(); + int columnIndex = cell.getColumnIndex(); + + if (isSearchEnabled(element)) { + if (isMatchingToPattern(element, columnIndex)) { + List<StyleRange> styleRanges = new ArrayList<StyleRange>(); + FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element) + .getInfo(); + + if (columnIndex > 0) { + for (Region reg : filterInfo.getFoundInLocaleRanges(locales + .get(columnIndex - 1))) { + styleRanges.add(new StyleRange(reg.getOffset(), reg + .getLength(), black, info_color, SWT.BOLD)); + } + } else { + // check if the pattern has been found within the key + // section + if (filterInfo.isFoundInKey()) { + for (Region reg : filterInfo.getKeyOccurrences()) { + StyleRange sr = new StyleRange(reg.getOffset(), + reg.getLength(), black, info_color, + SWT.BOLD); + styleRanges.add(sr); + } + } + } + cell.setStyleRanges(styleRanges + .toArray(new StyleRange[styleRanges.size()])); + } else { + cell.setForeground(gray); + } + } else if (columnIndex == 0) { + super.update(cell); + } } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java index 4efa9f26..55938982 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,12 +20,12 @@ import org.eclipse.swt.graphics.Image; public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements - ITableColorProvider, ITableFontProvider { + ITableColorProvider, ITableFontProvider { private IMessagesBundle locale; public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) { - this.locale = iBundle; + this.locale = iBundle; } /** @@ -33,7 +33,7 @@ public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) { */ @Override public Image getColumnImage(Object element, int columnIndex) { - return null; + return null; } /** @@ -41,17 +41,17 @@ public Image getColumnImage(Object element, int columnIndex) { */ @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 ""; + 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 ""; } /** @@ -59,7 +59,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); } /** @@ -67,7 +67,7 @@ public Color getBackground(Object element, int columnIndex) { */ @Override public Color getForeground(Object element, int columnIndex) { - return null; + return null; } /** @@ -75,7 +75,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); } } 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 824f7b46..e7d1c194 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 @@ -24,54 +24,54 @@ public class ValuedKeyTreeItemSorter extends ViewerSorter { private SortInfo sortInfo; public ValuedKeyTreeItemSorter(StructuredViewer viewer, SortInfo sortInfo) { - this.viewer = viewer; - this.sortInfo = sortInfo; + this.viewer = viewer; + this.sortInfo = sortInfo; } public StructuredViewer getViewer() { - return viewer; + return viewer; } public void setViewer(StructuredViewer viewer) { - this.viewer = viewer; + this.viewer = viewer; } public SortInfo getSortInfo() { - return sortInfo; + return sortInfo; } public void setSortInfo(SortInfo sortInfo) { - this.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; + try { + if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode)) + return super.compare(viewer, e1, e2); + IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1; + IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2; - int result = 0; + int result = 0; - if (sortInfo == null) - return 0; + if (sortInfo == null) + return 0; - if (sortInfo.getColIdx() == 0) - result = comp1.getMessageKey().compareTo(comp2.getMessageKey()); - else { - Locale loc = sortInfo.getVisibleLocales().get( - sortInfo.getColIdx() - 1); - result = (comp1.getValue(loc) == null ? "" : comp1 - .getValue(loc)) - .compareTo((comp2.getValue(loc) == null ? "" : comp2 - .getValue(loc))); - } + if (sortInfo.getColIdx() == 0) + result = comp1.getMessageKey().compareTo(comp2.getMessageKey()); + else { + Locale loc = sortInfo.getVisibleLocales().get( + sortInfo.getColIdx() - 1); + result = (comp1.getValue(loc) == null ? "" : comp1 + .getValue(loc)) + .compareTo((comp2.getValue(loc) == null ? "" : comp2 + .getValue(loc))); + } - return result * (sortInfo.isDESC() ? -1 : 1); - } catch (Exception e) { - return 0; - } + return result * (sortInfo.isDESC() ? -1 : 1); + } catch (Exception e) { + return 0; + } } } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java index 84c0844f..8d7bdf97 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java @@ -50,11 +50,11 @@ public Activator() { */ @Override public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - - // detect resource bundles - RBManager.getAllMessagesBundleGroupNames(); + super.start(context); + plugin = this; + + // detect resource bundles + RBManager.getAllMessagesBundleGroupNames(); } /* @@ -66,8 +66,8 @@ public void start(BundleContext context) throws Exception { */ @Override public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); + plugin = null; + super.stop(context); } /** @@ -76,7 +76,7 @@ public void stop(BundleContext context) throws Exception { * @return the shared instance */ public static Activator getDefault() { - return plugin; + return plugin; } /** @@ -88,12 +88,12 @@ public static Activator getDefault() { * @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; - } + ResourceBundle bundle = Activator.getDefault().getResourceBundle(); + try { + return (bundle != null) ? bundle.getString(key) : key; + } catch (MissingResourceException e) { + return key; + } } /** @@ -107,7 +107,7 @@ public static String getString(String key) { * @return localized string corresponding to key */ public static String getString(String key, String arg1) { - return MessageFormat.format(getString(key), new String[] { arg1 }); + return MessageFormat.format(getString(key), new String[] { arg1 }); } /** @@ -123,8 +123,8 @@ public static String getString(String key, String arg1) { * @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 }); + return MessageFormat + .format(getString(key), new String[] { arg1, arg2 }); } /** @@ -142,9 +142,9 @@ public static String getString(String key, String arg1, String arg2) { * @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 }); + String arg3) { + return MessageFormat.format(getString(key), new String[] { arg1, arg2, + arg3 }); } /** @@ -153,7 +153,7 @@ public static String getString(String key, String arg1, String arg2, * @return resource bundle */ protected ResourceBundle getResourceBundle() { - return resourceBundle; + return resourceBundle; } } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java index 8bfd10a5..7f21d7bc 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,30 +15,30 @@ 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); - } + 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 index e53d2b94..1faa7c3b 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 916f6ecc..36e21bf6 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 @@ -11,11 +11,11 @@ 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_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; + 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 f51fbca0..26727ee5 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 83f073be..cb80a2f5 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 setProjectName(String projName); - public void setRelativePath(String relPath); + public void setRelativePath(String relPath); - public void setAbsolutePath(String absPath); + public void setAbsolutePath(String absPath); - public void setBundleId(String bundleId); + public void setBundleId(String bundleId); - public String getProjectName(); + public String getProjectName(); - public String getRelativePath(); + public String getRelativePath(); - public String getAbsolutePath(); + public String getAbsolutePath(); - public String getBundleId(); + public String getBundleId(); } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java index 4a85add5..31f913ba 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java @@ -14,6 +14,6 @@ public interface IResourceExclusionListener { - public void exclusionChanged(ResourceExclusionEvent event); + public void exclusionChanged(ResourceExclusionEvent event); } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java index dfd91df3..fc556c3f 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 @@ -14,71 +14,71 @@ 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; - } + private String projectName; + private String relativePath; + private String absolutePath; + private String bundleId; + + public ResourceDescriptor(IResource resource) { + projectName = resource.getProject().getName(); + relativePath = resource.getProjectRelativePath().toString(); + absolutePath = resource.getRawLocation().toString(); + } + + public ResourceDescriptor() { + } + + @Override + public String getAbsolutePath() { + return absolutePath; + } + + @Override + public String getProjectName() { + return projectName; + } + + @Override + public String getRelativePath() { + return relativePath; + } + + @Override + public int hashCode() { + return projectName.hashCode() + relativePath.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof ResourceDescriptor)) + return false; + + return absolutePath.equals(absolutePath); + } + + @Override + public void setAbsolutePath(String absPath) { + this.absolutePath = absPath; + } + + @Override + public void setProjectName(String projName) { + this.projectName = projName; + } + + @Override + public void setRelativePath(String relPath) { + this.relativePath = relPath; + } + + @Override + public String getBundleId() { + return this.bundleId; + } + + @Override + public void setBundleId(String bundleId) { + this.bundleId = bundleId; + } } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java index 036af55f..5ac24c83 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 @@ -17,55 +17,55 @@ public class SLLocation implements Serializable, ILocation { - private static final long serialVersionUID = 1L; - private IFile file = null; - private int startPos = -1; - private int endPos = -1; - private String literal; - private Serializable data; + private static final long serialVersionUID = 1L; + private IFile file = null; + private int startPos = -1; + private int endPos = -1; + private String literal; + private Serializable data; - public SLLocation(IFile file, int startPos, int endPos, String literal) { - super(); - this.file = file; - this.startPos = startPos; - this.endPos = endPos; - this.literal = literal; - } + public SLLocation(IFile file, int startPos, int endPos, String literal) { + super(); + this.file = file; + this.startPos = startPos; + this.endPos = endPos; + this.literal = literal; + } - public IFile getFile() { - return file; - } + public IFile getFile() { + return file; + } - public void setFile(IFile file) { - this.file = file; - } + public void setFile(IFile file) { + this.file = file; + } - public int getStartPos() { - return startPos; - } + public int getStartPos() { + return startPos; + } - public void setStartPos(int startPos) { - this.startPos = startPos; - } + public void setStartPos(int startPos) { + this.startPos = startPos; + } - public int getEndPos() { - return endPos; - } + public int getEndPos() { + return endPos; + } - public void setEndPos(int endPos) { - this.endPos = endPos; - } + public void setEndPos(int endPos) { + this.endPos = endPos; + } - public String getLiteral() { - return literal; - } + public String getLiteral() { + return literal; + } - public Serializable getData() { - return data; - } + public Serializable getData() { + return data; + } - public void setData(Serializable data) { - this.data = data; - } + public void setData(Serializable data) { + this.data = data; + } } diff --git a/org.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 408fd506..767a7614 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 @@ -12,14 +12,14 @@ public class ResourceBundleException extends Exception { - private static final long serialVersionUID = -2039182473628481126L; + private static final long serialVersionUID = -2039182473628481126L; - public ResourceBundleException(String msg) { - super(msg); - } + public ResourceBundleException(String msg) { + super(msg); + } - public ResourceBundleException() { - super(); - } + 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 index 762687fa..73166a21 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java @@ -21,18 +21,18 @@ */ public interface IStateLoader { - /** - * Loads the state from a xml-file - */ - void loadState(); + /** + * Loads the state from a xml-file + */ + void loadState(); - /** - * Stores the state into a xml-file - */ - void saveState(); + /** + * Stores the state into a xml-file + */ + void saveState(); - /** - * @return The excluded resources - */ - Set<IResourceDescriptor> getExcludedResources(); + /** + * @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 index 17f62868..1196f111 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 @@ -14,43 +14,43 @@ 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; - } + 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/ResourceExclusionEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java index 769d49ad..1230be27 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 @@ -14,19 +14,19 @@ public class ResourceExclusionEvent { - private Collection<Object> changedResources; + private Collection<Object> changedResources; - public ResourceExclusionEvent(Collection<Object> changedResources) { - super(); - this.changedResources = changedResources; - } + public ResourceExclusionEvent(Collection<Object> changedResources) { + super(); + this.changedResources = changedResources; + } - public void setChangedResources(Collection<Object> changedResources) { - this.changedResources = changedResources; - } + public void setChangedResources(Collection<Object> changedResources) { + this.changedResources = changedResources; + } - public Collection<Object> getChangedResources() { - return 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 index 94c1a7a1..3c7b9209 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 @@ -18,36 +18,36 @@ 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"; + /** 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"; + /** 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 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 = ""; + public static String getFormattedMessage(String pattern, Object[] arguments) { + String formattedMessage = ""; - MessageFormat formatter = new MessageFormat(pattern); - formattedMessage = formatter.format(arguments); + MessageFormat formatter = new MessageFormat(pattern); + formattedMessage = formatter.format(arguments); - return formattedMessage; - } + 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]; + 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); + 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; - } + 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 index 491d0872..986bded2 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 @@ -26,36 +26,36 @@ public class FileUtils { public static String readFile(IResource resource) { - return readFileAsString(resource.getRawLocation().toFile()); + return readFileAsString(resource.getRawLocation().toFile()); } protected static String readFileAsString(File filePath) { - String content = ""; + String content = ""; - if (!filePath.exists()) - return content; - try { - BufferedReader fileReader = new BufferedReader(new FileReader( - filePath)); - String line = ""; + if (!filePath.exists()) + return content; + try { + BufferedReader fileReader = new BufferedReader(new FileReader( + filePath)); + String line = ""; - while ((line = fileReader.readLine()) != null) { - content += line + "\n"; - } + while ((line = fileReader.readLine()) != null) { + content += line + "\n"; + } - // close filereader - fileReader.close(); - } catch (Exception e) { - // TODO log error output - Logger.logError(e); - } + // close filereader + fileReader.close(); + } catch (Exception e) { + // TODO log error output + Logger.logError(e); + } - return content; + return content; } public static File getRBManagerStateFile() { - return Activator.getDefault().getStateLocation() - .append("internationalization.xml").toFile(); + return Activator.getDefault().getStateLocation() + .append("internationalization.xml").toFile(); } /** @@ -68,14 +68,14 @@ public static File getRBManagerStateFile() { * @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(); - } + 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 index 8ffcf52e..99c49241 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 @@ -17,28 +17,28 @@ public class FragmentProjectUtils { - public static String getPluginId(IProject project) { - return PDEUtils.getPluginId(project); - } + public static String getPluginId(IProject project) { + return PDEUtils.getPluginId(project); + } - public static IProject[] lookupFragment(IProject pluginProject) { - return PDEUtils.lookupFragment(pluginProject); - } + public static IProject[] lookupFragment(IProject pluginProject) { + return PDEUtils.lookupFragment(pluginProject); + } - public static boolean isFragment(IProject pluginProject) { - return PDEUtils.isFragment(pluginProject); - } + public static boolean isFragment(IProject pluginProject) { + return PDEUtils.isFragment(pluginProject); + } - public static List<IProject> getFragments(IProject hostProject) { - return PDEUtils.getFragments(hostProject); - } + 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 String getFragmentId(IProject project, String hostPluginId) { + return PDEUtils.getFragmentId(project, hostPluginId); + } - public static IProject getFragmentHost(IProject fragment) { - return PDEUtils.getFragmentHost(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/OverlayIcon.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java index e23e07db..56465ce6 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 @@ -17,50 +17,50 @@ 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; + 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; + 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); - } + 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(); + @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; - } - } + 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); - } + @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/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java index f5cfe749..915f70a0 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 @@ -21,16 +21,16 @@ public class RBFileUtils extends Action { * 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; - } + try { + if (r.findMarkers(EditorUtils.RB_MARKER_ID, true, + IResource.DEPTH_INFINITE).length > 0) { + return true; + } else { + return false; + } + } catch (CoreException e) { + return false; + } } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java index a564ecf5..93d84631 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java @@ -29,69 +29,69 @@ public class ConstantStringHover implements IJavaEditorTextHover { @Override public void setEditor(IEditorPart editor) { - this.editor = editor; - initConstantStringAuditor(); + this.editor = editor; + initConstantStringAuditor(); } protected void initConstantStringAuditor() { - // parse editor content and extract resource-bundle access strings + // parse editor content and extract resource-bundle access strings - // get the type of the currently loaded resource - ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor - .getEditorInput()); + // get the type of the currently loaded resource + ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor + .getEditorInput()); - if (typeRoot == null) { - return; - } + if (typeRoot == null) { + return; + } - CompilationUnit cu = ASTutilsUI.getCompilationUnit(typeRoot); + CompilationUnit cu = ASTutilsUI.getCompilationUnit(typeRoot); - if (cu == null) { - return; - } + if (cu == null) { + return; + } - manager = ResourceBundleManager.getManager(cu.getJavaElement() - .getResource().getProject()); + manager = ResourceBundleManager.getManager(cu.getJavaElement() + .getResource().getProject()); - // determine the element at the position of the cursur - csf = new ResourceAuditVisitor(null, manager.getProject().getName()); - cu.accept(csf); + // determine the element at the position of the cursur + csf = new ResourceAuditVisitor(null, manager.getProject().getName()); + cu.accept(csf); } @Override public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - initConstantStringAuditor(); - if (hoverRegion == null) { - return null; - } - - // 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; - } + 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; - } + if (editor == null) { + return null; + } - // Retrieve the property key at this position. Otherwise, null is - // returned. - return csf.getKeyAt(Long.valueOf(offset)); + // Retrieve the property key at this position. Otherwise, null is + // returned. + return csf.getKeyAt(Long.valueOf(offset)); } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java index ac697121..f201c427 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java @@ -43,123 +43,123 @@ public class JavaResourceAuditor extends I18nResourceAuditor { @Override public String[] getFileEndings() { - return new String[] { "java" }; + return new String[] { "java" }; } @Override public void audit(IResource resource) { - ResourceAuditVisitor csav = new ResourceAuditVisitor(resource - .getProject().getFile(resource.getProjectRelativePath()), - resource.getProject().getName()); + 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); + // 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 constant string literals + constantLiterals = csav.getConstantStringLiterals(); - // Report all broken Resource-Bundle references - brokenResourceReferences = csav.getBrokenResourceReferences(); + // Report all broken Resource-Bundle references + brokenResourceReferences = csav.getBrokenResourceReferences(); - // Report all broken definitions to Resource-Bundle references - brokenBundleReferences = csav.getBrokenRBReferences(); + // Report all broken definitions to Resource-Bundle references + brokenBundleReferences = csav.getBrokenRBReferences(); } @Override public List<ILocation> getConstantStringLiterals() { - return new ArrayList<ILocation>(constantLiterals); + return new ArrayList<ILocation>(constantLiterals); } @Override public List<ILocation> getBrokenResourceReferences() { - return new ArrayList<ILocation>(brokenResourceReferences); + return new ArrayList<ILocation>(brokenResourceReferences); } @Override public List<ILocation> getBrokenBundleReferences() { - return new ArrayList<ILocation>(brokenBundleReferences); + return new ArrayList<ILocation>(brokenBundleReferences); } @Override public String getContextId() { - return "java"; + 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; + 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 index ae5b3990..b329f847 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java @@ -43,243 +43,244 @@ 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 (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 (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME - && (tokenEnd + 1) - tokenStart > 0) { - - // Cal10n extension - String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos(manager.getProject().getName(), - cu, tokenOffset-1); - - if (metaData != null) { - completions.add(new KeyRefactoringProposal(tokenOffset, metaData[1], - manager.getProject().getName(), metaData[0], metaData[2])); - } - - return completions; - } - - - 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.toLowerCase())) { - if (!key.equals(fullToken)) { - completions.add(new MessageCompletionProposal( - tokenStart, tokenEnd - tokenStart, key, false)); - } else { - hit = true; - // Refactoring function - completions.add(new KeyRefactoringProposal( - tokenStart, fullToken, manager.getProject().getName(), - bundleName, null)); - } - } - } - 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; - } + 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 (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 (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME + && (tokenEnd + 1) - tokenStart > 0) { + + // Cal10n extension + String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos( + manager.getProject().getName(), cu, tokenOffset - 1); + + if (metaData != null) { + completions.add(new KeyRefactoringProposal(tokenOffset, + metaData[1], manager.getProject().getName(), + metaData[0], metaData[2])); + } + + return completions; + } + + 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.toLowerCase())) { + if (!key.equals(fullToken)) { + completions.add(new MessageCompletionProposal( + tokenStart, tokenEnd - tokenStart, key, false)); + } else { + hit = true; + // Refactoring function + completions.add(new KeyRefactoringProposal(tokenStart, + fullToken, manager.getProject().getName(), + bundleName, null)); + } + } + } + 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 index 72fe63e4..c9b41629 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java @@ -48,184 +48,184 @@ public class CreateResourceBundleProposal implements IJavaCompletionProposal { 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; + 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 + "'"; + return "Creates a new Resource-Bundle with the id '" + key + "'"; } public String getLabel() { - return "Create Resource-Bundle '" + key + "'"; + 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) { - } + // 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(); + this.runAction(); } @Override public String getAdditionalProposalInfo() { - return getDescription(); + return getDescription(); } @Override public IContextInformation getContextInformation() { - return null; + return null; } @Override public String getDisplayString() { - return getLabel(); + return getLabel(); } @Override public Point getSelection(IDocument document) { - return null; + return null; } @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 int getRelevance() { - // TODO Auto-generated method stub - if (end - start == 0) { - return 99; - } else { - return 1099; - } + // TODO Auto-generated method stub + if (end - start == 0) { + return 99; + } else { + return 1099; + } } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java index 066271c7..886847a6 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java @@ -27,7 +27,7 @@ import org.eclipse.ui.PlatformUI; public class InsertResourceBundleReferenceProposal implements - IJavaCompletionProposal { + IJavaCompletionProposal { private int offset = 0; private int length = 0; @@ -36,69 +36,69 @@ public class InsertResourceBundleReferenceProposal implements 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; + 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); + ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( + Display.getDefault().getActiveShell()); + dialog.setProjectName(projectName); - if (dialog.open() != InputDialog.OK) { - return; - } + if (dialog.open() != InputDialog.OK) { + return; + } - String resourceBundleId = dialog.getSelectedResourceBundle(); - String key = dialog.getSelectedResource(); - Locale locale = dialog.getSelectedLocale(); + String resourceBundleId = dialog.getSelectedResourceBundle(); + String key = dialog.getSelectedResource(); + Locale locale = dialog.getSelectedLocale(); - reference = ASTutilsUI.insertExistingBundleRef(document, resource, - offset, length, resourceBundleId, key, locale); + reference = ASTutilsUI.insertExistingBundleRef(document, resource, + offset, length, resourceBundleId, key, locale); } @Override public String getAdditionalProposalInfo() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public IContextInformation getContextInformation() { - return null; + return null; } @Override public String getDisplayString() { - return "Insert reference to a localized string literal"; + return "Insert reference to a localized string literal"; } @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 - int referenceLength = reference == null ? 0 : reference.length(); - return new Point(offset + referenceLength, 0); + // 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; - } + // 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/KeyRefactoringProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/KeyRefactoringProposal.java index b331ea39..0549e4b9 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/KeyRefactoringProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/KeyRefactoringProposal.java @@ -20,115 +20,128 @@ import org.eclipse.swt.graphics.Point; /** - * Proposal for the key refactoring. The gets triggerd if you press - * Ctrl + Shift + Space on an externalized (!) {@link String} or - * on an externalized (!) enum! The key must be registered in the system! + * Proposal for the key refactoring. The gets triggerd if you press Ctrl + Shift + * + Space on an externalized (!) {@link String} or on an externalized (!) enum! + * The key must be registered in the system! * * @author Alexej Strelzow */ public class KeyRefactoringProposal implements IJavaCompletionProposal { - private int startPos; - private String value; - private String projectName; - private String bundleName; - private String reference; - private String enumPath; + private int startPos; + private String value; + private String projectName; + private String bundleName; + private String reference; + private String enumPath; - /** - * Constructor for non Cal10n refactoring. - * @param startPos The starting position of the Ctrl + Shift + Space command. - * @param value The value of the key to refactor. - * @param projectName The project the resource bundle is in. - * @param bundleName The resource bundle, which contains the key to be refactored. - */ - public KeyRefactoringProposal(int startPos, - String value, String projectName, String bundleName) { + /** + * Constructor for non Cal10n refactoring. + * + * @param startPos + * The starting position of the Ctrl + Shift + Space command. + * @param value + * The value of the key to refactor. + * @param projectName + * The project the resource bundle is in. + * @param bundleName + * The resource bundle, which contains the key to be refactored. + */ + public KeyRefactoringProposal(int startPos, String value, + String projectName, String bundleName) { - this.startPos = startPos; - this.value = value; - this.projectName = projectName; - this.bundleName = bundleName; - } - - /** - * Constructor for Cal10n refactoring. - * @param startPos The starting position of the Ctrl + Shift + Space command. - * @param value The value of the key to refactor. - * @param projectName The project the resource bundle is in. - * @param bundleName The resource bundle, which contains the key to be refactored. - * @param enumPath The {@link IPath#toPortableString()} of the enum to change - */ - public KeyRefactoringProposal(int startPos, - String value, String projectName, String bundleName, String enumPath) { - this(startPos, value, projectName, bundleName); - this.enumPath = enumPath; // relative path (to the project) - } - - /** - * {@inheritDoc} - */ - @Override - public void apply(IDocument document) { - RBManager.getRefactorService().openRefactorDialog(projectName, bundleName, value, enumPath); - } + this.startPos = startPos; + this.value = value; + this.projectName = projectName; + this.bundleName = bundleName; + } - /** - * {@inheritDoc} - */ - @Override - public Point getSelection(IDocument document) { - int refLength = reference == null ? 0 : reference.length() - 1; - return new Point(startPos + refLength, 0); - } + /** + * Constructor for Cal10n refactoring. + * + * @param startPos + * The starting position of the Ctrl + Shift + Space command. + * @param value + * The value of the key to refactor. + * @param projectName + * The project the resource bundle is in. + * @param bundleName + * The resource bundle, which contains the key to be refactored. + * @param enumPath + * The {@link IPath#toPortableString()} of the enum to change + */ + public KeyRefactoringProposal(int startPos, String value, + String projectName, String bundleName, String enumPath) { + this(startPos, value, projectName, bundleName); + this.enumPath = enumPath; // relative path (to the project) + } - /** - * {@inheritDoc} - */ - @Override - public String getAdditionalProposalInfo() { - - if (enumPath != null) { - return "Replace this enum key with a new one! \r\n" + - "This operation will automatically replace all references to the selected key " + - "with the new one. Also the enum value will be changed!"; - } else { - return "Replace this key with a new one! \r\n" + - "This operation will automatically replace all references to the selected key " + - "with the new one."; - } - } + /** + * {@inheritDoc} + */ + @Override + public void apply(IDocument document) { + RBManager.getRefactorService().openRefactorDialog(projectName, + bundleName, value, enumPath); + } - /** - * {@inheritDoc} - */ - @Override - public String getDisplayString() { - return "Refactor this key..."; - } + /** + * {@inheritDoc} + */ + @Override + public Point getSelection(IDocument document) { + int refLength = reference == null ? 0 : reference.length() - 1; + return new Point(startPos + refLength, 0); + } - /** - * {@inheritDoc} - */ - @Override - public Image getImage() { - return UIUtils.getImageDescriptor(UIUtils.IMAGE_REFACTORING).createImage(); - } + /** + * {@inheritDoc} + */ + @Override + public String getAdditionalProposalInfo() { - /** - * {@inheritDoc} - */ - @Override - public IContextInformation getContextInformation() { - return null; - } + if (enumPath != null) { + return "Replace this enum key with a new one! \r\n" + + "This operation will automatically replace all references to the selected key " + + "with the new one. Also the enum value will be changed!"; + } else { + return "Replace this key with a new one! \r\n" + + "This operation will automatically replace all references to the selected key " + + "with the new one."; + } + } - /** - * {@inheritDoc} - */ - @Override - public int getRelevance() { - return 100; - } + /** + * {@inheritDoc} + */ + @Override + public String getDisplayString() { + return "Refactor this key..."; + } + + /** + * {@inheritDoc} + */ + @Override + public Image getImage() { + return UIUtils.getImageDescriptor(UIUtils.IMAGE_REFACTORING) + .createImage(); + } + + /** + * {@inheritDoc} + */ + @Override + public IContextInformation getContextInformation() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public int getRelevance() { + return 100; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java index a56d19c3..6d5d3939 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java @@ -26,52 +26,52 @@ public class MessageCompletionProposal implements IJavaCompletionProposal { 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; + 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); - } + try { + document.replace(offset, length, content); + } catch (Exception e) { + Logger.logError(e); + } } @Override public String getAdditionalProposalInfo() { - return "Inserts the resource key '" + this.content + "'"; + return "Inserts the resource key '" + this.content + "'"; } @Override public IContextInformation getContextInformation() { - return null; + return null; } @Override public String getDisplayString() { - return content; + return content; } @Override public Image getImage() { - if (messageAccessor) - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE); + 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); + return new Point(offset + content.length() + 1, 0); } @Override public int getRelevance() { - return 99; + return 99; } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java index 6960fa36..8a68647c 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 @@ -38,104 +38,104 @@ public class NewResourceBundleEntryProposal implements IJavaCompletionProposal { 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; + 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); - } + 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 ""; - } + 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; + 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; + 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(); + 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); + 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; - } + if (this.value.trim().length() == 0) { + return 96; + } else { + return 1096; + } } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java index 1af9bca7..f6a6ec5b 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java @@ -19,49 +19,49 @@ public class NoActionProposal implements IJavaCompletionProposal { public NoActionProposal() { - super(); + super(); } @Override public void apply(IDocument document) { - // TODO Auto-generated method stub + // TODO Auto-generated method stub } @Override public String getAdditionalProposalInfo() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public IContextInformation getContextInformation() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public String getDisplayString() { - // TODO Auto-generated method stub - return "No Default Proposals"; + // TODO Auto-generated method stub + return "No Default Proposals"; } @Override public Image getImage() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public Point getSelection(IDocument document) { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public int getRelevance() { - // TODO Auto-generated method stub - return 100; + // TODO Auto-generated method stub + return 100; } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java index 4c35d723..a49665f6 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java @@ -21,27 +21,27 @@ public Sorter() { @Override public void beginSorting(ContentAssistInvocationContext context) { - // TODO Auto-generated method stub - super.beginSorting(context); + // TODO Auto-generated method stub + super.beginSorting(context); } @Override public int compare(ICompletionProposal prop1, ICompletionProposal prop2) { - return getIndex(prop1) - getIndex(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; - } + if (prop instanceof NoActionProposal) { + return 1; + } else if (prop instanceof MessageCompletionProposal) { + return 2; + } else if (prop instanceof InsertResourceBundleReferenceProposal) { + return 3; + } else if (prop instanceof NewResourceBundleEntryProposal) { + return 4; + } else { + return 0; + } } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java index 3e2ddc97..23d86fee 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java @@ -25,52 +25,52 @@ public class SLLocation implements Serializable, ILocation { 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; + super(); + this.file = file; + this.startPos = startPos; + this.endPos = endPos; + this.literal = literal; } @Override public IFile getFile() { - return file; + return file; } public void setFile(IFile file) { - this.file = file; + this.file = file; } @Override public int getStartPos() { - return startPos; + return startPos; } public void setStartPos(int startPos) { - this.startPos = startPos; + this.startPos = startPos; } @Override public int getEndPos() { - return endPos; + return endPos; } public void setEndPos(int endPos) { - this.endPos = endPos; + this.endPos = endPos; } @Override public String getLiteral() { - return literal; + return literal; } @Override public Serializable getData() { - return data; + return data; } public void setData(Serializable data) { - this.data = data; + this.data = data; } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java index 75e71b8c..54f8a000 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java @@ -22,48 +22,48 @@ import org.eclipse.ui.progress.IProgressService; public class ExcludeResourceFromInternationalization implements - IMarkerResolution2 { + IMarkerResolution2 { @Override public String getLabel() { - return "Exclude Resource"; + return "Exclude Resource"; } @Override public void run(IMarker marker) { - final IResource resource = marker.getResource(); + final IResource resource = marker.getResource(); - IWorkbench wb = PlatformUI.getWorkbench(); - IProgressService ps = wb.getProgressService(); - try { - ps.busyCursorWhile(new IRunnableWithProgress() { - public void run(IProgressMonitor pm) { + IWorkbench wb = PlatformUI.getWorkbench(); + IProgressService ps = wb.getProgressService(); + try { + ps.busyCursorWhile(new IRunnableWithProgress() { + public void run(IProgressMonitor pm) { - ResourceBundleManager manager = null; - pm.beginTask( - "Excluding Resource from Internationalization", 1); + ResourceBundleManager manager = null; + pm.beginTask( + "Excluding Resource from Internationalization", 1); - if (manager == null - || (manager.getProject() != resource.getProject())) - manager = ResourceBundleManager.getManager(resource - .getProject()); - manager.excludeResource(resource, pm); - pm.worked(1); - pm.done(); - } - }); - } catch (Exception e) { - } + if (manager == null + || (manager.getProject() != resource.getProject())) + manager = ResourceBundleManager.getManager(resource + .getProject()); + manager.excludeResource(resource, pm); + pm.worked(1); + pm.done(); + } + }); + } catch (Exception e) { + } } @Override public String getDescription() { - return "Exclude Resource from Internationalization"; + return "Exclude Resource from Internationalization"; } @Override public Image getImage() { - return null; + return null; } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java index fc3a130b..bcceaed9 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java @@ -34,66 +34,66 @@ public ExportToResourceBundleResolution() { @Override public String getDescription() { - return "Export constant string literal to a resource bundle."; + return "Export constant string literal to a resource bundle."; } @Override public Image getImage() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } @Override public String getLabel() { - return "Export to Resource-Bundle"; + 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.setPreselectedMessage((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(); - } - } + 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.setPreselectedMessage((startPos + 1 < document.getLength() && endPos > 1) ? document + .get(startPos + 1, endPos - 2) : ""); + config.setPreselectedLocale(""); + config.setProjectName(resource.getProject().getName()); + + dialog.setDialogConfiguration(config); + + if (dialog.open() != InputDialog.OK) + return; + + ASTutilsUI + .insertNewBundleRef(document, resource, startPos, endPos, + dialog.getSelectedResourceBundle(), + dialog.getSelectedKey()); + + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + e.printStackTrace(); + } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java index ce3b10b1..67429aa1 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java @@ -31,48 +31,48 @@ public class IgnoreStringFromInternationalization implements IMarkerResolution2 @Override public String getLabel() { - return "Ignore String"; + return "Ignore String"; } @Override public void run(IMarker marker) { - IResource resource = marker.getResource(); + IResource resource = marker.getResource(); - CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource); + CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource); - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); + 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(); + 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); + int position = marker.getAttribute(IMarker.CHAR_START, 0); - ASTutils.createReplaceNonInternationalisationComment(cu, document, - position); - textFileBuffer.commit(null, false); + ASTutils.createReplaceNonInternationalisationComment(cu, document, + position); + textFileBuffer.commit(null, false); - } catch (JavaModelException e) { - Logger.logError(e); - } catch (CoreException e) { - Logger.logError(e); - } + } catch (JavaModelException e) { + Logger.logError(e); + } catch (CoreException e) { + Logger.logError(e); + } } @Override public String getDescription() { - return "Ignore String from Internationalization"; + return "Ignore String from Internationalization"; } @Override public Image getImage() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java index 2fa6cfc7..162ad5cd 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java @@ -32,66 +32,66 @@ public class ReplaceResourceBundleDefReference implements IMarkerResolution2 { private int end; public ReplaceResourceBundleDefReference(String key, int start, int end) { - this.key = key; - this.start = start; - this.end = 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."; + 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; + // TODO Auto-generated method stub + return null; } @Override public String getLabel() { - return "Select an alternative Resource-Bundle"; + return "Select an alternative Resource-Bundle"; } @Override public void run(IMarker marker) { - int startPos = start; - int endPos = end - start; - IResource resource = marker.getResource(); + int startPos = start; + int endPos = end - start; + IResource resource = marker.getResource(); - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( - path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, LocationKind.NORMALIZE, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( + path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); - ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog( - Display.getDefault().getActiveShell(), - resource.getProject()); + ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog( + Display.getDefault().getActiveShell(), + resource.getProject()); - if (dialog.open() != InputDialog.OK) - return; + if (dialog.open() != InputDialog.OK) + return; - key = dialog.getSelectedBundleId(); - int iSep = key.lastIndexOf("/"); - key = iSep != -1 ? key.substring(iSep + 1) : key; + key = dialog.getSelectedBundleId(); + int iSep = key.lastIndexOf("/"); + key = iSep != -1 ? key.substring(iSep + 1) : key; - document.replace(startPos, endPos, "\"" + key + "\""); + document.replace(startPos, endPos, "\"" + key + "\""); - textFileBuffer.commit(null, false); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - bufferManager.disconnect(path, LocationKind.NORMALIZE, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, LocationKind.NORMALIZE, null); + } catch (CoreException e) { + e.printStackTrace(); + } + } } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java index f0eaedc3..a959b54c 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java @@ -33,66 +33,66 @@ public class ReplaceResourceBundleReference implements IMarkerResolution2 { private String bundleId; public ReplaceResourceBundleReference(String key, String bundleId) { - this.key = key; - this.bundleId = 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."; + 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; + return null; } @Override public String getLabel() { - return "Select alternative Resource-Bundle entry"; + 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(); - } - } + 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/refactoring/Cal10nEnumRefactoringVisitor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nEnumRefactoringVisitor.java index 1c2453b5..ec4a573e 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nEnumRefactoringVisitor.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nEnumRefactoringVisitor.java @@ -24,69 +24,78 @@ import org.eclipse.text.edits.TextEdit; /** - * Changes the enum class, which is referenced by the Cal10n framework. - * It replaces the old key with the new one. + * Changes the enum class, which is referenced by the Cal10n framework. It + * replaces the old key with the new one. * * @author Alexej Strelzow */ public class Cal10nEnumRefactoringVisitor extends ASTVisitor { - private List<String> changeSet = new ArrayList<String>(); - - private String oldKey; - private String newKey; - private CompilationUnit enumCu; - - /** - * Constructor. - * @param oldKey The old key name - * @param newKey The new key name, which should overwrite the old one - * @param enumCu The {@link CompilationUnit} to modify - * @param changeSet The set of changes (protocol) - */ - public Cal10nEnumRefactoringVisitor(CompilationUnit enumCu, - String oldKey, String newKey, List<String> changeSet) { - this.oldKey = oldKey; - this.newKey = newKey; - this.enumCu = enumCu; - this.changeSet = changeSet; - } - - /** - * Modifies the enum file. It replaces the old key with the new one. - */ - public boolean visit(EnumConstantDeclaration node) { - - if (node.resolveVariable().getName().equals(oldKey)) { - - // ASTRewrite - AST ast = enumCu.getAST(); - ASTRewrite rewriter = ASTRewrite.create(ast); - - EnumConstantDeclaration newDeclaration = ast.newEnumConstantDeclaration(); - + private List<String> changeSet = new ArrayList<String>(); + + private String oldKey; + private String newKey; + private CompilationUnit enumCu; + + /** + * Constructor. + * + * @param oldKey + * The old key name + * @param newKey + * The new key name, which should overwrite the old one + * @param enumCu + * The {@link CompilationUnit} to modify + * @param changeSet + * The set of changes (protocol) + */ + public Cal10nEnumRefactoringVisitor(CompilationUnit enumCu, String oldKey, + String newKey, List<String> changeSet) { + this.oldKey = oldKey; + this.newKey = newKey; + this.enumCu = enumCu; + this.changeSet = changeSet; + } + + /** + * Modifies the enum file. It replaces the old key with the new one. + */ + public boolean visit(EnumConstantDeclaration node) { + + if (node.resolveVariable().getName().equals(oldKey)) { + + // ASTRewrite + AST ast = enumCu.getAST(); + ASTRewrite rewriter = ASTRewrite.create(ast); + + EnumConstantDeclaration newDeclaration = ast + .newEnumConstantDeclaration(); + SimpleName newSimpleName = ast.newSimpleName(newKey); newDeclaration.setName(newSimpleName); - + rewriter.replace(node, newDeclaration, null); - + try { TextEdit textEdit = rewriter.rewriteAST(); - if (textEdit.hasChildren()) { // if the compilation unit has been + if (textEdit.hasChildren()) { // if the compilation unit has + // been // changed - ICompilationUnit icu = (ICompilationUnit) enumCu.getJavaElement(); + ICompilationUnit icu = (ICompilationUnit) enumCu + .getJavaElement(); icu.applyTextEdit(textEdit, null); icu.getBuffer().save(null, true); - + // protocol int startPos = node.getStartPosition(); - changeSet.add(icu.getPath().toPortableString() + ": line " + enumCu.getLineNumber(startPos)); + changeSet.add(icu.getPath().toPortableString() + ": line " + + enumCu.getLineNumber(startPos)); } } catch (Exception e) { - Logger.logError(e); + Logger.logError(e); } - } - - return false; - }; + } + + return false; + }; } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nRefactoringVisitor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nRefactoringVisitor.java index 1ead32ac..ec1ea6f5 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nRefactoringVisitor.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nRefactoringVisitor.java @@ -27,91 +27,105 @@ import org.eclipse.text.edits.TextEdit; /** - * Refactors java files, which are using the old enumeration key - * that gets refactored. + * Refactors java files, which are using the old enumeration key that gets + * refactored. * * @author Alexej Strelzow */ public class Cal10nRefactoringVisitor extends ASTVisitor { - - private List<String> changeSet = new ArrayList<String>(); - - private String oldKey; - private String newKey; - private String enumPath; - - private CompilationUnit cu; - private AST ast; - private ASTRewrite rewriter; - - /** - * Constructor. - * @param oldKey The old key name - * @param newKey The new key name, which should overwrite the old one - * @param enumPath The path of the enum file to change - * @param cu The {@link CompilationUnit} to modify - * @param changeSet The set of changes (protocol) - */ - public Cal10nRefactoringVisitor(CompilationUnit cu, - String oldKey, String newKey, String enumPath, List<String> changeSet) { - this.oldKey = oldKey; - this.newKey = newKey; - this.enumPath = enumPath; - this.cu = cu; - this.changeSet = changeSet; - this.ast = cu.getAST(); - this.rewriter = ASTRewrite.create(ast); - } - - /** - * Changes the argument of the IMessageConveyor#getMessage(...) call. - * The new enum key replaces the old one. - */ - @SuppressWarnings("unchecked") - public boolean visit(MethodInvocation node) { - - boolean isCal10nCall = "ch.qos.cal10n.IMessageConveyor".equals(node.resolveMethodBinding().getDeclaringClass().getQualifiedName()); - - if (!isCal10nCall) { - if (node.arguments().size() == 0) { - return false; - } else { - return true; // because the Cal10n call may be an argument! - } - } else { - QualifiedName qName = (QualifiedName) node.arguments().get(0); - String fullPath = qName.resolveTypeBinding().getJavaElement().getResource().getFullPath().toPortableString(); - if (fullPath.equals(enumPath) && qName.getName().toString().equals(oldKey)) { - - // ASTRewrite - Expression exp = (Expression) rewriter.createCopyTarget(node.getExpression()); - + + private List<String> changeSet = new ArrayList<String>(); + + private String oldKey; + private String newKey; + private String enumPath; + + private CompilationUnit cu; + private AST ast; + private ASTRewrite rewriter; + + /** + * Constructor. + * + * @param oldKey + * The old key name + * @param newKey + * The new key name, which should overwrite the old one + * @param enumPath + * The path of the enum file to change + * @param cu + * The {@link CompilationUnit} to modify + * @param changeSet + * The set of changes (protocol) + */ + public Cal10nRefactoringVisitor(CompilationUnit cu, String oldKey, + String newKey, String enumPath, List<String> changeSet) { + this.oldKey = oldKey; + this.newKey = newKey; + this.enumPath = enumPath; + this.cu = cu; + this.changeSet = changeSet; + this.ast = cu.getAST(); + this.rewriter = ASTRewrite.create(ast); + } + + /** + * Changes the argument of the IMessageConveyor#getMessage(...) call. The + * new enum key replaces the old one. + */ + @SuppressWarnings("unchecked") + public boolean visit(MethodInvocation node) { + + boolean isCal10nCall = "ch.qos.cal10n.IMessageConveyor".equals(node + .resolveMethodBinding().getDeclaringClass().getQualifiedName()); + + if (!isCal10nCall) { + if (node.arguments().size() == 0) { + return false; + } else { + return true; // because the Cal10n call may be an argument! + } + } else { + QualifiedName qName = (QualifiedName) node.arguments().get(0); + String fullPath = qName.resolveTypeBinding().getJavaElement() + .getResource().getFullPath().toPortableString(); + if (fullPath.equals(enumPath) + && qName.getName().toString().equals(oldKey)) { + + // ASTRewrite + Expression exp = (Expression) rewriter.createCopyTarget(node + .getExpression()); + MethodInvocation newMethod = ast.newMethodInvocation(); newMethod.setExpression(exp); - newMethod.setName(ast.newSimpleName(node.getName().getIdentifier())); - + newMethod.setName(ast.newSimpleName(node.getName() + .getIdentifier())); + SimpleName newSimpleName = ast.newSimpleName(newKey); - Name newName = ast.newName(qName.getQualifier().getFullyQualifiedName()); - QualifiedName newQualifiedName = ast.newQualifiedName(newName, newSimpleName); - + Name newName = ast.newName(qName.getQualifier() + .getFullyQualifiedName()); + QualifiedName newQualifiedName = ast.newQualifiedName(newName, + newSimpleName); + newMethod.arguments().add(newQualifiedName); rewriter.replace(node, newMethod, null); - + // protocol int startPos = node.getStartPosition(); ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); - changeSet.add(icu.getPath().toPortableString() + ": line " + cu.getLineNumber(startPos)); - } - } - - return false; - } - - /** - * Saves the changes, which were made in {@link #visit(MethodInvocation)} - */ - public void saveChanges() { - try { + changeSet.add(icu.getPath().toPortableString() + ": line " + + cu.getLineNumber(startPos)); + } + } + + return false; + } + + /** + * Saves the changes, which were made in {@link #visit(MethodInvocation)} + */ + public void saveChanges() { + try { TextEdit textEdit = rewriter.rewriteAST(); if (textEdit.hasChildren()) { // if the compilation unit has been // changed @@ -120,7 +134,7 @@ public void saveChanges() { icu.getBuffer().save(null, true); } } catch (Exception e) { - Logger.logError(e); + Logger.logError(e); } - } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/PrimitiveRefactoringVisitor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/PrimitiveRefactoringVisitor.java index 83137a88..e6d5762f 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/PrimitiveRefactoringVisitor.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/PrimitiveRefactoringVisitor.java @@ -36,173 +36,190 @@ * @author Alexej Strelzow */ public class PrimitiveRefactoringVisitor extends ASTVisitor { - - private String varNameOfBundle; // name of the variable, which references the resource bundle - private List<String> changeSet = new ArrayList<String>(); - - private String oldKey; - private String newKey; - private String resourceBundleId; - - private CompilationUnit cu; - private AST ast; - private ASTRewrite rewriter; - - /** - * Constructor. - * @param cu The {@link CompilationUnit} to modify - * @param resourceBundleId The Id of the resource bundle to change - * @param oldKey The old key name - * @param newKey The new key name, which should overwrite the old one - * @param changeSet The set of changes (protocol) - */ - public PrimitiveRefactoringVisitor(CompilationUnit cu, String resourceBundleId, - String oldKey, String newKey, List<String> changeSet) { - this.oldKey = oldKey; - this.newKey = newKey; - this.resourceBundleId = resourceBundleId; - this.cu = cu; - this.changeSet = changeSet; - this.ast = cu.getAST(); - this.rewriter = ASTRewrite.create(ast); - } - - /** - * GLOBAL VARS:<br> - * <br> - * Find the variable name of the bundle (if exists!) - * E.g.: - * <pre> - * static ResourceBundle applicationresourcesref = ResourceBundle - * .getBundle("dev.ApplicationResources"); - * </pre> - * - * {@inheritDoc} - */ - @Override - public boolean visit(FieldDeclaration node) { - for (Object obj : node.fragments()) { - String val = getVarNameOfBundle((VariableDeclarationFragment) obj, resourceBundleId); - - if (val != null) { - varNameOfBundle = val; - } - } - return false; - } - - /** - * LOCAL VARS: <br> - * <br> - * Find the variable name of the bundle (if exists!) - * E.g.: - * <pre> - * ResourceBundle applicationresourcesref = ResourceBundle - * .getBundle("dev.ApplicationResources"); - * </pre> - * - * {@inheritDoc} - */ - @SuppressWarnings("rawtypes") - @Override - public boolean visit(VariableDeclarationStatement node) { - for (Object obj : node.fragments()) { - String val = getVarNameOfBundle((VariableDeclarationFragment) obj, resourceBundleId); - - if (val != null) { - varNameOfBundle = val; - } - - // [alst] because visit(MethodInvocation node) does not work when the MethodInvocation is embedded - // in an Initializer (I don't know why...) - if (!node.fragments().isEmpty()) { - List fragments = node.fragments(); - ListIterator listIterator = fragments.listIterator(); - while (listIterator.hasNext()) { - Object element = listIterator.next(); - if (element instanceof VariableDeclarationFragment) { - VariableDeclarationFragment fragment = (VariableDeclarationFragment) element; - Expression initializer = fragment.getInitializer(); - if (initializer != null && initializer instanceof MethodInvocation) { - visit((MethodInvocation)initializer); - } - } - } - } - - } - return false; - } - - @Override - public boolean visit(StringLiteral node) { - // TODO Auto-generated method stub - return super.visit(node); - } - - /** - * Searches for the {@link MethodInvocation}, which needs to be modified. - * It gets only executed, if the variable name of the resource bundle has been - * found. E.g. applicationresourcesref: - * <pre> - * ResourceBundle applicationresourcesref = ResourceBundle - * .getBundle("dev.ApplicationResources"); - * </pre> - */ - @SuppressWarnings("unchecked") - @Override - public boolean visit(MethodInvocation node) { - if (varNameOfBundle == null) { - return false; - } - - boolean isResourceBundle = "java.util.ResourceBundle".equals( - node.resolveMethodBinding().getDeclaringClass().getQualifiedName()); - - if (!isResourceBundle) { - if (node.arguments().size() == 0) { - return false; - } else { - return true; // because the call (we are searching for) may be an argument! - } - } else { - // check the name of the caller, is it our resource bundle? - if (node.getExpression() instanceof SimpleName - && varNameOfBundle.equals( - node.getExpression().toString())) { - - // is the parameter the old key? - StringLiteral literal = (StringLiteral) node.arguments().get(0); - - if (oldKey.equals(literal.getLiteralValue())) { - - // ASTRewrite - Expression exp = (Expression) rewriter.createCopyTarget(node.getExpression()); - - MethodInvocation newMethod = ast.newMethodInvocation(); - newMethod.setExpression(exp); - newMethod.setName(ast.newSimpleName(node.getName().getIdentifier())); - - StringLiteral newStringLiteral = ast.newStringLiteral(); - newStringLiteral.setLiteralValue(newKey); - newMethod.arguments().add(newStringLiteral); - rewriter.replace(node, newMethod, null); - - // protocol - int startPos = node.getStartPosition(); - ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); - changeSet.add(icu.getPath().toPortableString() + ": line " + cu.getLineNumber(startPos)); - } - } - } - return false; - } - - /** - * Saves the changes, which were made in {@link #visit(MethodInvocation)} - */ - public void saveChanges() { - try { + + private String varNameOfBundle; // name of the variable, which references + // the resource bundle + private List<String> changeSet = new ArrayList<String>(); + + private String oldKey; + private String newKey; + private String resourceBundleId; + + private CompilationUnit cu; + private AST ast; + private ASTRewrite rewriter; + + /** + * Constructor. + * + * @param cu + * The {@link CompilationUnit} to modify + * @param resourceBundleId + * The Id of the resource bundle to change + * @param oldKey + * The old key name + * @param newKey + * The new key name, which should overwrite the old one + * @param changeSet + * The set of changes (protocol) + */ + public PrimitiveRefactoringVisitor(CompilationUnit cu, + String resourceBundleId, String oldKey, String newKey, + List<String> changeSet) { + this.oldKey = oldKey; + this.newKey = newKey; + this.resourceBundleId = resourceBundleId; + this.cu = cu; + this.changeSet = changeSet; + this.ast = cu.getAST(); + this.rewriter = ASTRewrite.create(ast); + } + + /** + * GLOBAL VARS:<br> + * <br> + * Find the variable name of the bundle (if exists!) E.g.: + * + * <pre> + * static ResourceBundle applicationresourcesref = ResourceBundle + * .getBundle(&quot;dev.ApplicationResources&quot;); + * </pre> + * + * {@inheritDoc} + */ + @Override + public boolean visit(FieldDeclaration node) { + for (Object obj : node.fragments()) { + String val = getVarNameOfBundle((VariableDeclarationFragment) obj, + resourceBundleId); + + if (val != null) { + varNameOfBundle = val; + } + } + return false; + } + + /** + * LOCAL VARS: <br> + * <br> + * Find the variable name of the bundle (if exists!) E.g.: + * + * <pre> + * ResourceBundle applicationresourcesref = ResourceBundle + * .getBundle(&quot;dev.ApplicationResources&quot;); + * </pre> + * + * {@inheritDoc} + */ + @SuppressWarnings("rawtypes") + @Override + public boolean visit(VariableDeclarationStatement node) { + for (Object obj : node.fragments()) { + String val = getVarNameOfBundle((VariableDeclarationFragment) obj, + resourceBundleId); + + if (val != null) { + varNameOfBundle = val; + } + + // [alst] because visit(MethodInvocation node) does not work when + // the MethodInvocation is embedded + // in an Initializer (I don't know why...) + if (!node.fragments().isEmpty()) { + List fragments = node.fragments(); + ListIterator listIterator = fragments.listIterator(); + while (listIterator.hasNext()) { + Object element = listIterator.next(); + if (element instanceof VariableDeclarationFragment) { + VariableDeclarationFragment fragment = (VariableDeclarationFragment) element; + Expression initializer = fragment.getInitializer(); + if (initializer != null + && initializer instanceof MethodInvocation) { + visit((MethodInvocation) initializer); + } + } + } + } + + } + return false; + } + + @Override + public boolean visit(StringLiteral node) { + // TODO Auto-generated method stub + return super.visit(node); + } + + /** + * Searches for the {@link MethodInvocation}, which needs to be modified. It + * gets only executed, if the variable name of the resource bundle has been + * found. E.g. applicationresourcesref: + * + * <pre> + * ResourceBundle applicationresourcesref = ResourceBundle + * .getBundle(&quot;dev.ApplicationResources&quot;); + * </pre> + */ + @SuppressWarnings("unchecked") + @Override + public boolean visit(MethodInvocation node) { + if (varNameOfBundle == null) { + return false; + } + + boolean isResourceBundle = "java.util.ResourceBundle".equals(node + .resolveMethodBinding().getDeclaringClass().getQualifiedName()); + + if (!isResourceBundle) { + if (node.arguments().size() == 0) { + return false; + } else { + return true; // because the call (we are searching for) may be + // an argument! + } + } else { + // check the name of the caller, is it our resource bundle? + if (node.getExpression() instanceof SimpleName + && varNameOfBundle.equals(node.getExpression().toString())) { + + // is the parameter the old key? + StringLiteral literal = (StringLiteral) node.arguments().get(0); + + if (oldKey.equals(literal.getLiteralValue())) { + + // ASTRewrite + Expression exp = (Expression) rewriter + .createCopyTarget(node.getExpression()); + + MethodInvocation newMethod = ast.newMethodInvocation(); + newMethod.setExpression(exp); + newMethod.setName(ast.newSimpleName(node.getName() + .getIdentifier())); + + StringLiteral newStringLiteral = ast.newStringLiteral(); + newStringLiteral.setLiteralValue(newKey); + newMethod.arguments().add(newStringLiteral); + rewriter.replace(node, newMethod, null); + + // protocol + int startPos = node.getStartPosition(); + ICompilationUnit icu = (ICompilationUnit) cu + .getJavaElement(); + changeSet.add(icu.getPath().toPortableString() + ": line " + + cu.getLineNumber(startPos)); + } + } + } + return false; + } + + /** + * Saves the changes, which were made in {@link #visit(MethodInvocation)} + */ + public void saveChanges() { + try { TextEdit textEdit = rewriter.rewriteAST(); if (textEdit.hasChildren()) { // if the compilation unit has been // changed @@ -211,25 +228,28 @@ public void saveChanges() { icu.getBuffer().save(null, true); } } catch (Exception e) { - Logger.logError(e); + Logger.logError(e); } - } - - private static String getVarNameOfBundle(VariableDeclarationFragment vdf, String resourceBundleId) { - - // Is the referenced bundle in there? - if (vdf.getInitializer() != null && vdf.getInitializer() instanceof MethodInvocation) { - MethodInvocation method = (MethodInvocation)vdf.getInitializer(); - - // what's the name of the variable of the target res. bundle? - for (Object arg : method.arguments()) { - if (arg instanceof StringLiteral - && resourceBundleId.equals(((StringLiteral)arg).getLiteralValue())) { - return vdf.getName().toString(); - } - } - } - - return null; - } + } + + private static String getVarNameOfBundle(VariableDeclarationFragment vdf, + String resourceBundleId) { + + // Is the referenced bundle in there? + if (vdf.getInitializer() != null + && vdf.getInitializer() instanceof MethodInvocation) { + MethodInvocation method = (MethodInvocation) vdf.getInitializer(); + + // what's the name of the variable of the target res. bundle? + for (Object arg : method.arguments()) { + if (arg instanceof StringLiteral + && resourceBundleId.equals(((StringLiteral) arg) + .getLiteralValue())) { + return vdf.getName().toString(); + } + } + } + + return null; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/RefactoringService.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/RefactoringService.java index 75d6f676..388acbee 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/RefactoringService.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/RefactoringService.java @@ -32,72 +32,81 @@ */ public class RefactoringService implements IRefactoringService { - /** - * {@inheritDoc} - */ - @Override - public void refactorKey(String projectName, String resourceBundleId, - String selectedLocale, String oldKey, String newKey, String enumName) { - ASTutilsUI.refactorKey(projectName, resourceBundleId, selectedLocale, oldKey, newKey, enumName); - } + /** + * {@inheritDoc} + */ + @Override + public void refactorKey(String projectName, String resourceBundleId, + String selectedLocale, String oldKey, String newKey, String enumName) { + ASTutilsUI.refactorKey(projectName, resourceBundleId, selectedLocale, + oldKey, newKey, enumName); + } - /** - * {@inheritDoc} - */ - @Override - public void openRefactorDialog(String projectName, String resourceBundleId, - String oldKey, String enumName) { - - KeyRefactoringDialog dialog = new KeyRefactoringDialog( - Display.getDefault().getActiveShell()); + /** + * {@inheritDoc} + */ + @Override + public void openRefactorDialog(String projectName, String resourceBundleId, + String oldKey, String enumName) { - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(oldKey); - config.setPreselectedBundle(resourceBundleId); - config.setProjectName(projectName); + KeyRefactoringDialog dialog = new KeyRefactoringDialog(Display + .getDefault().getActiveShell()); - dialog.setDialogConfiguration(config); + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(oldKey); + config.setPreselectedBundle(resourceBundleId); + config.setProjectName(projectName); - if (dialog.open() != InputDialog.OK) { - return; - } - - refactorKey(projectName, resourceBundleId, config.getSelectedLocale(), oldKey, config.getNewKey(), enumName); - } + dialog.setDialogConfiguration(config); - - /** - * {@inheritDoc} - */ - @Override - public void openRefactorDialog(IFile file, int selectionOffset) { - - String projectName = file.getProject().getName(); - CompilationUnit cu = ASTutilsUI.getCompilationUnit(file); - - StringLiteral literal = ASTutils.getStringLiteralAtPos(cu, selectionOffset); - - if (literal == null) { // check for Cal10n - String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos(projectName, cu, selectionOffset); - if (metaData != null) { - openRefactorDialog(projectName, metaData[0], metaData[1], metaData[2]); - } - } else { // it's a String (not Cal10n) - ResourceBundleManager manager = ResourceBundleManager.getManager(projectName); - ResourceAuditVisitor visitor = new ResourceAuditVisitor(file, projectName); - cu.accept(visitor); - - String oldKey = literal.getLiteralValue(); - IRegion region = visitor.getKeyAt(new Long(selectionOffset)); - String bundleName = visitor.getBundleReference(region); - if (bundleName != null) { - IMessagesBundleGroup resourceBundle = manager.getResourceBundle(bundleName); - if (resourceBundle.containsKey(oldKey)) { - String resourceBundleId = resourceBundle.getResourceBundleId(); - - openRefactorDialog(projectName, resourceBundleId, oldKey, null); - } - } - } - } + if (dialog.open() != InputDialog.OK) { + return; + } + + refactorKey(projectName, resourceBundleId, config.getSelectedLocale(), + oldKey, config.getNewKey(), enumName); + } + + /** + * {@inheritDoc} + */ + @Override + public void openRefactorDialog(IFile file, int selectionOffset) { + + String projectName = file.getProject().getName(); + CompilationUnit cu = ASTutilsUI.getCompilationUnit(file); + + StringLiteral literal = ASTutils.getStringLiteralAtPos(cu, + selectionOffset); + + if (literal == null) { // check for Cal10n + String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos( + projectName, cu, selectionOffset); + if (metaData != null) { + openRefactorDialog(projectName, metaData[0], metaData[1], + metaData[2]); + } + } else { // it's a String (not Cal10n) + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + ResourceAuditVisitor visitor = new ResourceAuditVisitor(file, + projectName); + cu.accept(visitor); + + String oldKey = literal.getLiteralValue(); + IRegion region = visitor.getKeyAt(new Long(selectionOffset)); + String bundleName = visitor.getBundleReference(region); + if (bundleName != null) { + IMessagesBundleGroup resourceBundle = manager + .getResourceBundle(bundleName); + if (resourceBundle.containsKey(oldKey)) { + String resourceBundleId = resourceBundle + .getResourceBundleId(); + + openRefactorDialog(projectName, resourceBundleId, oldKey, + null); + } + } + } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java index a5d9b317..d24a4f47 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java @@ -49,226 +49,246 @@ 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); + IJavaElement je = JavaCore.create(resource, + JavaCore.create(resource.getProject())); + // get the type of the currently loaded resource + ITypeRoot typeRoot = ((ICompilationUnit) je); - if (typeRoot == null) { - return null; - } + if (typeRoot == null) { + return null; + } - return getCompilationUnit(typeRoot); + 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); + // 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; + 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; + 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; + 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; } /** - * Performs the refactoring of messages key. The key can be a {@link String} or an - * Enumeration! If it is an enumeration, then the enumPath needs to be provided! - * - * @param projectName The name of the project, where the resource bundle file is in - * @param resourceBundleId The Id of the resource bundle, which contains the old key - * @param selectedLocale The {@link Locale} to change - * @param oldKey The name of the key to change - * @param newKey The name of the key, which replaces the old one - * @param enumPath The path of the enum file (needs: {@link IPath#toPortableString()}) - */ - public static void refactorKey(final String projectName, final String resourceBundleId, - final String selectedLocale, final String oldKey, final String newKey, final String enumPath) { - - // contains file and line - final List<String> changeSet = new ArrayList<String>(); - - ResourceBundleManager manager = ResourceBundleManager.getManager(projectName); - IProject project = manager.getProject(); - - try { - project.accept(new IResourceVisitor() { - - /** - * First step of filtering. Only classes, which import java.util.ResourceBundle - * or ch.qos.cal10n.MessageConveyor will be changed. An exception is the - * enum file, which gets referenced by the Cal10n framework. - * - * {@inheritDoc} - */ - @Override - public boolean visit(IResource resource) throws CoreException { - if (!(resource instanceof IFile) || !resource.getFileExtension().equals("java")) { - return true; - } - - final CompilationUnit cu = getCompilationUnit(resource); - - // step 1: import filter - for (Object obj : cu.imports()) { - ImportDeclaration imp = (ImportDeclaration) obj; - String importName = imp.getName().toString(); - if ("java.util.ResourceBundle".equals(importName)) { - PrimitiveRefactoringVisitor prv = new PrimitiveRefactoringVisitor(cu, - resourceBundleId, oldKey, newKey, changeSet); - cu.accept(prv); - prv.saveChanges(); - break; - } else if ("ch.qos.cal10n.MessageConveyor".equals(importName)) { // Cal10n - Cal10nRefactoringVisitor crv = new Cal10nRefactoringVisitor(cu, - oldKey, newKey, enumPath, changeSet); - cu.accept(crv); - crv.saveChanges(); - break; - } - } - - return false; - } - }); - } catch (CoreException e) { - Logger.logError(e); - } - - if (enumPath != null) { // Cal10n support, change the enum file - IFile file = project.getFile(enumPath.substring(project.getName().length() + 1)); - final CompilationUnit enumCu = getCompilationUnit(file); - - Cal10nEnumRefactoringVisitor enumVisitor = new Cal10nEnumRefactoringVisitor(enumCu, oldKey, newKey, changeSet); - enumCu.accept(enumVisitor); - } - - // change backend - RBManager rbManager = RBManager.getInstance(projectName); - IMessagesBundleGroup messagesBundleGroup = rbManager.getMessagesBundleGroup(resourceBundleId); - - if (KeyRefactoringDialog.ALL_LOCALES.equals(selectedLocale)) { - messagesBundleGroup.renameMessageKeys(oldKey, newKey); - } else { - IMessagesBundle messagesBundle = messagesBundleGroup.getMessagesBundle(LocaleUtils - .getLocaleByDisplayName(manager.getProvidedLocales(resourceBundleId), selectedLocale)); - messagesBundle.renameMessageKey(oldKey, newKey); -// rbManager.fireResourceChanged(messagesBundle); ?? - } - rbManager.fireEditorChanged(); // notify Resource Bundle View - - // show the summary dialog - KeyRefactoringSummaryDialog summaryDialog = new KeyRefactoringSummaryDialog(Display.getDefault().getActiveShell()); - - DialogConfiguration config = summaryDialog.new DialogConfiguration(); - config.setPreselectedKey(oldKey); - config.setNewKey(newKey); - config.setPreselectedBundle(resourceBundleId); - config.setProjectName(projectName); - - summaryDialog.setDialogConfiguration(config); - summaryDialog.setChangeSet(changeSet); - - summaryDialog.open(); - } - + * Performs the refactoring of messages key. The key can be a {@link String} + * or an Enumeration! If it is an enumeration, then the enumPath needs to be + * provided! + * + * @param projectName + * The name of the project, where the resource bundle file is in + * @param resourceBundleId + * The Id of the resource bundle, which contains the old key + * @param selectedLocale + * The {@link Locale} to change + * @param oldKey + * The name of the key to change + * @param newKey + * The name of the key, which replaces the old one + * @param enumPath + * The path of the enum file (needs: + * {@link IPath#toPortableString()}) + */ + public static void refactorKey(final String projectName, + final String resourceBundleId, final String selectedLocale, + final String oldKey, final String newKey, final String enumPath) { + + // contains file and line + final List<String> changeSet = new ArrayList<String>(); + + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + IProject project = manager.getProject(); + + try { + project.accept(new IResourceVisitor() { + + /** + * First step of filtering. Only classes, which import + * java.util.ResourceBundle or ch.qos.cal10n.MessageConveyor + * will be changed. An exception is the enum file, which gets + * referenced by the Cal10n framework. + * + * {@inheritDoc} + */ + @Override + public boolean visit(IResource resource) throws CoreException { + if (!(resource instanceof IFile) + || !resource.getFileExtension().equals("java")) { + return true; + } + + final CompilationUnit cu = getCompilationUnit(resource); + + // step 1: import filter + for (Object obj : cu.imports()) { + ImportDeclaration imp = (ImportDeclaration) obj; + String importName = imp.getName().toString(); + if ("java.util.ResourceBundle".equals(importName)) { + PrimitiveRefactoringVisitor prv = new PrimitiveRefactoringVisitor( + cu, resourceBundleId, oldKey, newKey, + changeSet); + cu.accept(prv); + prv.saveChanges(); + break; + } else if ("ch.qos.cal10n.MessageConveyor" + .equals(importName)) { // Cal10n + Cal10nRefactoringVisitor crv = new Cal10nRefactoringVisitor( + cu, oldKey, newKey, enumPath, changeSet); + cu.accept(crv); + crv.saveChanges(); + break; + } + } + + return false; + } + }); + } catch (CoreException e) { + Logger.logError(e); + } + + if (enumPath != null) { // Cal10n support, change the enum file + IFile file = project.getFile(enumPath.substring(project.getName() + .length() + 1)); + final CompilationUnit enumCu = getCompilationUnit(file); + + Cal10nEnumRefactoringVisitor enumVisitor = new Cal10nEnumRefactoringVisitor( + enumCu, oldKey, newKey, changeSet); + enumCu.accept(enumVisitor); + } + + // change backend + RBManager rbManager = RBManager.getInstance(projectName); + IMessagesBundleGroup messagesBundleGroup = rbManager + .getMessagesBundleGroup(resourceBundleId); + + if (KeyRefactoringDialog.ALL_LOCALES.equals(selectedLocale)) { + messagesBundleGroup.renameMessageKeys(oldKey, newKey); + } else { + IMessagesBundle messagesBundle = messagesBundleGroup + .getMessagesBundle(LocaleUtils.getLocaleByDisplayName( + manager.getProvidedLocales(resourceBundleId), + selectedLocale)); + messagesBundle.renameMessageKey(oldKey, newKey); + // rbManager.fireResourceChanged(messagesBundle); ?? + } + rbManager.fireEditorChanged(); // notify Resource Bundle View + + // show the summary dialog + KeyRefactoringSummaryDialog summaryDialog = new KeyRefactoringSummaryDialog( + Display.getDefault().getActiveShell()); + + DialogConfiguration config = summaryDialog.new DialogConfiguration(); + config.setPreselectedKey(oldKey); + config.setNewKey(newKey); + config.setPreselectedBundle(resourceBundleId); + config.setProjectName(projectName); + + summaryDialog.setDialogConfiguration(config); + summaryDialog.setChangeSet(changeSet); + + summaryDialog.open(); + } + } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java index 8542a7e5..8e64a4a3 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java @@ -62,993 +62,1012 @@ public class ASTutils { 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; + 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; + 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; + 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; + 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(); + 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); + VariableFinder vf = new VariableFinder(actRef); + cu.accept(vf); - if (!vf.isVariableFound()) { - referenceName = actRef; - break; - } + if (!vf.isVariableFound()) { + referenceName = actRef; + break; + } - i++; - } + i++; + } - return referenceName; + 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; + 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; + 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; + 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; + 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; + 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); + // Instantiate a new AST parser + ASTParser parser = ASTParser.newParser(AST.JLS3); + parser.setResolveBindings(true); - ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource - .getProject().getFile(resource.getRawLocation())); + ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource + .getProject().getFile(resource.getRawLocation())); - return cu; + return cu; } public static CompilationUnit createCompilationUnit(IDocument document) { - // Instantiate a new AST parser - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setResolveBindings(true); + // Instantiate a new AST parser + ASTParser parser = ASTParser.newParser(AST.JLS3); + parser.setResolveBindings(true); - parser.setSource(document.get().toCharArray()); - return (CompilationUnit) parser.createAST(null); + 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); - } + 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); - } + 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(); - } + 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(); + String bundleId, Locale locale) { + MethodInvocation mi = ast.newMethodInvocation(); - mi.setName(ast.newSimpleName("getBundle")); - mi.setExpression(ast.newName(new String[] { "ResourceBundle" })); + 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); + // Add bundle argument + StringLiteral sl = ast.newStringLiteral(); + sl.setLiteralValue(bundleId); + mi.arguments().add(sl); - // TODO Add Locale argument + // TODO Add Locale argument - return mi; + 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(); + 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(); + 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(); + String accessorName, String key, Locale locale) { + MethodParameterDescriptor accessorDesc = getRBAccessorDesc(); + MethodInvocation mi = ast.newMethodInvocation(); - mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0))); + mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0))); - // Declare expression - StringLiteral sl = ast.newStringLiteral(); - sl.setLiteralValue(key); + // Declare expression + StringLiteral sl = ast.newStringLiteral(); + sl.setLiteralValue(key); - // TODO define locale expression - if (mi.arguments().size() == accessorDesc.getPosition()) { - mi.arguments().add(sl); - } + // TODO define locale expression + if (mi.arguments().size() == accessorDesc.getPosition()) { + mi.arguments().add(sl); + } - SimpleName name = ast.newSimpleName(accessorName); - mi.setExpression(name); + SimpleName name = ast.newSimpleName(accessorName); + mi.setExpression(name); - return mi; + return mi; } public static String createResourceReference(String bundleId, String key, - Locale locale, IResource resource, int typePos, - String accessorName, IDocument doc, CompilationUnit cu) { + 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(); + 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(); + // retrieve compilation unit from document + ASTNode node = atd == null ? td : atd; + AST ast = node.getAST(); - ExpressionStatement expressionStatement = ast - .newExpressionStatement(referenceResource(ast, accessorName, - key, locale)); + ExpressionStatement expressionStatement = ast + .newExpressionStatement(referenceResource(ast, accessorName, + key, locale)); - String exp = expressionStatement.toString(); + 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); - } + // 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; + 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; + 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; + 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(); + 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; - } - } + 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; + String qName; + boolean importFound = false; - public ImportFinder(String qName) { - this.qName = qName; - } + public ImportFinder(String qName) { + this.qName = qName; + } - public boolean isImportFound() { - return importFound; - } + public boolean isImportFound() { + return importFound; + } - @Override - public boolean visit(ImportDeclaration id) { - if (id.getName().getFullyQualifiedName().equals(qName)) { - importFound = true; - } + @Override + public boolean visit(ImportDeclaration id) { + if (id.getName().getFullyQualifiedName().equals(qName)) { + importFound = true; + } - return true; - } + return true; + } } static class VariableFinder extends ASTVisitor { - boolean found = false; - String variableName; + boolean found = false; + String variableName; - public boolean isVariableFound() { - return found; - } + public boolean isVariableFound() { + return found; + } - public VariableFinder(String variableName) { - this.variableName = variableName; - } + public VariableFinder(String variableName) { + this.variableName = variableName; + } - @Override - public boolean visit(VariableDeclarationFragment vdf) { - if (vdf.getName().getFullyQualifiedName().equals(variableName)) { - found = true; - return false; - } + @Override + public boolean visit(VariableDeclarationFragment vdf) { + if (vdf.getName().getFullyQualifiedName().equals(variableName)) { + found = true; + return false; + } - return true; - } + 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; - } + 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; - } + 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; - } + 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; - } + 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; + } } - + /** - * Decides if an enumeration can be refactored or not. - * In other words, gives the OK for the Proposal to display. - * - * @author Alexej Strelzow - */ - static class Cal10nEnumLiteralFinder extends ASTVisitor { - private int position; - private String projectName; - - private String[] metaData; - // [0] resourceBunldeId - // [1] key value - // [2] relative path (to the project) of the enum file - - /** - * Constructor. - * @param position The position of the CTRL + Shift + Space operation - */ - public Cal10nEnumLiteralFinder(String projectName, int position) { - this.position = position; - this.projectName = projectName; - } - - /** - * Following constraints must be fulfilled to make an enum "refactorable":<br> - * <ol> - * <li>It must be known by the system (stored in a resource bundle file)</li> - * <li>It must be used by the class ch.qos.cal10n.IMessageConveyor (Cal10n framework)</li> - * </ol> - * - * {@inheritDoc} - */ - public boolean visit(MethodInvocation node) { - - boolean isCal10nCall = "ch.qos.cal10n.IMessageConveyor".equals(node.resolveMethodBinding().getDeclaringClass().getQualifiedName()); - - if (!isCal10nCall) { - if (node.arguments().size() == 0) { - return false; - } else { - return true; // because the Cal10n call may be an argument! - } - } else { - int startPosition = node.getStartPosition(); - int length = startPosition + node.getLength(); - if (startPosition < this.position && length > position && - !node.arguments().isEmpty() && - node.arguments().get(0) instanceof QualifiedName) { - QualifiedName qName = (QualifiedName) node.arguments().get(0); - startPosition = qName.getStartPosition(); - length = startPosition + qName.getLength(); - - if (startPosition < this.position && length > position) { - String resourceBundleId = getResourceBundleId(qName); - String keyName = qName.getName().toString(); - - if (isKnownBySystem(resourceBundleId, keyName)) { - String path = qName.resolveTypeBinding().getJavaElement().getResource().getFullPath().toPortableString(); - this.metaData = new String[3]; - this.metaData[0] = resourceBundleId; - this.metaData[1] = keyName; - this.metaData[2] = path; - } - } - } - } - - return false; - } - - private boolean isKnownBySystem(String resourceBundleId, String keyName) { - IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(this.projectName) - .getMessagesBundleGroup(resourceBundleId); - return messagesBundleGroup.containsKey(keyName); - } - - private String getResourceBundleId(QualifiedName qName) { - IAnnotationBinding[] annotations = qName.resolveTypeBinding().getAnnotations(); - for (IAnnotationBinding annotation : annotations) { - if ("BaseName".equals(annotation.getName())) { - return (String) annotation.getAllMemberValuePairs()[0].getValue(); - } - } - - return null; - } - - public String[] getMetaData() { - return metaData; - } - } - - /** - * Returns whether a refactoring proposal will be shown or not. - * @param projectName The name of the project the cu is in - * @param cu The {@link CompilationUnit} to analyze - * @param i The starting point to begin the analysis - * @return Meta data of the enum key to refactor or null - */ - public static String[] getCal10nEnumLiteralDataAtPos(String projectName, CompilationUnit cu, int i) { - Cal10nEnumLiteralFinder enumFinder = new Cal10nEnumLiteralFinder(projectName, i); - cu.accept(enumFinder); - return enumFinder.getMetaData(); - } + * Decides if an enumeration can be refactored or not. In other words, gives + * the OK for the Proposal to display. + * + * @author Alexej Strelzow + */ + static class Cal10nEnumLiteralFinder extends ASTVisitor { + private int position; + private String projectName; + + private String[] metaData; + + // [0] resourceBunldeId + // [1] key value + // [2] relative path (to the project) of the enum file + + /** + * Constructor. + * + * @param position + * The position of the CTRL + Shift + Space operation + */ + public Cal10nEnumLiteralFinder(String projectName, int position) { + this.position = position; + this.projectName = projectName; + } + + /** + * Following constraints must be fulfilled to make an enum + * "refactorable":<br> + * <ol> + * <li>It must be known by the system (stored in a resource bundle file) + * </li> + * <li>It must be used by the class ch.qos.cal10n.IMessageConveyor + * (Cal10n framework)</li> + * </ol> + * + * {@inheritDoc} + */ + public boolean visit(MethodInvocation node) { + + boolean isCal10nCall = "ch.qos.cal10n.IMessageConveyor".equals(node + .resolveMethodBinding().getDeclaringClass() + .getQualifiedName()); + + if (!isCal10nCall) { + if (node.arguments().size() == 0) { + return false; + } else { + return true; // because the Cal10n call may be an argument! + } + } else { + int startPosition = node.getStartPosition(); + int length = startPosition + node.getLength(); + if (startPosition < this.position && length > position + && !node.arguments().isEmpty() + && node.arguments().get(0) instanceof QualifiedName) { + QualifiedName qName = (QualifiedName) node.arguments().get( + 0); + startPosition = qName.getStartPosition(); + length = startPosition + qName.getLength(); + + if (startPosition < this.position && length > position) { + String resourceBundleId = getResourceBundleId(qName); + String keyName = qName.getName().toString(); + + if (isKnownBySystem(resourceBundleId, keyName)) { + String path = qName.resolveTypeBinding() + .getJavaElement().getResource() + .getFullPath().toPortableString(); + this.metaData = new String[3]; + this.metaData[0] = resourceBundleId; + this.metaData[1] = keyName; + this.metaData[2] = path; + } + } + } + } + + return false; + } + + private boolean isKnownBySystem(String resourceBundleId, String keyName) { + IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( + this.projectName).getMessagesBundleGroup(resourceBundleId); + return messagesBundleGroup.containsKey(keyName); + } + + private String getResourceBundleId(QualifiedName qName) { + IAnnotationBinding[] annotations = qName.resolveTypeBinding() + .getAnnotations(); + for (IAnnotationBinding annotation : annotations) { + if ("BaseName".equals(annotation.getName())) { + return (String) annotation.getAllMemberValuePairs()[0] + .getValue(); + } + } + + return null; + } + + public String[] getMetaData() { + return metaData; + } + } + + /** + * Returns whether a refactoring proposal will be shown or not. + * + * @param projectName + * The name of the project the cu is in + * @param cu + * The {@link CompilationUnit} to analyze + * @param i + * The starting point to begin the analysis + * @return Meta data of the enum key to refactor or null + */ + public static String[] getCal10nEnumLiteralDataAtPos(String projectName, + CompilationUnit cu, int i) { + Cal10nEnumLiteralFinder enumFinder = new Cal10nEnumLiteralFinder( + projectName, i); + cu.accept(enumFinder); + return enumFinder.getMetaData(); + } } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java index 5cb23c1b..34db6026 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java @@ -20,44 +20,44 @@ public class MethodParameterDescriptor { 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; + String declaringClass, boolean considerSuperclass, int position) { + super(); + this.setMethodName(methodName); + this.declaringClass = declaringClass; + this.considerSuperclass = considerSuperclass; + this.position = position; } public String getDeclaringClass() { - return declaringClass; + return declaringClass; } public void setDeclaringClass(String declaringClass) { - this.declaringClass = declaringClass; + this.declaringClass = declaringClass; } public boolean isConsiderSuperclass() { - return considerSuperclass; + return considerSuperclass; } public void setConsiderSuperclass(boolean considerSuperclass) { - this.considerSuperclass = considerSuperclass; + this.considerSuperclass = considerSuperclass; } public int getPosition() { - return position; + return position; } public void setPosition(int position) { - this.position = position; + this.position = position; } public void setMethodName(List<String> methodName) { - this.methodName = methodName; + this.methodName = methodName; } public List<String> getMethodName() { - return methodName; + return methodName; } } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java index 36ac0510..e431fc84 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java @@ -43,7 +43,7 @@ * */ public class ResourceAuditVisitor extends ASTVisitor implements - IResourceVisitor { + IResourceVisitor { private List<SLLocation> constants; private List<SLLocation> brokenStrings; @@ -57,205 +57,205 @@ public class ResourceAuditVisitor extends ASTVisitor implements 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; + 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; + 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; + 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); + 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; + 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; + return constants; } public List<SLLocation> getBrokenResourceReferences() { - return brokenStrings; + return brokenStrings; } public List<SLLocation> getBrokenRBReferences() { - return this.brokenRBReferences; + 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; + 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 ""; - } + if (bundleKeys.containsKey(region)) { + return bundleKeys.get(region); + } else { + return ""; + } } public String getBundleReference(IRegion region) { - return bundleReferences.get(region); + return bundleReferences.get(region); } @Override public boolean visit(IResource resource) throws CoreException { - // TODO Auto-generated method stub - return false; + // 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; + 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; + IRegion reg = null; + + Iterator<Long> keys = rbDefReferences.keySet().iterator(); + while (keys.hasNext()) { + Long startPos = keys.next(); + if (startPos > offset) { + break; + } + + IRegion region = rbDefReferences.get(startPos); + if (region != null && region.getOffset() <= offset + && (region.getOffset() + region.getLength()) >= offset) { + reg = region; + break; + } + } + + return reg; } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java index 8db317c5..56694650 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 @@ -29,27 +29,27 @@ public class ImageUtils { public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif"; //$NON-NLS-1$ public static final String EXPAND = "expand.gif"; //$NON-NLS-1$ public static final String DEFAULT_LOCALICON = File.separatorChar - + "countries" + File.separatorChar + "_f.gif"; + + "countries" + File.separatorChar + "_f.gif"; public static final String LOCATION_WITHOUT_ICON = File.separatorChar - + "countries" + File.separatorChar + "un.gif"; + + "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; + 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; } /** @@ -57,17 +57,17 @@ public static Image getBaseImage(String imageName) { * @return baseImage with a overlay warning-image */ public static Image getImageWithWarning(Image baseImage) { - String imageWithWarningId = baseImage.toString() + ".w"; - Image imageWithWarning = imageRegistry.get(imageWithWarningId); + 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); - } + if (imageWithWarning == null) { + Image warningImage = getBaseImage(WARNING_FLAG_IMAGE); + imageWithWarning = new OverlayIcon(baseImage, warningImage, + OverlayIcon.BOTTOM_LEFT).createImage(); + imageRegistry.put(imageWithWarningId, imageWithWarning); + } - return imageWithWarning; + return imageWithWarning; } /** @@ -76,46 +76,46 @@ public static Image getImageWithWarning(Image baseImage) { * @return baseImage with a overlay fragment-image */ public static Image getImageWithFragment(Image baseImage) { - String imageWithFragmentId = baseImage.toString() + ".f"; - Image imageWithFragment = imageRegistry.get(imageWithFragmentId); + 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); - } + 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 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; + String imageName; + Image image = null; + + if (locale != null && !locale.getCountry().equals("")) { + imageName = File.separatorChar + "countries" + File.separatorChar + + locale.getCountry().toLowerCase() + ".gif"; + image = getBaseImage(imageName); + } else { + if (locale != null) { + imageName = File.separatorChar + "countries" + + File.separatorChar + "l_" + + locale.getLanguage().toLowerCase() + ".gif"; + image = getBaseImage(imageName); + } else { + imageName = DEFAULT_LOCALICON.toLowerCase(); // Default locale + // icon + image = getBaseImage(imageName); + } + } + + if (image == null) + image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase()); + return image; } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java index 68faf55f..5ff9b3eb 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 @@ -37,8 +37,8 @@ public RBManagerActivator() { * ) */ public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; + super.start(context); + plugin = this; } /* @@ -49,8 +49,8 @@ public void start(BundleContext context) throws Exception { * ) */ public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); + plugin = null; + super.stop(context); } /** @@ -59,13 +59,13 @@ public void stop(BundleContext context) throws Exception { * @return the shared instance */ public static RBManagerActivator getDefault() { - return plugin; + return plugin; } public static ImageDescriptor getImageDescriptor(String name) { - String path = "icons/" + name; + String path = "icons/" + name; - return imageDescriptorFromPlugin(PLUGIN_ID, path); + return imageDescriptorFromPlugin(PLUGIN_ID, path); } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java index 4d7ed6f7..522a992a 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 @@ -23,48 +23,48 @@ public class RBLocation implements ILocation { 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; + 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; + ILocation sameValuePartner) { + this(file, startPos, endPos, language); + this.sameValuePartner = sameValuePartner; } @Override public IFile getFile() { - return file; + return file; } @Override public int getStartPos() { - return startPos; + return startPos; } @Override public int getEndPos() { - return endPos; + return endPos; } @Override public String getLiteral() { - return language; + return language; } @Override public Serializable getData() { - return data; + return data; } public void setData(Serializable data) { - this.data = data; + this.data = data; } public ILocation getSameValuePartner() { - return sameValuePartner; + 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 c3cc8562..c75044ef 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 @@ -52,27 +52,27 @@ public class ResourceBundleAuditor extends I18nRBAuditor { @Override public String[] getFileEndings() { - return new String[] { "properties" }; + return new String[] { "properties" }; } @Override public String getContextId() { - return "resourcebundle"; + return "resourcebundle"; } @Override public List<ILocation> getUnspecifiedKeyReferences() { - return unspecifiedKeys; + return unspecifiedKeys; } @Override public Map<ILocation, ILocation> getSameValuesReferences() { - return sameValues; + return sameValues; } @Override public List<ILocation> getMissingLanguageReferences() { - return missingLanguages; + return missingLanguages; } /* @@ -80,10 +80,10 @@ public List<ILocation> getMissingLanguageReferences() { */ @Override public void resetProblems() { - unspecifiedKeys = new LinkedList<ILocation>(); - sameValues = new HashMap<ILocation, ILocation>(); - missingLanguages = new LinkedList<ILocation>(); - seenRBs = new LinkedList<String>(); + unspecifiedKeys = new LinkedList<ILocation>(); + sameValues = new HashMap<ILocation, ILocation>(); + missingLanguages = new LinkedList<ILocation>(); + seenRBs = new LinkedList<String>(); } /* @@ -93,62 +93,62 @@ public void resetProblems() { */ @Override public void audit(IResource resource) { - if (!RBFileUtils.isResourceBundleFile(resource)) { - return; - } + if (!RBFileUtils.isResourceBundleFile(resource)) { + return; + } - IFile file = (IFile) resource; - String rbId = RBFileUtils.getCorrespondingResourceBundleId(file); + IFile file = (IFile) resource; + String rbId = RBFileUtils.getCorrespondingResourceBundleId(file); - if (!seenRBs.contains(rbId)) { - ResourceBundleManager rbmanager = ResourceBundleManager - .getManager(file.getProject()); - audit(rbId, rbmanager); - seenRBs.add(rbId); - } else { - return; - } + if (!seenRBs.contains(rbId)) { + ResourceBundleManager rbmanager = ResourceBundleManager + .getManager(file.getProject()); + audit(rbId, rbmanager); + seenRBs.add(rbId); + } else { + return; + } } /* * audits all files of a resourcebundle */ public void audit(String rbId, ResourceBundleManager rbmanager) { - IConfiguration configuration = ConfigurationManager.getInstance() - .getConfiguration(); - IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId); - Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId); - String[] keys = bundlegroup.getMessageKeys(); + IConfiguration configuration = ConfigurationManager.getInstance() + .getConfiguration(); + IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId); + Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId); + String[] keys = bundlegroup.getMessageKeys(); - for (IResource r : bundlefile) { - IFile f1 = (IFile) r; + for (IResource r : bundlefile) { + IFile f1 = (IFile) r; - for (String key : keys) { - // check if all keys have a value + for (String key : keys) { + // check if all keys have a value - if (auditUnspecifiedKey(f1, key, bundlegroup)) { - /* do nothing - all just done */ - } else { - // check if a key has the same value like a key of an other - // properties-file - if (configuration.getAuditSameValue() - && bundlefile.size() > 1) { - for (IResource r2 : bundlefile) { - IFile f2 = (IFile) r2; - auditSameValues(f1, f2, key, bundlegroup); - } - } - } - } - } + if (auditUnspecifiedKey(f1, key, bundlegroup)) { + /* do nothing - all just done */ + } else { + // check if a key has the same value like a key of an other + // properties-file + if (configuration.getAuditSameValue() + && bundlefile.size() > 1) { + for (IResource r2 : bundlefile) { + IFile f2 = (IFile) r2; + auditSameValues(f1, f2, key, bundlegroup); + } + } + } + } + } - if (configuration.getAuditMissingLanguage()) { - // checks if the resourcebundle supports all project-languages - Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId); - Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales(); + if (configuration.getAuditMissingLanguage()) { + // checks if the resourcebundle supports all project-languages + Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId); + Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales(); - auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId); - } + auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId); + } } /* @@ -156,14 +156,14 @@ public void audit(String rbId, ResourceBundleManager rbmanager) { * 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; - } + 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; + } } /* @@ -171,23 +171,23 @@ private boolean auditUnspecifiedKey(IFile f1, String key, * 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 (l1 != null && l2 != null && !l2.equals(l1)) { - IMessage message = bundlegroup.getMessage(key, l2); + IMessagesBundleGroup bundlegroup) { + Locale l1 = RBFileUtils.getLocale(f1); + Locale l2 = RBFileUtils.getLocale(f2); - if (message != null) { - if (bundlegroup.getMessage(key, l1).getValue() - .equals(message.getValue())) { - int pos1 = calculateKeyLine(key, f1); - int pos2 = calculateKeyLine(key, f2); - sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key), - new RBLocation(f2, pos2, pos2 + 1, key)); - } - } - } + if (l1 != null && l2 != null && !l2.equals(l1)) { + 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)); + } + } + } } /* @@ -195,68 +195,68 @@ private void auditSameValues(IFile f1, IFile f2, String key, * 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; + Set<Locale> projectLocales, ResourceBundleManager rbmanager, + String rbId) { + for (Locale pLocale : projectLocales) { + if (!rbLocales.contains(pLocale)) { + String language = pLocale != null ? pLocale.toString() + : ResourceBundleManager.defaultLocaleTag; - // Add Warning to default-file or a random chosen file - IResource representative = rbmanager.getResourceBundleFile( - rbId, null); - if (representative == null) { - representative = rbmanager.getRandomFile(rbId); - } - missingLanguages.add(new RBLocation((IFile) representative, 1, - 2, language)); - } - } + // Add Warning to default-file or a random chosen file + IResource representative = rbmanager.getResourceBundleFile( + rbId, null); + if (representative == null) { + representative = rbmanager.getRandomFile(rbId); + } + missingLanguages.add(new RBLocation((IFile) representative, 1, + 2, language)); + } + } } /* * Finds a position where the key is located or missing */ private int calculateKeyLine(String key, IFile file) { - int linenumber = 1; - try { - // if (!Boolean.valueOf(System.getProperty("dirty"))) { - // System.setProperty("dirty", "true"); - file.refreshLocal(IFile.DEPTH_ZERO, null); - InputStream is = file.getContents(); - BufferedReader bf = new BufferedReader(new InputStreamReader(is)); - String line; - while ((line = bf.readLine()) != null) { - if ((!line.isEmpty()) && (!line.startsWith("#")) - && (line.compareTo(key) > 0)) { - return linenumber; - } - linenumber++; - } - // System.setProperty("dirty", "false"); - // } - } catch (CoreException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return linenumber; + 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; - } + 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; + return resolutions; } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java index 912d27e1..7671b1c9 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 @@ -24,30 +24,30 @@ public class MissingLanguageResolution implements IMarkerResolution2 { private Locale language; public MissingLanguageResolution(Locale language) { - this.language = 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); + 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"; + return "Creates a new localized properties-file with the same basename as the resourcebundle"; } @Override public Image getImage() { - return null; + return null; } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java index fedbd4f1..2e47dac9 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 @@ -23,53 +23,53 @@ public class VirtualContainer { 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; - } + 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; + this.container = container; } public VirtualContainer(IContainer container, int rbCount) { - this(container, false); - this.rbCount = rbCount; + this(container, false); + this.rbCount = rbCount; } public ResourceBundleManager getResourceBundleManager() { - if (rbmanager == null) { - rbmanager = ResourceBundleManager - .getManager(container.getProject()); - } - return rbmanager; + if (rbmanager == null) { + rbmanager = ResourceBundleManager + .getManager(container.getProject()); + } + return rbmanager; } public IContainer getContainer() { - return container; + return container; } public void setRbCounter(int rbCount) { - this.rbCount = rbCount; + this.rbCount = rbCount; } public int getRbCount() { - return rbCount; + return rbCount; } public void recount() { - rbCount = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .countRecursiveResourceBundle(container); + rbCount = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .countRecursiveResourceBundle(container); } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java index a6c1447a..fe589e91 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 @@ -25,43 +25,43 @@ private VirtualContentManager() { } public static VirtualContentManager getVirtualContentManager() { - if (singelton == null) { - singelton = new VirtualContentManager(); - } - return singelton; + if (singelton == null) { + singelton = new VirtualContentManager(); + } + return singelton; } public VirtualContainer getContainer(IContainer container) { - return containers.get(container); + return containers.get(container); } public void addVContainer(IContainer container, VirtualContainer vContainer) { - containers.put(container, vContainer); + containers.put(container, vContainer); } public void removeVContainer(IContainer container) { - vResourceBundles.remove(container); + vResourceBundles.remove(container); } public VirtualResourceBundle getVResourceBundles(String vRbId) { - return vResourceBundles.get(vRbId); + return vResourceBundles.get(vRbId); } public void addVResourceBundle(String vRbId, - VirtualResourceBundle vResourceBundle) { - vResourceBundles.put(vRbId, vResourceBundle); + VirtualResourceBundle vResourceBundle) { + vResourceBundles.put(vRbId, vResourceBundle); } public void removeVResourceBundle(String vRbId) { - vResourceBundles.remove(vRbId); + vResourceBundles.remove(vRbId); } public boolean containsVResourceBundles(String vRbId) { - return vResourceBundles.containsKey(vRbId); + return vResourceBundles.containsKey(vRbId); } public void reset() { - vResourceBundles.clear(); - containers.clear(); + vResourceBundles.clear(); + containers.clear(); } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java index 44cd4a76..70ab5b2d 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 @@ -29,46 +29,46 @@ public class VirtualProject extends VirtualContainer { // 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); + 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); - // } - // }); + 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(); + return rbmanager.getProjectProvidedLocales(); } public boolean isFragment() { - return isFragment; + return isFragment; } public IProject getHostProject() { - return hostProject; + return hostProject; } public boolean hasFragments() { - return !fragmentProjects.isEmpty(); + return !fragmentProjects.isEmpty(); } public List<IProject> getFragmets() { - return fragmentProjects; + 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 ce0b96df..3cc8e55c 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 @@ -23,38 +23,38 @@ public class VirtualResourceBundle { private ResourceBundleManager rbmanager; public VirtualResourceBundle(String rbname, String rbId, - ResourceBundleManager rbmanager) { - this.rbmanager = rbmanager; - resourcebundlename = rbname; - resourcebundleId = rbId; + ResourceBundleManager rbmanager) { + this.rbmanager = rbmanager; + resourcebundlename = rbname; + resourcebundleId = rbId; } public ResourceBundleManager getResourceBundleManager() { - return rbmanager; + return rbmanager; } public String getResourceBundleId() { - return resourcebundleId; + return resourcebundleId; } @Override public String toString() { - return resourcebundleId; + return resourcebundleId; } public IPath getFullPath() { - return rbmanager.getRandomFile(resourcebundleId).getFullPath(); + return rbmanager.getRandomFile(resourcebundleId).getFullPath(); } public String getName() { - return resourcebundlename; + return resourcebundlename; } public Collection<IResource> getFiles() { - return rbmanager.getResourceBundles(resourcebundleId); + return rbmanager.getResourceBundles(resourcebundleId); } public IFile getRandomFile() { - return rbmanager.getRandomFile(resourcebundleId); + 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 49d72909..7601c78f 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 @@ -33,87 +33,87 @@ public class Hover { 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(); + this.informant = informant; + hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); + Display display = hoverShell.getDisplay(); - GridLayout gridLayout = new GridLayout(1, false); - gridLayout.verticalSpacing = 2; - hoverShell.setLayout(gridLayout); + GridLayout gridLayout = new GridLayout(1, false); + gridLayout.verticalSpacing = 2; + hoverShell.setLayout(gridLayout); - hoverShell.setBackground(display - .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - hoverShell.setForeground(display - .getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + hoverShell.setBackground(display + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + hoverShell.setForeground(display + .getSystemColor(SWT.COLOR_INFO_FOREGROUND)); } private void setHoverLocation(Shell shell, Point position) { - Rectangle displayBounds = shell.getDisplay().getBounds(); - Rectangle shellBounds = shell.getBounds(); - shellBounds.x = Math.max( - Math.min(position.x + 1, displayBounds.width - - shellBounds.width), 0); - shellBounds.y = Math.max( - Math.min(position.y + 16, displayBounds.height - - (shellBounds.height + 1)), 0); - shell.setBounds(shellBounds); + 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.addMouseListener(new MouseAdapter() { + public void mouseDown(MouseEvent e) { + if (hoverShell != null && hoverShell.isVisible()) { + hoverShell.setVisible(false); + } + } + }); - control.addMouseTrackListener(new MouseTrackAdapter() { - public void mouseExit(MouseEvent e) { - if (hoverShell != null && hoverShell.isVisible()) - hoverShell.setVisible(false); - } + control.addMouseTrackListener(new MouseTrackAdapter() { + public void mouseExit(MouseEvent e) { + if (hoverShell != null && hoverShell.isVisible()) + hoverShell.setVisible(false); + } - public void mouseHover(MouseEvent event) { - Point pt = new Point(event.x, event.y); - Widget widget = event.widget; - if (widget instanceof ToolBar) { - ToolBar w = (ToolBar) widget; - widget = w.getItem(pt); - } - if (widget instanceof Table) { - Table w = (Table) widget; - widget = w.getItem(pt); - } - if (widget instanceof Tree) { - Tree w = (Tree) widget; - widget = w.getItem(pt); - } - if (widget == null) { - hoverShell.setVisible(false); - return; - } - hoverPosition = control.toDisplay(pt); + public void mouseHover(MouseEvent event) { + Point pt = new Point(event.x, event.y); + Widget widget = event.widget; + if (widget instanceof ToolBar) { + ToolBar w = (ToolBar) widget; + widget = w.getItem(pt); + } + if (widget instanceof Table) { + Table w = (Table) widget; + widget = w.getItem(pt); + } + if (widget instanceof Tree) { + Tree w = (Tree) widget; + widget = w.getItem(pt); + } + if (widget == null) { + hoverShell.setVisible(false); + return; + } + hoverPosition = control.toDisplay(pt); - boolean show = false; - Object data = widget.getData(); + boolean show = false; + Object data = widget.getData(); - for (HoverInformant hi : informant) { - hi.getInfoComposite(data, hoverShell); - if (hi.show()) - show = true; - } + for (HoverInformant hi : informant) { + hi.getInfoComposite(data, hoverShell); + if (hi.show()) + show = true; + } - if (show) { - hoverShell.pack(); - hoverShell.layout(); - setHoverLocation(hoverShell, hoverPosition); - hoverShell.setVisible(true); - } else - hoverShell.setVisible(false); + if (show) { + hoverShell.pack(); + hoverShell.layout(); + setHoverLocation(hoverShell, hoverPosition); + hoverShell.setVisible(true); + } else + hoverShell.setVisible(false); - } - }); + } + }); } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java index 18b99cac..c415e211 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 @@ -29,29 +29,29 @@ public class ExpandAllActionDelegate implements IViewActionDelegate { @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(); - } + 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 + // TODO Auto-generated method stub } @Override public void init(IViewPart view) { - viewer = ((CommonNavigator) view).getCommonViewer(); + viewer = ((CommonNavigator) view).getCommonViewer(); } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java index b5f40936..5ca05a7b 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 @@ -24,44 +24,44 @@ public class ToggleFilterActionDelegate implements IViewActionDelegate { private INavigatorFilterService filterService; private boolean active; private static final String[] FILTER = { RBManagerActivator.PLUGIN_ID - + ".filter.ProblematicResourceBundleFiles" }; + + ".filter.ProblematicResourceBundleFiles" }; @Override public void run(IAction action) { - if (active == true) { - filterService.activateFilterIdsAndUpdateViewer(new String[0]); - active = false; - } else { - filterService.activateFilterIdsAndUpdateViewer(FILTER); - active = true; - } + 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 + // Active when content change } @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; + 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]; + ICommonFilterDescriptor[] fds = filterService + .getVisibleFilterDescriptors(); + String activeFilterIds[] = new String[fds.length]; - for (int i = 0; i < fds.length; i++) - activeFilterIds[i] = fds[i].getId(); + for (int i = 0; i < fds.length; i++) + activeFilterIds[i] = fds[i].getId(); - return activeFilterIds; + return activeFilterIds; } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java index 1b98016a..78e7de75 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 @@ -29,21 +29,21 @@ public class LinkHelper implements ILinkHelper { @Override public IStructuredSelection findSelection(IEditorInput anInput) { - IFile file = ResourceUtil.getFile(anInput); - if (file != null) { - return new StructuredSelection(file); - } - return StructuredSelection.EMPTY; + 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) {/**/ - } + IStructuredSelection aSelection) { + if (aSelection.getFirstElement() instanceof IFile) + try { + IDE.openEditor(aPage, (IFile) aSelection.getFirstElement()); + } catch (PartInitException e) {/**/ + } } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java index 50ae03ab..a33d985b 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 @@ -57,8 +57,8 @@ * */ public class ResourceBundleContentProvider implements ITreeContentProvider, - IResourceChangeListener, IPropertyChangeListener, - IResourceBundleChangedListener { + 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; @@ -72,96 +72,96 @@ public class ResourceBundleContentProvider implements ITreeContentProvider, * */ public ResourceBundleContentProvider() { - ResourcesPlugin.getWorkspace().addResourceChangeListener(this, - IResourceChangeEvent.POST_CHANGE); - TapiJIPreferences.addPropertyChangeListener(this); - vcManager = VirtualContentManager.getVirtualContentManager(); - listenedProjects = new LinkedList<IProject>(); + 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); + 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]; + 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]; } /* @@ -169,298 +169,298 @@ public Object[] getChildren(final Object parentElement) { * 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(); + 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; + 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; + 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(); + ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); + TapiJIPreferences.removePropertyChangeListener(this); + vcManager.reset(); + unregisterAllResourceBundleListner(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - this.viewer = (StructuredViewer) viewer; + 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(); - } + 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; - } + 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(); + if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) { + vcManager.reset(); - refresh(root); - } + 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()); - } + 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(); + 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); + listenedProjects.add(p); - ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p); - for (String rbId : rbmanager.getResourceBundleIdentifiers()) { - rbmanager.registerResourceBundleChangeListener(rbId, this); - } + 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); - } - } + 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); + 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 fc147942..b883d060 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,172 +36,172 @@ import org.eclipse.ui.navigator.IDescriptionProvider; public class ResourceBundleLabelProvider extends LabelProvider implements - ILabelProvider, IDescriptionProvider { + ILabelProvider, IDescriptionProvider { VirtualContentManager vcManager; public ResourceBundleLabelProvider() { - super(); - vcManager = VirtualContentManager.getVirtualContentManager(); + 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; + 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(); + 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; + 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; + 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 index b919658f..6b224116 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 @@ -24,31 +24,31 @@ 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)); + 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; + 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); - } + IStructuredSelection sSelection = (IStructuredSelection) viewer + .getSelection(); + Iterator<?> it = sSelection.iterator(); + while (it.hasNext()) { + viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS); + } } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java index 4bb15f1e..25536452 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 @@ -28,29 +28,29 @@ public class GeneralActionProvider extends CommonActionProvider { private IAction expandAction; public GeneralActionProvider() { - // TODO Auto-generated constructor stub + // 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()); + 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); + 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 2b8b9587..48a99efa 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 @@ -22,32 +22,32 @@ public class OpenVRBAction extends Action { private ISelectionProvider selectionProvider; public OpenVRBAction(ISelectionProvider selectionProvider) { - this.selectionProvider = selectionProvider; + this.selectionProvider = selectionProvider; } @Override public boolean isEnabled() { - IStructuredSelection sSelection = (IStructuredSelection) selectionProvider - .getSelection(); - if (sSelection.size() == 1) - return true; - else - return false; + 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(); + IStructuredSelection sSelection = (IStructuredSelection) selectionProvider + .getSelection(); + if (sSelection.size() == 1 + && sSelection.getFirstElement() instanceof VirtualResourceBundle) { + VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection + .getFirstElement(); + IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); - EditorUtils.openEditor(wp, vRB.getRandomFile(), - EditorUtils.RESOURCE_BUNDLE_EDITOR); - } + EditorUtils.openEditor(wp, vRB.getRandomFile(), + EditorUtils.RESOURCE_BUNDLE_EDITOR); + } } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java index f1972fc0..50a2dbcc 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 @@ -23,19 +23,19 @@ public class VirtualRBActionProvider extends CommonActionProvider { private IAction openAction; public VirtualRBActionProvider() { - // TODO Auto-generated constructor stub + // TODO Auto-generated constructor stub } @Override public void init(ICommonActionExtensionSite aSite) { - super.init(aSite); - openAction = new OpenVRBAction(aSite.getViewSite() - .getSelectionProvider()); + super.init(aSite); + openAction = new OpenVRBAction(aSite.getViewSite() + .getSelectionProvider()); } @Override public void fillActionBars(IActionBars actionBars) { - actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, - openAction); + 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 ae330da6..87edcf6b 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 @@ -44,189 +44,189 @@ public class I18NProjectInformant implements HoverInformant { @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; + 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; + return show; } private void setColor(Control control) { - Display display = control.getParent().getDisplay(); + 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) { - setColor(composite); - - for (Control c : composite.getChildren()) { - setColor(c); - if (c instanceof Composite) { - sinkColor((Composite) c); - } - } + 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(); + 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(); + 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 ""; + 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 ""; + if (data instanceof IProject) { + List<IProject> fragments = FragmentProjectUtils + .getFragments((IProject) data); + if (fragments.size() > 0) { + StringBuilder sb = new StringBuilder(); + + int i = 0; + for (IProject f : fragments) { + sb.append(f.getName()); + if (++i != fragments.size()) { + sb.append("\n"); + } + } + return sb.toString(); + } + } + return ""; } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java index 32169845..8c06e72b 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 @@ -52,230 +52,230 @@ public class RBMarkerInformant implements HoverInformant { @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; + 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; + return show; } private void setColor(Control control) { - Display display = control.getParent().getDisplay(); + 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) { - setColor(composite); - - for (Control c : composite.getChildren()) { - setColor(c); - if (c instanceof Composite) { - sinkColor((Composite) c); - } - } + 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(); + 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(); + 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 ""; + 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 ""; + 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 index fa7a44eb..0f3fc344 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 @@ -33,52 +33,52 @@ public class ProblematicResourceBundleFilter extends ViewerFilter { */ @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; - } + 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())); + 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; - } + 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; + } catch (CoreException e) { + } + } + return false; } }
65a5e2cc46b2c04591aa59b7a85751479a7dbd0b
hadoop
YARN-1936. Added security support for the Timeline- Client. Contributed by Zhijie Shen. svn merge --ignore-ancestry -c 1597153- ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1597154 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 32c042622ceb3..02b922616b362 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -78,6 +78,9 @@ Release 2.5.0 - UNRELEASED YARN-2049. Added delegation-token support for the Timeline Server. (Zhijie Shen via vinodkv) + YARN-1936. Added security support for the Timeline Client. (Zhijie Shen via + vinodkv) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/TimelineClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/TimelineClient.java index a2ed3e70a51c9..de1d3e2ae53ff 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/TimelineClient.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/TimelineClient.java @@ -23,11 +23,13 @@ import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Unstable; +import org.apache.hadoop.security.token.Token; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity; import org.apache.hadoop.yarn.api.records.timeline.TimelinePutResponse; import org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl; import org.apache.hadoop.yarn.exceptions.YarnException; +import org.apache.hadoop.yarn.security.client.TimelineDelegationTokenIdentifier; /** * A client library that can be used to post some information in terms of a @@ -65,4 +67,22 @@ protected TimelineClient(String name) { public abstract TimelinePutResponse putEntities( TimelineEntity... entities) throws IOException, YarnException; + /** + * <p> + * Get a delegation token so as to be able to talk to the timeline server in a + * secure way. + * </p> + * + * @param renewer + * Address of the renewer who can renew these tokens when needed by + * securely talking to the timeline server + * @return a delegation token ({@link Token}) that can be used to talk to the + * timeline server + * @throws IOException + * @throws YarnException + */ + @Public + public abstract Token<TimelineDelegationTokenIdentifier> getDelegationToken( + String renewer) throws IOException, YarnException; + } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/TimelineClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/TimelineClientImpl.java index 64cc041aaea54..5ffe17a24a6fb 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/TimelineClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/TimelineClientImpl.java @@ -18,24 +18,43 @@ package org.apache.hadoop.yarn.client.api.impl; +import java.io.File; import java.io.IOException; +import java.net.HttpURLConnection; import java.net.URI; +import java.net.URL; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import javax.ws.rs.core.MediaType; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.GnuParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Options; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.security.authentication.client.AuthenticatedURL; +import org.apache.hadoop.security.authentication.client.AuthenticationException; +import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntities; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity; import org.apache.hadoop.yarn.api.records.timeline.TimelinePutResponse; import org.apache.hadoop.yarn.client.api.TimelineClient; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; +import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; +import org.apache.hadoop.yarn.security.client.TimelineDelegationTokenIdentifier; +import org.apache.hadoop.yarn.security.client.TimelineDelegationTokenSelector; +import org.apache.hadoop.yarn.util.timeline.TimelineUtils; import org.apache.hadoop.yarn.webapp.YarnJacksonJaxbJsonProvider; +import org.codehaus.jackson.map.ObjectMapper; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; @@ -44,6 +63,8 @@ import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory; +import com.sun.jersey.client.urlconnection.URLConnectionClientHandler; @Private @Unstable @@ -52,16 +73,29 @@ public class TimelineClientImpl extends TimelineClient { private static final Log LOG = LogFactory.getLog(TimelineClientImpl.class); private static final String RESOURCE_URI_STR = "/ws/v1/timeline/"; private static final Joiner JOINER = Joiner.on(""); + private static Options opts; + static { + opts = new Options(); + opts.addOption("put", true, "Put the TimelineEntities in a JSON file"); + opts.getOption("put").setArgName("Path to the JSON file"); + opts.addOption("help", false, "Print usage"); + } private Client client; private URI resURI; private boolean isEnabled; + private TimelineAuthenticatedURLConnectionFactory urlFactory; public TimelineClientImpl() { super(TimelineClientImpl.class.getName()); ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(YarnJacksonJaxbJsonProvider.class); - client = Client.create(cc); + if (UserGroupInformation.isSecurityEnabled()) { + urlFactory = new TimelineAuthenticatedURLConnectionFactory(); + client = new Client(new URLConnectionClientHandler(urlFactory), cc); + } else { + client = Client.create(cc); + } } protected void serviceInit(Configuration conf) throws Exception { @@ -83,6 +117,9 @@ protected void serviceInit(Configuration conf) throws Exception { YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_ADDRESS), RESOURCE_URI_STR)); } + if (UserGroupInformation.isSecurityEnabled()) { + urlFactory.setService(TimelineUtils.buildTimelineTokenService(conf)); + } LOG.info("Timeline service address: " + resURI); } super.serviceInit(conf); @@ -124,6 +161,13 @@ public TimelinePutResponse putEntities( return resp.getEntity(TimelinePutResponse.class); } + @Override + public Token<TimelineDelegationTokenIdentifier> getDelegationToken( + String renewer) throws IOException, YarnException { + return TimelineAuthenticator.getDelegationToken(resURI.toURL(), + urlFactory.token, renewer); + } + @Private @VisibleForTesting public ClientResponse doPostingEntities(TimelineEntities entities) { @@ -133,4 +177,138 @@ public ClientResponse doPostingEntities(TimelineEntities entities) { .post(ClientResponse.class, entities); } + private static class TimelineAuthenticatedURLConnectionFactory + implements HttpURLConnectionFactory { + + private AuthenticatedURL.Token token; + private TimelineAuthenticator authenticator; + private Token<TimelineDelegationTokenIdentifier> dToken; + private Text service; + + public TimelineAuthenticatedURLConnectionFactory() { + token = new AuthenticatedURL.Token(); + authenticator = new TimelineAuthenticator(); + } + + @Override + public HttpURLConnection getHttpURLConnection(URL url) throws IOException { + try { + if (dToken == null) { + //TODO: need to take care of the renew case + dToken = selectToken(); + if (LOG.isDebugEnabled()) { + LOG.debug("Timeline delegation token: " + dToken.toString()); + } + } + if (dToken != null) { + Map<String, String> params = new HashMap<String, String>(); + TimelineAuthenticator.injectDelegationToken(params, dToken); + url = TimelineAuthenticator.appendParams(url, params); + if (LOG.isDebugEnabled()) { + LOG.debug("URL with delegation token: " + url); + } + } + return new AuthenticatedURL(authenticator).openConnection(url, token); + } catch (AuthenticationException e) { + LOG.error("Authentication failed when openning connection [" + url + + "] with token [" + token + "].", e); + throw new IOException(e); + } + } + + private Token<TimelineDelegationTokenIdentifier> selectToken() { + UserGroupInformation ugi; + try { + ugi = UserGroupInformation.getCurrentUser(); + } catch (IOException e) { + String msg = "Error when getting the current user"; + LOG.error(msg, e); + throw new YarnRuntimeException(msg, e); + } + TimelineDelegationTokenSelector tokenSelector = + new TimelineDelegationTokenSelector(); + return tokenSelector.selectToken( + service, ugi.getCredentials().getAllTokens()); + } + + public void setService(Text service) { + this.service = service; + } + + } + + public static void main(String[] argv) throws Exception { + CommandLine cliParser = new GnuParser().parse(opts, argv); + if (cliParser.hasOption("put")) { + String path = cliParser.getOptionValue("put"); + if (path != null && path.length() > 0) { + putTimelineEntitiesInJSONFile(path); + return; + } + } + printUsage(); + } + + /** + * Put timeline data in a JSON file via command line. + * + * @param path + * path to the {@link TimelineEntities} JSON file + */ + private static void putTimelineEntitiesInJSONFile(String path) { + File jsonFile = new File(path); + if (!jsonFile.exists()) { + System.out.println("Error: File [" + jsonFile.getAbsolutePath() + + "] doesn't exist"); + return; + } + ObjectMapper mapper = new ObjectMapper(); + YarnJacksonJaxbJsonProvider.configObjectMapper(mapper); + TimelineEntities entities = null; + try { + entities = mapper.readValue(jsonFile, TimelineEntities.class); + } catch (Exception e) { + System.err.println("Error: " + e.getMessage()); + e.printStackTrace(System.err); + return; + } + Configuration conf = new YarnConfiguration(); + TimelineClient client = TimelineClient.createTimelineClient(); + client.init(conf); + client.start(); + try { + if (UserGroupInformation.isSecurityEnabled() + && conf.getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, false)) { + Token<TimelineDelegationTokenIdentifier> token = + client.getDelegationToken( + UserGroupInformation.getCurrentUser().getUserName()); + UserGroupInformation.getCurrentUser().addToken(token); + } + TimelinePutResponse response = client.putEntities( + entities.getEntities().toArray( + new TimelineEntity[entities.getEntities().size()])); + if (response.getErrors().size() == 0) { + System.out.println("Timeline data is successfully put"); + } else { + for (TimelinePutResponse.TimelinePutError error : response.getErrors()) { + System.out.println("TimelineEntity [" + error.getEntityType() + ":" + + error.getEntityId() + "] is not successfully put. Error code: " + + error.getErrorCode()); + } + } + } catch (Exception e) { + System.err.println("Error: " + e.getMessage()); + e.printStackTrace(System.err); + } finally { + client.stop(); + } + } + + /** + * Helper function to print out usage + */ + private static void printUsage() { + new HelpFormatter().printHelp("TimelineClient", opts); + } + } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java index 8a0348b336842..f1a3b6eeceaf3 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java @@ -19,6 +19,7 @@ package org.apache.hadoop.yarn.client.api.impl; import java.io.IOException; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; @@ -29,8 +30,13 @@ import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.io.DataInputByteBuffer; +import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.Text; import org.apache.hadoop.ipc.RPC; +import org.apache.hadoop.security.Credentials; +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportResponse; @@ -64,6 +70,7 @@ import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerId; +import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerReport; import org.apache.hadoop.yarn.api.records.NodeReport; import org.apache.hadoop.yarn.api.records.NodeState; @@ -74,6 +81,7 @@ import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; import org.apache.hadoop.yarn.client.ClientRMProxy; import org.apache.hadoop.yarn.client.api.AHSClient; +import org.apache.hadoop.yarn.client.api.TimelineClient; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.YarnClientApplication; import org.apache.hadoop.yarn.conf.YarnConfiguration; @@ -82,8 +90,10 @@ import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; +import org.apache.hadoop.yarn.security.client.TimelineDelegationTokenIdentifier; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; +import org.apache.hadoop.yarn.util.timeline.TimelineUtils; import com.google.common.annotations.VisibleForTesting; @@ -97,8 +107,11 @@ public class YarnClientImpl extends YarnClient { protected long submitPollIntervalMillis; private long asyncApiPollIntervalMillis; private long asyncApiPollTimeoutMillis; - protected AHSClient historyClient; + private AHSClient historyClient; private boolean historyServiceEnabled; + protected TimelineClient timelineClient; + protected Text timelineService; + protected boolean timelineServiceEnabled; private static final String ROOT = "root"; @@ -126,10 +139,17 @@ protected void serviceInit(Configuration conf) throws Exception { if (conf.getBoolean(YarnConfiguration.APPLICATION_HISTORY_ENABLED, YarnConfiguration.DEFAULT_APPLICATION_HISTORY_ENABLED)) { historyServiceEnabled = true; - historyClient = AHSClientImpl.createAHSClient(); - historyClient.init(getConfig()); + historyClient = AHSClient.createAHSClient(); + historyClient.init(conf); } + if (conf.getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, + YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED)) { + timelineServiceEnabled = true; + timelineClient = TimelineClient.createTimelineClient(); + timelineClient.init(conf); + timelineService = TimelineUtils.buildTimelineTokenService(conf); + } super.serviceInit(conf); } @@ -141,6 +161,9 @@ protected void serviceStart() throws Exception { if (historyServiceEnabled) { historyClient.start(); } + if (timelineServiceEnabled) { + timelineClient.start(); + } } catch (IOException e) { throw new YarnRuntimeException(e); } @@ -155,6 +178,9 @@ protected void serviceStop() throws Exception { if (historyServiceEnabled) { historyClient.stop(); } + if (timelineServiceEnabled) { + timelineClient.stop(); + } super.serviceStop(); } @@ -189,6 +215,12 @@ public YarnClientApplication createApplication() Records.newRecord(SubmitApplicationRequest.class); request.setApplicationSubmissionContext(appContext); + // Automatically add the timeline DT into the CLC + // Only when the security and the timeline service are both enabled + if (isSecurityEnabled() && timelineServiceEnabled) { + addTimelineDelegationToken(appContext.getAMContainerSpec()); + } + //TODO: YARN-1763:Handle RM failovers during the submitApplication call. rmClient.submitApplication(request); @@ -238,6 +270,48 @@ public YarnClientApplication createApplication() return applicationId; } + private void addTimelineDelegationToken( + ContainerLaunchContext clc) throws YarnException, IOException { + org.apache.hadoop.security.token.Token<TimelineDelegationTokenIdentifier> timelineDelegationToken = + timelineClient.getDelegationToken( + UserGroupInformation.getCurrentUser().getUserName()); + if (timelineDelegationToken == null) { + return; + } + Credentials credentials = new Credentials(); + DataInputByteBuffer dibb = new DataInputByteBuffer(); + ByteBuffer tokens = clc.getTokens(); + if (tokens != null) { + dibb.reset(tokens); + credentials.readTokenStorageStream(dibb); + tokens.rewind(); + } + // If the timeline delegation token is already in the CLC, no need to add + // one more + for (org.apache.hadoop.security.token.Token<? extends TokenIdentifier> token : credentials + .getAllTokens()) { + TokenIdentifier tokenIdentifier = token.decodeIdentifier(); + if (tokenIdentifier instanceof TimelineDelegationTokenIdentifier) { + return; + } + } + credentials.addToken(timelineService, timelineDelegationToken); + if (LOG.isDebugEnabled()) { + LOG.debug("Add timline delegation token into credentials: " + + timelineDelegationToken); + } + DataOutputBuffer dob = new DataOutputBuffer(); + credentials.writeTokenStorageToStream(dob); + tokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); + clc.setTokens(tokens); + } + + @Private + @VisibleForTesting + protected boolean isSecurityEnabled() { + return UserGroupInformation.isSecurityEnabled(); + } + @Override public void killApplication(ApplicationId applicationId) throws YarnException, IOException { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java index cfee6f78d0c86..6407f7a1089e8 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java @@ -25,19 +25,26 @@ import static org.mockito.Mockito.when; import java.io.IOException; +import java.nio.ByteBuffer; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; +import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.junit.Assert; - import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.io.DataInputByteBuffer; +import org.apache.hadoop.io.DataOutputBuffer; +import org.apache.hadoop.security.Credentials; +import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod; +import org.apache.hadoop.security.token.Token; +import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportResponse; @@ -69,19 +76,23 @@ import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.YarnApplicationAttemptState; import org.apache.hadoop.yarn.api.records.YarnApplicationState; +import org.apache.hadoop.yarn.client.api.TimelineClient; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.YarnClientApplication; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.ApplicationIdNotProvidedException; import org.apache.hadoop.yarn.exceptions.YarnException; +import org.apache.hadoop.yarn.security.client.TimelineDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.MiniYARNCluster; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.util.Records; +import org.apache.hadoop.yarn.util.timeline.TimelineUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; +import org.junit.Assert; import org.junit.Test; public class TestYarnClient { @@ -725,4 +736,80 @@ private void testAsyncAPIPollTimeoutHelper(Long valueForTimeout, IOUtils.closeQuietly(client); } } + + @Test + public void testAutomaticTimelineDelegationTokenLoading() + throws Exception { + Configuration conf = new YarnConfiguration(); + conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true); + SecurityUtil.setAuthenticationMethod(AuthenticationMethod.KERBEROS, conf); + final Token<TimelineDelegationTokenIdentifier> dToken = + new Token<TimelineDelegationTokenIdentifier>(); + // crate a mock client + YarnClientImpl client = new YarnClientImpl() { + @Override + protected void serviceInit(Configuration conf) throws Exception { + if (getConfig().getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, + YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED)) { + timelineServiceEnabled = true; + timelineClient = mock(TimelineClient.class); + when(timelineClient.getDelegationToken(any(String.class))) + .thenReturn(dToken); + timelineClient.init(getConfig()); + timelineService = TimelineUtils.buildTimelineTokenService(getConfig()); + } + this.setConfig(conf); + } + + @Override + protected void serviceStart() throws Exception { + rmClient = mock(ApplicationClientProtocol.class); + } + + @Override + protected void serviceStop() throws Exception { + } + + @Override + public ApplicationReport getApplicationReport(ApplicationId appId) { + ApplicationReport report = mock(ApplicationReport.class); + when(report.getYarnApplicationState()) + .thenReturn(YarnApplicationState.SUBMITTED); + return report; + } + + @Override + public boolean isSecurityEnabled() { + return true; + } + }; + client.init(conf); + client.start(); + ApplicationSubmissionContext context = + mock(ApplicationSubmissionContext.class); + ApplicationId applicationId = ApplicationId.newInstance(0, 1); + when(context.getApplicationId()).thenReturn(applicationId); + DataOutputBuffer dob = new DataOutputBuffer(); + Credentials credentials = new Credentials(); + credentials.writeTokenStorageToStream(dob); + ByteBuffer tokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); + ContainerLaunchContext clc = ContainerLaunchContext.newInstance( + null, null, null, null, tokens, null); + when(context.getAMContainerSpec()).thenReturn(clc); + client.submitApplication(context); + // Check whether token is added or not + credentials = new Credentials(); + DataInputByteBuffer dibb = new DataInputByteBuffer(); + tokens = clc.getTokens(); + if (tokens != null) { + dibb.reset(tokens); + credentials.readTokenStorageStream(dibb); + tokens.rewind(); + } + Collection<Token<? extends TokenIdentifier>> dTokens = + credentials.getAllTokens(); + Assert.assertEquals(1, dTokens.size()); + Assert.assertEquals(dToken, dTokens.iterator().next()); + client.stop(); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/timeline/TimelineUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/timeline/TimelineUtils.java index a62ed4869da47..02b5eb4eabdd9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/timeline/TimelineUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/timeline/TimelineUtils.java @@ -19,9 +19,14 @@ package org.apache.hadoop.yarn.util.timeline; import java.io.IOException; +import java.net.InetSocketAddress; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Evolving; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.security.SecurityUtil; +import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.webapp.YarnJacksonJaxbJsonProvider; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; @@ -78,4 +83,26 @@ public static String dumpTimelineRecordtoJSON(Object o, boolean pretty) } } + public static InetSocketAddress getTimelineTokenServiceAddress( + Configuration conf) { + InetSocketAddress timelineServiceAddr = null; + if (YarnConfiguration.useHttps(conf)) { + timelineServiceAddr = conf.getSocketAddr( + YarnConfiguration.TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS, + YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS, + YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_HTTPS_PORT); + } else { + timelineServiceAddr = conf.getSocketAddr( + YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS, + YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_ADDRESS, + YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_PORT); + } + return timelineServiceAddr; + } + + public static Text buildTimelineTokenService(Configuration conf) { + InetSocketAddress timelineServiceAddr = + getTimelineTokenServiceAddress(conf); + return SecurityUtil.buildTokenService(timelineServiceAddr); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineDelegationTokenSecretManagerService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineDelegationTokenSecretManagerService.java index fee9eb41cd80a..2808dac60dae6 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineDelegationTokenSecretManagerService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineDelegationTokenSecretManagerService.java @@ -34,6 +34,7 @@ import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.security.client.TimelineDelegationTokenIdentifier; +import org.apache.hadoop.yarn.util.timeline.TimelineUtils; /** * The service wrapper of {@link TimelineDelegationTokenSecretManager} @@ -65,17 +66,7 @@ protected void serviceInit(Configuration conf) throws Exception { 3600000); secretManager.startThreads(); - if (YarnConfiguration.useHttps(getConfig())) { - serviceAddr = getConfig().getSocketAddr( - YarnConfiguration.TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS, - YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS, - YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_HTTPS_PORT); - } else { - serviceAddr = getConfig().getSocketAddr( - YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS, - YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_ADDRESS, - YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_PORT); - } + serviceAddr = TimelineUtils.getTimelineTokenServiceAddress(getConfig()); super.init(conf); }
5122c892b23298f9faa681aa76d0401f7f5ee236
orientdb
Fixed issue 156 about deep inheritance--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java index 674d49436ba..b0aa582e847 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java @@ -148,12 +148,17 @@ public OGraphElement newInstance(final String iClassName) { else if (iClassName.equals(OGraphEdge.class.getSimpleName())) return new OGraphEdge(this); - final OClass cls = getMetadata().getSchema().getClass(iClassName); - if (cls != null && cls.getSuperClass() != null) { - if (cls.getSuperClass().getName().equals(OGraphVertex.class.getSimpleName())) - return new OGraphVertex(this, iClassName); - else if (cls.getSuperClass().getName().equals(OGraphEdge.class.getSimpleName())) - return new OGraphEdge(this, iClassName); + OClass cls = getMetadata().getSchema().getClass(iClassName); + if (cls != null) { + cls = cls.getSuperClass(); + while (cls != null) { + if (cls.getName().equals(OGraphVertex.class.getSimpleName())) + return new OGraphVertex(this, iClassName); + else if (cls.getName().equals(OGraphEdge.class.getSimpleName())) + return new OGraphEdge(this, iClassName); + + cls = cls.getSuperClass(); + } } throw new OGraphException("Unrecognized class: " + iClassName);
d7929a40521731c53f510996bf9918ff3b158e3d
Delta Spike
DELTASPIKE-378 add ProjectStageAware property handling Main entry point for this feature is ConfigResolver#getProjectStageAwarePropertyValue
a
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java index 43bb6602f..05cbc59df 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java @@ -31,9 +31,11 @@ import javax.enterprise.inject.Typed; +import org.apache.deltaspike.core.api.projectstage.ProjectStage; import org.apache.deltaspike.core.spi.config.ConfigSource; import org.apache.deltaspike.core.spi.config.ConfigSourceProvider; import org.apache.deltaspike.core.util.ClassUtils; +import org.apache.deltaspike.core.util.ProjectStageProducer; import org.apache.deltaspike.core.util.ServiceUtils; /** @@ -56,6 +58,8 @@ public final class ConfigResolver private static Map<ClassLoader, ConfigSource[]> configSources = new ConcurrentHashMap<ClassLoader, ConfigSource[]>(); + private static volatile ProjectStage projectStage = null; + private ConfigResolver() { // this is a utility class which doesn't get instantiated. @@ -146,6 +150,35 @@ public static String getPropertyValue(String key) return null; } + /** + * <p>Search for the configured value in all {@link ConfigSource}s and take the + * current {@link org.apache.deltaspike.core.api.projectstage.ProjectStage} + * into account.</p> + * + * <p>It first will search if there is a configured value of the given key prefixed + * with the current ProjectStage (e.g. 'myproject.myconfig.Production') and if this didn't + * find anything it will lookup the given key without any prefix.</p> + * + * <p><b>Attention</b> This method must only be used after all ConfigSources + * got registered and it also must not be used to determine the ProjectStage itself.</p> + * @param key + * @param defaultValue + * @return the configured value or if non found the defaultValue + * + */ + public static String getProjectStageAwarePropertyValue(String key, String defaultValue) + { + ProjectStage ps = getProjectStage(); + + String value = getPropertyValue(key + '.' + ps, defaultValue); + if (value == null) + { + value = getPropertyValue(key, defaultValue); + } + + return value; + } + /** * Resolve all values for the given key, from all registered ConfigSources ordered by their * ordinal value in ascending ways. If more {@link ConfigSource}s have the same ordinal, their @@ -264,4 +297,17 @@ public int compare(ConfigSource configSource1, ConfigSource configSource2) return configSources; } + private static ProjectStage getProjectStage() + { + if (projectStage == null) + { + synchronized (ConfigResolver.class) + { + projectStage = ProjectStageProducer.getInstance().getProjectStage(); + } + } + + return projectStage; + } + } diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java index ba4ac6b28..f2e39bf53 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java @@ -47,6 +47,7 @@ * } * </pre> * + * <p>Please note that there can only be one ProjectStage per EAR.</p> */ @ApplicationScoped public class ProjectStageProducer implements Serializable diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java index 809ccc1df..70c00e802 100644 --- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java +++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java @@ -19,6 +19,8 @@ package org.apache.deltaspike.test.api.config; import org.apache.deltaspike.core.api.config.ConfigResolver; +import org.apache.deltaspike.core.api.projectstage.ProjectStage; +import org.apache.deltaspike.core.util.ProjectStageProducer; import org.junit.Assert; import org.junit.Test; @@ -50,4 +52,12 @@ public void testStandaloneConfigSource() Assert.assertNull(ConfigResolver.getPropertyValue("notexisting")); Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey")); } + + @Test + public void testGetProjectStageAwarePropertyValue() + { + ProjectStageProducer.setProjectStage(ProjectStage.UnitTest); + Assert.assertNull(ConfigResolver.getProjectStageAwarePropertyValue("notexisting", null)); + Assert.assertEquals("unittestvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey", null)); + } } diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java index 581c837e3..ed9dc8667 100644 --- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java +++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java @@ -33,6 +33,15 @@ public class TestConfigSource implements ConfigSource private int ordinal = 700; + private Map<String, String> props = new HashMap<String, String>(); + + + public TestConfigSource() + { + props.put("testkey", "testvalue"); + props.put("testkey.UnitTest", "unittestvalue"); + } + @Override public String getConfigName() { @@ -48,15 +57,13 @@ public int getOrdinal() @Override public String getPropertyValue(String key) { - return "testkey".equals(key) ? "testvalue" : null; + return props.get(key); } @Override public Map<String, String> getProperties() { - Map<String, String> map = new HashMap<String, String>(); - map.put("testkey", "testvalue"); - return map; + return props; } @Override
1eb43ca4be09336d6354fd7dddb0b19b195e8396
aeshell$aesh
[AESH-257] added postProcessing of commands/options so we can support optionactivators being enhanced by the provider
a
https://github.com/aeshell/aesh
diff --git a/src/main/java/org/jboss/aesh/cl/internal/ProcessedCommand.java b/src/main/java/org/jboss/aesh/cl/internal/ProcessedCommand.java index b46498a97..2bb1a0f1f 100644 --- a/src/main/java/org/jboss/aesh/cl/internal/ProcessedCommand.java +++ b/src/main/java/org/jboss/aesh/cl/internal/ProcessedCommand.java @@ -17,6 +17,7 @@ import org.jboss.aesh.cl.validator.NullCommandValidator; import org.jboss.aesh.cl.validator.OptionValidator; import org.jboss.aesh.console.Config; +import org.jboss.aesh.console.InvocationProviders; import org.jboss.aesh.terminal.TerminalString; import org.jboss.aesh.util.ReflectionUtil; @@ -37,10 +38,12 @@ public final class ProcessedCommand { private List<ProcessedOption> options; private ProcessedOption argument; - public ProcessedCommand(String name, String description, CommandValidator validator) { + public ProcessedCommand(String name, String description, CommandValidator validator, + ResultHandler resultHandler) { setName(name); setDescription(description); setValidator(validator); + setResultHandler(resultHandler); options = new ArrayList<>(); } @@ -171,12 +174,16 @@ public CommandValidator getValidator() { } private void setValidator(CommandValidator validator) { + if(validator == null) + validator = new NullCommandValidator(); this.validator = validator; } public ResultHandler getResultHandler() { return resultHandler; } private void setResultHandler(ResultHandler resultHandler) { + if(resultHandler == null) + resultHandler = new NullResultHandler(); this.resultHandler = resultHandler; } @@ -380,4 +387,9 @@ public boolean hasUniqueLongOption(String optionName) { } return false; } + + public void processAfterInit(InvocationProviders invocationProviders) { + for(ProcessedOption option : options) + option.processAfterInit(invocationProviders); + } } diff --git a/src/main/java/org/jboss/aesh/cl/internal/ProcessedOption.java b/src/main/java/org/jboss/aesh/cl/internal/ProcessedOption.java index 9f2c712a3..6a8469ef0 100644 --- a/src/main/java/org/jboss/aesh/cl/internal/ProcessedOption.java +++ b/src/main/java/org/jboss/aesh/cl/internal/ProcessedOption.java @@ -497,6 +497,10 @@ else if(optionType == OptionType.GROUP) { } } + public void processAfterInit(InvocationProviders invocationProviders) { + activator = invocationProviders.getOptionActivatorProvider().enhanceOptionActivator(activator); + } + private <String, T> Map<String, T> newHashMap() { return new HashMap<>(); } diff --git a/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java b/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java index 0dd2f0f2a..fbbb1e949 100644 --- a/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java +++ b/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java @@ -25,6 +25,7 @@ import org.jboss.aesh.complete.Completion; import org.jboss.aesh.console.command.CommandNotFoundException; import org.jboss.aesh.console.command.CommandResult; +import org.jboss.aesh.console.command.activator.AeshOptionActivatorProvider; import org.jboss.aesh.console.command.activator.OptionActivatorProvider; import org.jboss.aesh.console.command.completer.CompleterInvocationProvider; import org.jboss.aesh.console.command.container.CommandContainer; @@ -79,7 +80,7 @@ public class AeshConsoleImpl implements AeshConsole { console = new Console(settings); console.setConsoleCallback(new AeshConsoleCallbackImpl(this)); console.addCompletion(new AeshCompletion()); - processSettings(settings); + processAfterInit(settings); } @Override @@ -172,11 +173,24 @@ public InputProcessor getInputProcessor() { return console.getInputProcessor(); } - private void processSettings(Settings settings) { + private void processAfterInit(Settings settings) { if (settings.isManEnabled()) { internalRegistry = new AeshInternalCommandRegistry(); internalRegistry.addCommand(new Man(manProvider)); } + if(!(invocationProviders.getOptionActivatorProvider() instanceof AeshOptionActivatorProvider)) { + //we have a custom OptionActivatorProvider, and need to process all options + try { + for (String commandName : registry.getAllCommandNames()) { + registry.getCommand(commandName, "").getParser().getCommand().processAfterInit(invocationProviders); + } + } + catch (CommandNotFoundException e) { + e.printStackTrace(); + } + + + } } private List<String> completeCommandName(String input) {
016918b2e276f95a7e8868dc6cd00fc3ca6fb71c
camel
CAMEL-870: Added transferExchange option to- camel-jms.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@756685 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java index 8c00e9ef54d63..0c2c20116682a 100644 --- a/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java @@ -76,6 +76,9 @@ public class MockEndpoint extends DefaultEndpoint implements BrowsableEndpoint { private String headerName; private Object headerValue; private Object actualHeader; + private String propertyName; + private Object propertyValue; + private Object actualProperty; private Processor reporter; public MockEndpoint(String endpointUri, Component component) { @@ -322,6 +325,24 @@ public void run() { }); } + /** + * Adds an expectation that the given property name & value are received by this + * endpoint + */ + public void expectedPropertyReceived(final String name, final Object value) { + this.propertyName = name; + this.propertyValue = value; + + expects(new Runnable() { + public void run() { + assertTrue("No property with name " + propertyName + " found.", actualProperty != null); + + Object actualValue = getCamelContext().getTypeConverter().convertTo(actualProperty.getClass(), propertyValue); + assertEquals("Property of message", actualValue, actualProperty); + } + }); + } + /** * Adds an expectation that the given body values are received by this * endpoint in the specified order @@ -725,6 +746,10 @@ protected void performAssertions(Exchange exchange) throws Exception { actualHeader = in.getHeader(headerName); } + if (propertyName != null) { + actualProperty = exchange.getProperty(propertyName); + } + if (expectedBodyValues != null) { int index = actualBodyValues.size(); if (expectedBodyValues.size() > index) { diff --git a/components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaPayloadHolder.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultExchangeHolder.java similarity index 72% rename from components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaPayloadHolder.java rename to camel-core/src/main/java/org/apache/camel/impl/DefaultExchangeHolder.java index 1dd038c506fed..6eef003093f7b 100644 --- a/components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaPayloadHolder.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultExchangeHolder.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.camel.component.mina; +package org.apache.camel.impl; import java.io.Serializable; import java.util.LinkedHashMap; @@ -25,28 +25,29 @@ import org.apache.commons.logging.LogFactory; /** - * Holder object for sending an exchange over the wire using the MINA ObjectSerializationCodecFactory codec. - * This is configured using the <tt>transferExchange=true</tt> option for the TCP protocol. + * Holder object for sending an exchange over a remote wire as a serialized object. + * This is usually configured using the <tt>transferExchange=true</tt> option on the endpoint. * <p/> - * As opposed to normal usage of camel-mina where only the body part of the exchange is transfered, this holder - * object serializes the following fields over the wire: + * As opposed to normal usage where only the body part of the exchange is transfered over the wire, + * this holder object serializes the following fields over the wire: * <ul> - * <li>in body</li> - * <li>out body</li> - * <li>in headers</li> - * <li>out headers</li> - * <li>fault body </li> - * <li>fault headers</li> - * <li>exchange properties</li> - * <li>exception</li> + * <li>in body</li> + * <li>out body</li> + * <li>in headers</li> + * <li>out headers</li> + * <li>fault body </li> + * <li>fault headers</li> + * <li>exchange properties</li> + * <li>exception</li> * </ul> * Any object that is not serializable will be skipped and Camel will log this at WARN level. * * @version $Revision$ */ -public class MinaPayloadHolder implements Serializable { +public class DefaultExchangeHolder implements Serializable { + private static final long serialVersionUID = 1L; - private static final transient Log LOG = LogFactory.getLog(MinaPayloadHolder.class); + private static final transient Log LOG = LogFactory.getLog(DefaultExchangeHolder.class); private Object inBody; private Object outBody; @@ -61,11 +62,11 @@ public class MinaPayloadHolder implements Serializable { * Creates a payload object with the information from the given exchange. * Only marshal the Serializable object * - * @param exchange the exchange + * @param exchange the exchange * @return the holder object with information copied form the exchange */ - public static MinaPayloadHolder marshal(Exchange exchange) { - MinaPayloadHolder payload = new MinaPayloadHolder(); + public static DefaultExchangeHolder marshal(Exchange exchange) { + DefaultExchangeHolder payload = new DefaultExchangeHolder(); payload.inBody = checkSerializableObject("in body", exchange.getIn().getBody()); payload.inHeaders.putAll(checkMapSerializableObjects("in headers", exchange.getIn().getHeaders())); @@ -86,10 +87,10 @@ public static MinaPayloadHolder marshal(Exchange exchange) { /** * Transfers the information from the payload to the exchange. * - * @param exchange the exchange to set values from the payload - * @param payload the payload with the values + * @param exchange the exchange to set values from the payload + * @param payload the payload with the values */ - public static void unmarshal(Exchange exchange, MinaPayloadHolder payload) { + public static void unmarshal(Exchange exchange, DefaultExchangeHolder payload) { exchange.getIn().setBody(payload.inBody); exchange.getIn().setHeaders(payload.inHeaders); if (payload.outBody != null) { @@ -107,16 +108,19 @@ public static void unmarshal(Exchange exchange, MinaPayloadHolder payload) { } public String toString() { - return "MinaPayloadHolder{" + "inBody=" + inBody + ", outBody=" + outBody + ", inHeaders=" - + inHeaders + ", outHeaders=" + outHeaders + ", faultBody=" + faultBody + ", faultHeaders=" - + faultHeaders + ", properties=" + properties + ", exception=" + exception + '}'; + StringBuilder sb = new StringBuilder("DefaultExchangeHolder["); + sb.append("inBody=").append(inBody).append(", outBody=").append(outBody); + sb.append(", inHeaders=").append(inHeaders).append(", outHeaders=").append(outHeaders); + sb.append(", faultBody=").append(faultBody).append(", faultHeaders=").append(faultHeaders); + sb.append(", properties=").append(properties).append(", exception=").append(exception); + return sb.append(']').toString(); } private static Object checkSerializableObject(String type, Object object) { if (object instanceof Serializable) { return object; } else { - LOG.warn(type + " containig object " + object + " cannot be serialized, it will be excluded by the MinaPayloadHolder"); + LOG.warn(type + " containig object " + object + " cannot be serialized, it will be excluded by the holder"); return null; } } @@ -132,7 +136,7 @@ private static Map<String, Object> checkMapSerializableObjects(String type, Map< result.put(entry.getKey(), entry.getValue()); } else { LOG.warn(type + " containing object " + entry.getValue() + " of key " + entry.getKey() - + " cannot be serialized, it will be excluded by the MinaPayloadHolder"); + + " cannot be serialized, it will be excluded by the holder"); } } diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java index 21f9eb455b9e2..a176b864e077d 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java @@ -43,6 +43,7 @@ import org.apache.camel.Exchange; import org.apache.camel.RuntimeCamelException; import org.apache.camel.component.file.GenericFile; +import org.apache.camel.impl.DefaultExchangeHolder; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.util.CamelContextHelper; import org.apache.camel.util.ExchangeHelper; @@ -88,7 +89,14 @@ public Object extractBodyFromJms(Exchange exchange, Message message) { try { if (message instanceof ObjectMessage) { ObjectMessage objectMessage = (ObjectMessage)message; - return objectMessage.getObject(); + Object payload = objectMessage.getObject(); + if (payload instanceof DefaultExchangeHolder) { + DefaultExchangeHolder holder = (DefaultExchangeHolder) payload; + DefaultExchangeHolder.unmarshal(exchange, holder); + return exchange.getIn().getBody(); + } else { + return objectMessage.getObject(); + } } else if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage)message; return textMessage.getText(); @@ -194,7 +202,7 @@ public Message makeJmsMessage(Exchange exchange, org.apache.camel.Message camelM } } if (answer == null) { - answer = createJmsMessage(camelMessage.getBody(), camelMessage.getHeaders(), session, exchange.getContext()); + answer = createJmsMessage(exchange, camelMessage.getBody(), camelMessage.getHeaders(), session, exchange.getContext()); appendJmsProperties(answer, exchange, camelMessage); } return answer; @@ -288,9 +296,18 @@ protected Object getValidJMSHeaderValue(String headerName, Object headerValue) { return null; } - protected Message createJmsMessage(Object body, Map<String, Object> headers, Session session, CamelContext context) throws JMSException { + protected Message createJmsMessage(Exchange exchange, Object body, Map<String, Object> headers, Session session, CamelContext context) throws JMSException { JmsMessageType type = null; + // special for transferExchange + if (endpoint != null && endpoint.isTransferExchange()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Option transferExchange=true so we use JmsMessageType: Object"); + } + Serializable holder = DefaultExchangeHolder.marshal(exchange); + return session.createObjectMessage(holder); + } + // check if header have a type set, if so we force to use it if (headers.containsKey(JmsConstants.JMS_MESSAGE_TYPE)) { type = context.getTypeConverter().convertTo(JmsMessageType.class, headers.get(JmsConstants.JMS_MESSAGE_TYPE)); diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConfiguration.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConfiguration.java index 247a5dbba42f3..38cdc5586b451 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConfiguration.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConfiguration.java @@ -133,6 +133,7 @@ public class JmsConfiguration implements Cloneable { private String replyToDestinationSelectorName; private JmsMessageType jmsMessageType; private JmsKeyFormatStrategy jmsKeyFormatStrategy; + private boolean transferExchange; public JmsConfiguration() { } @@ -1165,4 +1166,12 @@ public JmsKeyFormatStrategy getJmsKeyFormatStrategy() { public void setJmsKeyFormatStrategy(JmsKeyFormatStrategy jmsKeyFormatStrategy) { this.jmsKeyFormatStrategy = jmsKeyFormatStrategy; } + + public boolean isTransferExchange() { + return transferExchange; + } + + public void setTransferExchange(boolean transferExchange) { + this.transferExchange = transferExchange; + } } diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java index f3e7500a0c97d..28df7f988e07d 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java @@ -779,6 +779,14 @@ public void setJmsKeyFormatStrategy(JmsKeyFormatStrategy jmsHeaderStrategy) { getConfiguration().setJmsKeyFormatStrategy(jmsHeaderStrategy); } + public boolean isTransferExchange() { + return getConfiguration().isTransferExchange(); + } + + public void setTransferExchange(boolean transferExchange) { + getConfiguration().setTransferExchange(transferExchange); + } + // Implementation methods //------------------------------------------------------------------------- diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsDeadLetterQueueTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsDeadLetterQueueTest.java new file mode 100644 index 0000000000000..f6eb502f91331 --- /dev/null +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsDeadLetterQueueTest.java @@ -0,0 +1,101 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.jms; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; + +/** + * Unit test for using JMS as DLQ + * + * @version $Revision$ + */ +public class JmsDeadLetterQueueTest extends ContextTestSupport { + + protected String getUri() { + return "activemq:queue:dead"; + } + + public void testOk() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("Hello World"); + + template.sendBody("direct:start", "Hello World"); + + assertMockEndpointsSatisfied(); + } + + public void testKabom() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:dead"); + mock.expectedBodiesReceived("Kabom"); + + try { + template.sendBody("direct:start", "Kabom"); + fail("Should have thrown a RuntimeCamelException"); + } catch (RuntimeCamelException e) { + assertEquals("Kabom", e.getCause().getMessage()); + } + + assertMockEndpointsSatisfied(); + + // the cause exception is gone in the transformation below + assertNull(mock.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT)); + + } + + protected CamelContext createCamelContext() throws Exception { + CamelContext camelContext = super.createCamelContext(); + + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory)); + + return camelContext; + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + errorHandler(deadLetterChannel("seda:dead").disableRedelivery()); + + from("direct:start").process(new Processor() { + public void process(Exchange exchange) throws Exception { + String body = exchange.getIn().getBody(String.class); + if ("Kabom".equals(body)) { + throw new IllegalArgumentException("Kabom"); + } + } + }).to("mock:result"); + + from("seda:dead").transform(exceptionMessage()).to(getUri()); + + from(getUri()).to("mock:dead"); + } + }; + } + +} \ No newline at end of file diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsDeadLetterQueueUsingTransferExchangeTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsDeadLetterQueueUsingTransferExchangeTest.java new file mode 100644 index 0000000000000..da85673d5ed59 --- /dev/null +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsDeadLetterQueueUsingTransferExchangeTest.java @@ -0,0 +1,99 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.jms; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; + +/** + * Unit test for using JMS as DLQ and to preserve the Exchange using transferExchange=true option + * + * @version $Revision$ + */ +public class JmsDeadLetterQueueUsingTransferExchangeTest extends ContextTestSupport { + + protected String getUri() { + return "activemq:queue:dead?transferExchange=true"; + } + + public void testOk() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("Hello World"); + + template.sendBody("direct:start", "Hello World"); + + assertMockEndpointsSatisfied(); + } + + public void testKabom() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:dead"); + mock.expectedBodiesReceived("Kabom"); + + try { + template.sendBody("direct:start", "Kabom"); + fail("Should have thrown a RuntimeCamelException"); + } catch (RuntimeCamelException e) { + assertEquals("Kabom", e.getCause().getMessage()); + } + + assertMockEndpointsSatisfied(); + + Exchange dead = mock.getReceivedExchanges().get(0); + // caused exception is stored as a property + assertEquals("Kabom", dead.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class).getMessage()); + } + + protected CamelContext createCamelContext() throws Exception { + CamelContext camelContext = super.createCamelContext(); + + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory)); + + return camelContext; + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + errorHandler(deadLetterChannel(getUri()).disableRedelivery()); + + from("direct:start").process(new Processor() { + public void process(Exchange exchange) throws Exception { + String body = exchange.getIn().getBody(String.class); + if ("Kabom".equals(body)) { + throw new IllegalArgumentException("Kabom"); + } + } + }).to("mock:result"); + + from(getUri()).to("mock:dead"); + } + }; + } + +} \ No newline at end of file diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsTransferExchangeTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsTransferExchangeTest.java new file mode 100644 index 0000000000000..7565714b00e44 --- /dev/null +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsTransferExchangeTest.java @@ -0,0 +1,95 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.jms; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; + +/** + * @version $Revision$ + */ +public class JmsTransferExchangeTest extends ContextTestSupport { + + protected String getUri() { + return "activemq:queue:foo?transferExchange=true"; + } + + public void testBodyOnly() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("Hello World"); + + template.sendBody("direct:start", "Hello World"); + + assertMockEndpointsSatisfied(); + } + + public void testBodyAndHeaderOnly() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("Hello World"); + mock.expectedHeaderReceived("foo", "cheese"); + + template.sendBodyAndHeader("direct:start", "Hello World", "foo", "cheese"); + + assertMockEndpointsSatisfied(); + } + + public void testSendExchange() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("Hello World"); + mock.expectedHeaderReceived("foo", "cheese"); + mock.expectedPropertyReceived("bar", 123); + + template.send("direct:start", new Processor() { + public void process(Exchange exchange) throws Exception { + exchange.getIn().setBody("Hello World"); + exchange.getIn().setHeader("foo", "cheese"); + exchange.setProperty("bar", 123); + } + }); + + assertMockEndpointsSatisfied(); + } + + protected CamelContext createCamelContext() throws Exception { + CamelContext camelContext = super.createCamelContext(); + + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory)); + + return camelContext; + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("direct:start").to(getUri()); + from(getUri()).to("mock:result"); + } + }; + } + +} diff --git a/components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaPayloadHelper.java b/components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaPayloadHelper.java index 7c5a4befbaf21..9cae9e999e3d1 100644 --- a/components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaPayloadHelper.java +++ b/components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaPayloadHelper.java @@ -17,15 +17,15 @@ package org.apache.camel.component.mina; import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchangeHolder; /** * Helper to get and set the correct payload when transfering data using camel-mina. * Always use this helper instead of direct access on the exchange object. * <p/> * This helper ensures that we can also transfer exchange objects over the wire using the - * <tt>exchangePayload=true</tt> option. + * <tt>transferExchange=true</tt> option. * - * @see org.apache.camel.component.mina.MinaPayloadHolder * @version $Revision$ */ public final class MinaPayloadHelper { @@ -37,7 +37,7 @@ private MinaPayloadHelper() { public static Object getIn(MinaEndpoint endpoint, Exchange exchange) { if (endpoint.getConfiguration().isTransferExchange()) { // we should transfer the entire exchange over the wire (includes in/out) - return MinaPayloadHolder.marshal(exchange); + return DefaultExchangeHolder.marshal(exchange); } else { // normal transfer using the body only return exchange.getIn().getBody(); @@ -47,7 +47,7 @@ public static Object getIn(MinaEndpoint endpoint, Exchange exchange) { public static Object getOut(MinaEndpoint endpoint, Exchange exchange) { if (endpoint.getConfiguration().isTransferExchange()) { // we should transfer the entire exchange over the wire (includes in/out) - return MinaPayloadHolder.marshal(exchange); + return DefaultExchangeHolder.marshal(exchange); } else { // normal transfer using the body only return exchange.getOut().getBody(); @@ -55,8 +55,8 @@ public static Object getOut(MinaEndpoint endpoint, Exchange exchange) { } public static void setIn(Exchange exchange, Object payload) { - if (payload instanceof MinaPayloadHolder) { - MinaPayloadHolder.unmarshal(exchange, (MinaPayloadHolder) payload); + if (payload instanceof DefaultExchangeHolder) { + DefaultExchangeHolder.unmarshal(exchange, (DefaultExchangeHolder) payload); } else { // normal transfer using the body only exchange.getIn().setBody(payload); @@ -64,8 +64,8 @@ public static void setIn(Exchange exchange, Object payload) { } public static void setOut(Exchange exchange, Object payload) { - if (payload instanceof MinaPayloadHolder) { - MinaPayloadHolder.unmarshal(exchange, (MinaPayloadHolder) payload); + if (payload instanceof DefaultExchangeHolder) { + DefaultExchangeHolder.unmarshal(exchange, (DefaultExchangeHolder) payload); } else { // normal transfer using the body only and preserve the headers exchange.getOut().setHeaders(exchange.getIn().getHeaders());
f7edaa99bc232ad970faf6369ebc3cf1f6eff70f
camel
added contains() method to the DSL for- .header("foo").contains("cheese") for multi-value headers--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@539516 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/builder/ValueBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ValueBuilder.java index cf8e84ec82147..4e20c97f180d9 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ValueBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ValueBuilder.java @@ -104,6 +104,20 @@ public Predicate<E> isNotNull() { return onNewPredicate(PredicateBuilder.isNotNull(expression)); } + /** + * Create a predicate that the left hand expression contains the value of the right hand expression + * + * @param value the element which is compared to be contained within this expression + * @return a predicate which evaluates to true if the given value expression is contained within this + * expression value + */ + @Fluent + public Predicate<E> contains(@FluentArg("value")Object value) { + Expression<E> right = asExpression(value); + return onNewPredicate(PredicateBuilder.contains(expression, right)); + } + + /** * Creates a predicate which is true if this expression matches the given regular expression *
838009943d082216c5b1b015c644617692d7059c
tapiji
Remove projects that have been contributed to the eclipse babel technology project
a
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.core.pdeutils/.classpath b/org.eclipse.babel.core.pdeutils/.classpath deleted file mode 100644 index 4c62a804..00000000 --- a/org.eclipse.babel.core.pdeutils/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="output" path="bin"/> -</classpath> diff --git a/org.eclipse.babel.core.pdeutils/.project b/org.eclipse.babel.core.pdeutils/.project deleted file mode 100644 index d9a92ce1..00000000 --- a/org.eclipse.babel.core.pdeutils/.project +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.core.pdeutils</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.jdt.core.javabuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.ManifestBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.SchemaBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.core.pdeutils/META-INF/MANIFEST.MF b/org.eclipse.babel.core.pdeutils/META-INF/MANIFEST.MF deleted file mode 100644 index 13ab4e98..00000000 --- a/org.eclipse.babel.core.pdeutils/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Pdeutils -Bundle-SymbolicName: org.eclipse.babel.core.pdeutils -Bundle-Version: 0.8.0.qualifier -Fragment-Host: org.eclipse.babel.core;bundle-version="0.8.0" -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Eclipse-PatchFragment: true -Require-Bundle: org.eclipse.pde.core;bundle-version="3.7.0" diff --git a/org.eclipse.babel.core.pdeutils/about.html b/org.eclipse.babel.core.pdeutils/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.core.pdeutils/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.core.pdeutils/build.properties b/org.eclipse.babel.core.pdeutils/build.properties deleted file mode 100644 index 06134302..00000000 --- a/org.eclipse.babel.core.pdeutils/build.properties +++ /dev/null @@ -1,12 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - org.eclipse.babel.core.pdeutils.jar,\ - about.html -source.org.eclipse.babel.core.pdeutils.jar = src/ -jars.compile.order = org.eclipse.babel.core.pdeutils.jar,\ - . -output.org.eclipse.babel.core.pdeutils.jar = bin/ -source.org.eclipse.babel.core.pdeutils.jar = src/ -src.includes = about.html diff --git a/org.eclipse.babel.core.pdeutils/pom.xml b/org.eclipse.babel.core.pdeutils/pom.xml deleted file mode 100644 index 56fbd79b..00000000 --- a/org.eclipse.babel.core.pdeutils/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.core.pdeutils</artifactId> - <version>0.8.0-SNAPSHOT</version> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file diff --git a/org.eclipse.babel.core.pdeutils/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core.pdeutils/src/org/eclipse/babel/core/util/PDEUtils.java deleted file mode 100644 index a2403c98..00000000 --- a/org.eclipse.babel.core.pdeutils/src/org/eclipse/babel/core/util/PDEUtils.java +++ /dev/null @@ -1,210 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Stefan Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Stefan Reiterer - initial API and implementation - ******************************************************************************/ - -package org.eclipse.babel.core.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.osgi.service.resolver.BundleDescription; -import org.eclipse.osgi.service.resolver.HostSpecification; -import org.eclipse.pde.core.plugin.IFragmentModel; -import org.eclipse.pde.core.plugin.IPluginBase; -import org.eclipse.pde.core.plugin.IPluginModelBase; -import org.eclipse.pde.core.plugin.PluginRegistry; - -public class PDEUtils { - - // The same as PDE.PLUGIN_NATURE, because the PDE provided constant is not accessible (internal class) - private static final String PLUGIN_NATURE = "org.eclipse.pde.PluginNature"; - - public static String getPluginId(IProject project) { - - if (project == null || !isPluginProject(project)) { - return null; - } - - IPluginModelBase pluginModelBase = PluginRegistry.findModel(project); - - if (pluginModelBase == null) { - // plugin not found in registry - return null; - } - - IPluginBase pluginBase = pluginModelBase.getPluginBase(); - - return pluginBase.getId(); - } - - public static boolean isFragment(IProject pluginProject) { - if (pluginProject == null) { - return false; - } - - IPluginModelBase pModel = PluginRegistry.findModel(pluginProject); - - if (pModel == null) { - // this project is not a plugin/fragment - return false; - } - - return pModel.isFragmentModel(); - } - - public static List<IProject> getFragments(IProject hostProject) { - // Check preconditions - String hostId = getPluginId(hostProject); - if (hostProject == null || hostId == null) { - // no valid host project given. - return Collections.emptyList(); - } - - // Get the fragments of the host project - IPluginModelBase pModelBase = PluginRegistry.findModel(hostProject); - BundleDescription desc = pModelBase.getBundleDescription(); - - ArrayList<IPluginModelBase> fragmentModels = new ArrayList<IPluginModelBase>(); - if (desc == null) { - // There is no bundle description for the host project - return Collections.emptyList(); - } - - BundleDescription[] f = desc.getFragments(); - for (BundleDescription candidateDesc : f) { - IPluginModelBase candidate = PluginRegistry.findModel(candidateDesc); - if (candidate instanceof IFragmentModel) { - fragmentModels.add(candidate); - } - } - - // Get the fragment project which is in the current workspace - ArrayList<IProject> fragments = getFragmentsAsWorkspaceProjects(hostProject, fragmentModels); - - return fragments; - } - - public static String getFragmentId(IProject project, String hostPluginId) { - if (!isFragment(project) || hostPluginId == null) { - return null; - } - - IPluginModelBase pluginModelBase = PluginRegistry.findModel(project); - if (pluginModelBase instanceof IFragmentModel) { - IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase; - BundleDescription description = fragmentModel.getBundleDescription(); - HostSpecification hostSpecification = description.getHost(); - - if (hostPluginId.equals(hostSpecification.getName())) { - return getPluginId(project); - } - } - return null; - } - - public static IProject getFragmentHost(IProject fragment) { - if (!isFragment(fragment)) { - return null; - } - - IPluginModelBase pluginModelBase = PluginRegistry.findModel(fragment); - if (pluginModelBase instanceof IFragmentModel) { - IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase; - BundleDescription description = fragmentModel.getBundleDescription(); - HostSpecification hostSpecification = description.getHost(); - - IPluginModelBase hostProject = PluginRegistry.findModel(hostSpecification.getName()); - IProject[] projects = fragment.getWorkspace().getRoot().getProjects(); - ArrayList<IProject> hostProjects = getPluginProjects(Arrays.asList(hostProject), projects); - - if (hostProjects.size() != 1) { - // hostproject not in workspace - return null; - } else { - return hostProjects.get(0); - } - } - - return null; - } - - /** - * Returns all project containing plugin/fragment of the specified project. - * If the specified project itself is a fragment, then only this is - * returned. - * - * @param pluginProject - * the plugin project - * @return the all project containing a fragment or null if none - */ - public static IProject[] lookupFragment(IProject pluginProject) { - if (isFragment(pluginProject) && pluginProject.isOpen()) { - return new IProject[] {pluginProject}; - } - - IProject[] workspaceProjects = pluginProject.getWorkspace().getRoot().getProjects(); - String hostPluginId = getPluginId(pluginProject); - - if (hostPluginId == null) { - // project is not a plugin project - return null; - } - - List<IProject> fragmentProjects = new ArrayList<IProject>(); - for (IProject project : workspaceProjects) { - if (!project.isOpen() || getFragmentId(project, hostPluginId) == null) { - // project is not open or it is no fragment where given project is the host project. - continue; - } - fragmentProjects.add(project); - } - - if (fragmentProjects.isEmpty()) { - return null; - } - - return fragmentProjects.toArray(new IProject[0]); - } - - private static ArrayList<IProject> getFragmentsAsWorkspaceProjects(IProject hostProject, ArrayList<IPluginModelBase> fragmentModels) { - IProject[] projects = hostProject.getWorkspace().getRoot().getProjects(); - - ArrayList<IProject> fragments = getPluginProjects(fragmentModels, projects); - - return fragments; - } - - private static ArrayList<IProject> getPluginProjects(List<IPluginModelBase> fragmentModels, IProject[] projects) { - ArrayList<IProject> fragments = new ArrayList<IProject>(); - for (IProject project : projects) { - IPluginModelBase pModel = PluginRegistry.findModel(project); - - if (fragmentModels.contains(pModel)) { - fragments.add(project); - } - } - - return fragments; - } - - private static boolean isPluginProject(IProject project) { - try { - return project.hasNature(PLUGIN_NATURE); - } catch (CoreException ce) { - //Logger.logError(ce); - } - return false; - } - -} \ No newline at end of file diff --git a/org.eclipse.babel.core/.classpath b/org.eclipse.babel.core/.classpath deleted file mode 100644 index 3a95b200..00000000 --- a/org.eclipse.babel.core/.classpath +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src/"/> - <classpathentry kind="output" path="target/classes"/> -</classpath> - diff --git a/org.eclipse.babel.core/.cvsignore b/org.eclipse.babel.core/.cvsignore deleted file mode 100644 index 60b00fed..00000000 --- a/org.eclipse.babel.core/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -bin -.settings diff --git a/org.eclipse.babel.core/.project b/org.eclipse.babel.core/.project deleted file mode 100644 index dfe6f27c..00000000 --- a/org.eclipse.babel.core/.project +++ /dev/null @@ -1,41 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.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> - <buildCommand> - <name>org.eclipse.babel.editor.rbeBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - <nature>org.eclipse.babel.editor.rbeNature</nature> - </natures> -</projectDescription> - diff --git a/org.eclipse.babel.core/META-INF/CVS/Entries b/org.eclipse.babel.core/META-INF/CVS/Entries deleted file mode 100644 index d6fdf829..00000000 --- a/org.eclipse.babel.core/META-INF/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -/MANIFEST.MF/1.5/Fri Aug 14 19:53:04 2009// diff --git a/org.eclipse.babel.core/META-INF/CVS/Repository b/org.eclipse.babel.core/META-INF/CVS/Repository deleted file mode 100644 index a89dff2f..00000000 --- a/org.eclipse.babel.core/META-INF/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.core/META-INF diff --git a/org.eclipse.babel.core/META-INF/CVS/Root b/org.eclipse.babel.core/META-INF/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.core/META-INF/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.core/META-INF/MANIFEST.MF b/org.eclipse.babel.core/META-INF/MANIFEST.MF deleted file mode 100644 index 12fba4db..00000000 --- a/org.eclipse.babel.core/META-INF/MANIFEST.MF +++ /dev/null @@ -1,36 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -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.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.manager;uses:="org.eclipse.core.resources,org.eclipselabs.tapiji.translator.rbe.babel.bundle", - 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, - 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.refactoring, - 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.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 -Eclipse-ExtensibleAPI: true -Bundle-ClassPath: org.eclipse.babel.core.pdeutils.jar, - . - diff --git a/org.eclipse.babel.core/build.properties b/org.eclipse.babel.core/build.properties deleted file mode 100644 index 580b822b..00000000 --- a/org.eclipse.babel.core/build.properties +++ /dev/null @@ -1,14 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - org.eclipse.babel.core.pdeutils.jar,\ - plugin.xml,\ - schema/ -src.includes = src/,\ - schema/,\ - plugin.xml,\ - META-INF/ -source.org.eclipse.babel.core.pedutils.jar = -jars.compile.order = org.eclipse.babel.core.pedutils.jar,\ - . diff --git a/org.eclipse.babel.core/plugin.xml b/org.eclipse.babel.core/plugin.xml deleted file mode 100644 index 788e3c79..00000000 --- a/org.eclipse.babel.core/plugin.xml +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?eclipse version="3.4"?> -<plugin> - <extension-point id="babelConfiguration" name="babelConfiguration.exsd" schema="schema/babelConfiguration.exsd"/> - <extension-point id="refactoringService" name="refactoringService.exsd" schema="schema/refactoringService.exsd"/> -</plugin> diff --git a/org.eclipse.babel.core/pom.xml b/org.eclipse.babel.core/pom.xml deleted file mode 100644 index d7712084..00000000 --- a/org.eclipse.babel.core/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.core</artifactId> - <version>0.8.0-SNAPSHOT</version> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> - - <properties> - <tycho-version>0.16.0</tycho-version> - </properties> - - <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> - </plugins> - </build> - - <repositories> - <!-- configure p2 repository to resolve against --> - <repository> - <id>indigo</id> - <layout>p2</layout> - <url>http://download.eclipse.org/releases/indigo/</url> - </repository> - </repositories> -</project> \ No newline at end of file diff --git a/org.eclipse.babel.core/schema/babelConfiguration.exsd b/org.eclipse.babel.core/schema/babelConfiguration.exsd deleted file mode 100644 index 97a39619..00000000 --- a/org.eclipse.babel.core/schema/babelConfiguration.exsd +++ /dev/null @@ -1,119 +0,0 @@ -<?xml version='1.0' encoding='UTF-8'?> -<!-- Schema file written by PDE --> -<schema targetNamespace="org.eclipse.babel.core" xmlns="http://www.w3.org/2001/XMLSchema"> -<annotation> - <appinfo> - <meta.schema plugin="org.eclipse.babel.core" id="babelConfiguration" name="babelConfiguration"/> - </appinfo> - <documentation> - Xpt, which is implemented by TapiJI to provide access to TapiJIPreferences. - </documentation> - </annotation> - - <element name="extension"> - <annotation> - <appinfo> - <meta.element /> - </appinfo> - </annotation> - <complexType> - <sequence> - <element ref="IConfiguration"/> - </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="IConfiguration"> - <complexType> - <attribute name="class" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - <appinfo> - <meta.attribute kind="java" basedOn=":org.eclipse.babel.core.configuration.IConfiguration"/> - </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.core/schema/refactoringService.exsd b/org.eclipse.babel.core/schema/refactoringService.exsd deleted file mode 100644 index 14e22404..00000000 --- a/org.eclipse.babel.core/schema/refactoringService.exsd +++ /dev/null @@ -1,119 +0,0 @@ -<?xml version='1.0' encoding='UTF-8'?> -<!-- Schema file written by PDE --> -<schema targetNamespace="refactoringService" xmlns="http://www.w3.org/2001/XMLSchema"> -<annotation> - <appinfo> - <meta.schema plugin="refactoringService" id="refactoringService" name="refactoringService"/> - </appinfo> - <documentation> - Xpt, which is implemented by TapiJI to provide a class, which executes the refactoring operation of keys. - </documentation> - </annotation> - - <element name="extension"> - <annotation> - <appinfo> - <meta.element /> - </appinfo> - </annotation> - <complexType> - <sequence> - <element ref="IRefactoringService"/> - </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="IRefactoringService"> - <complexType> - <attribute name="class" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - <appinfo> - <meta.attribute kind="java" basedOn=":org.eclipse.babel.tapiji.tools.core.ui.refactoring.IRefactoringService"/> - </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.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java deleted file mode 100644 index 628f04cb..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 - */ -public class ConfigurationManager { - - private static ConfigurationManager INSTANCE; - - private IConfiguration config; - - private IPropertiesSerializerConfig serializerConfig; - - private IPropertiesDeserializerConfig deserializerConfig; - - private final static IConfiguration DEFAULT_CONFIG = new IConfiguration() { - @Override - public String getNonRbPattern() { - return "^(.)*/build\\.properties:true;^(.)*/config\\.properties:true;^(.)*/targetplatform/(.)*:true"; - } - - @Override - public boolean getAuditSameValue() { - return false; - } - - @Override - public boolean getAuditResource() { - return false; - } - - @Override - public boolean getAuditRb() { - return false; - } - - @Override - public boolean getAuditMissingValue() { - return false; - } - - @Override - public boolean getAuditMissingLanguage() { - return false; - } - }; - - 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 DEFAULT_CONFIG; - } - - /** - * @return The singleton instance - */ - public static ConfigurationManager getInstance() { - if (INSTANCE == null) { - INSTANCE = new ConfigurationManager(); - } - 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 deleted file mode 100644 index b45d117d..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 - // 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.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java deleted file mode 100644 index a629827c..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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(); - -} 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 deleted file mode 100644 index 308feddf..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index e2b05884..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.IMessagesBundleGroup; -import org.eclipse.babel.core.message.internal.MessagesBundleGroup; -import org.eclipse.babel.core.message.strategy.PropertiesFileGroupStrategy; -import org.eclipse.core.resources.IResource; - -/** - * 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) { - - File ioFile = new File(resource.getRawLocation().toFile().getPath()); - - return new MessagesBundleGroup(new PropertiesFileGroupStrategy(ioFile, - ConfigurationManager.getInstance().getSerializerConfig(), - ConfigurationManager.getInstance().getDeserializerConfig())); - } -} 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 deleted file mode 100644 index 88aaa525..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API - * 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 deleted file mode 100644 index 273a438c..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API - * 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 deleted file mode 100644 index 446a0d40..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java +++ /dev/null @@ -1,200 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API - * 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); - - /** - * Renames a key in all messages bundles forming this group. - * - * @param sourceKey - * the message key to rename - * @param targetKey - * the new message name - */ - void renameMessageKeys(String sourceKey, String targetKey); -} 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 deleted file mode 100644 index 172e2550..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesResourceChangeListener.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.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/checks/IMessageCheck.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.java deleted file mode 100644 index 41fc1d8d..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/IMessageCheck.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.eclipse.babel.core.message.checks; - -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 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.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 deleted file mode 100644 index 7ef4cd1c..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/DuplicateValueCheck.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.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 deleted file mode 100644 index 6c613255..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/MissingValueCheck.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.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 deleted file mode 100644 index 6b6563ae..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/internal/SimilarValueCheck.java +++ /dev/null @@ -1,82 +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.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/checks/proximity/IProximityAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.java deleted file mode 100644 index aa0ac6fc..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/IProximityAnalyzer.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.eclipse.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.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.java deleted file mode 100644 index 4b86c745..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/LevenshteinDistanceAnalyzer.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.eclipse.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.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java deleted file mode 100644 index f035cee5..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/checks/proximity/WordCountAnalyzer.java +++ /dev/null @@ -1,72 +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.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.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 deleted file mode 100644 index 7065bd0a..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractIFileChangeListener.java +++ /dev/null @@ -1,95 +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.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 deleted file mode 100644 index 990e9c4b..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/AbstractMessageModel.java +++ /dev/null @@ -1,237 +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 - * 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 deleted file mode 100644 index 2328b048..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleGroupListener.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.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 deleted file mode 100644 index 1f430e76..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/IMessagesBundleListener.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.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 deleted file mode 100644 index 0bee1bc6..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/Message.java +++ /dev/null @@ -1,211 +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 - * 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 deleted file mode 100644 index 5961cfe2..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessageException.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.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 deleted file mode 100644 index 21a4cdba..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundle.java +++ /dev/null @@ -1,409 +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 - * 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 deleted file mode 100644 index 3c9059ca..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleAdapter.java +++ /dev/null @@ -1,56 +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.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 deleted file mode 100644 index 68c37357..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java +++ /dev/null @@ -1,626 +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 - * 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]); - } - } - - if (this.projectName != null) { - 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) { - MessagesBundle mb = (MessagesBundle) messagesBundle; - if (localeBundles.containsKey(mb.getLocale())) { - int oldBundleCount = localeBundles.size(); - - localeBundles.remove(mb.getLocale()); - firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount, - localeBundles.size()); - fireMessagesBundleRemoved(mb); - } - - // 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 - int oldKeyCount = keys.size(); - keys.remove(keyToRemove); - firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size()); - fireKeyRemoved(keyToRemove); - } - } - } - - public void removeMessagesBundle(Locale locale) { - removeMessagesBundle(getMessagesBundle(locale)); - } - - /** - * 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 deleted file mode 100644 index edbc9e85..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroupAdapter.java +++ /dev/null @@ -1,87 +0,0 @@ -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 deleted file mode 100644 index 2455a890..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.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 deleted file mode 100644 index a0a7bdae..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index c3a11e42..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java +++ /dev/null @@ -1,590 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.core.message.manager; - -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 java.util.logging.Level; -import java.util.logging.Logger; - -import org.eclipse.babel.core.configuration.DirtyHack; -import org.eclipse.babel.core.factory.MessagesBundleGroupFactory; -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.refactoring.IRefactoringService; -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.IProject; -import org.eclipse.core.resources.IResource; -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.Platform; - -/** - * 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.ui.nature"; - - private static Logger logger = Logger.getLogger(RBManager.class - .getSimpleName()); - - private static IRefactoringService refactorService; - - private RBManager() { - resourceBundles = new HashMap<String, IMessagesBundleGroup>(); - editorListeners = new ArrayList<IMessagesEditorListener>(3); - resourceListeners = new ArrayList<IResourceDeltaListener>(2); - } - - /** - * @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(resourceBundleId); - } - } - - /** - * @return All the names of the <code>resourceBundles</code> in the format: - * <projectName>/<resourceBundleId> - */ - public List<String> getMessagesBundleGroupNames() { - List<String> bundleGroupNames = new ArrayList<String>(); - - 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() { - List<String> bundleGroupNames = new ArrayList<String>(); - - for (IProject project : getAllSupportedProjects()) { - RBManager manager = getInstance(project); - for (String name : manager.getMessagesBundleGroupNames()) { - if (!bundleGroupNames.contains(name)) { - bundleGroupNames.add(name); - } - } - } - return bundleGroupNames; - } - - /** - * 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 notifyMessagesBundleGroupCreated( - IMessagesBundleGroup bundleGroup) { - if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) { - IMessagesBundleGroup oldbundleGroup = resourceBundles - .get(bundleGroup.getResourceBundleId()); - - // not the same object - if (!equalHash(oldbundleGroup, bundleGroup)) { - // 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); - - 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 - // do not need -> read only phenomenon - 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 - logger.log(Level.INFO, - "dispose: " + bundleGroup.getResourceBundleId()); - - bundleGroup.dispose(); - } - } - } else { - resourceBundles.put(bundleGroup.getResourceBundleId(), bundleGroup); - - logger.log(Level.INFO, "add: " + bundleGroup.getResourceBundleId()); - } - } - - /** - * Notification, that a {@link IMessagesBundleGroup} has been deleted! - * - * @param bundleGroup - * The {@link IMessagesBundleGroup} to remove - */ - public void notifyMessagesBundleGroupDeleted( - IMessagesBundleGroup bundleGroup) { - if (resourceBundles.containsKey(bundleGroup.getResourceBundleId())) { - if (equalHash( - resourceBundles.get(bundleGroup.getResourceBundleId()), - bundleGroup)) { - resourceBundles.remove(bundleGroup.getResourceBundleId()); - - 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 resourceBundleId = NameUtils.getResourceBundleId(resourceBundle); - - IMessagesBundleGroup bundleGroup = resourceBundles - .get(resourceBundleId); - - if (bundleGroup != null) { - 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) { - notifyMessagesBundleGroupDeleted(bundleGroup); - } - } - - // TODO: maybe save and reinit the editor? - - } - - /** - * Because BABEL-Builder does not work correctly (adds 1 x and removes 2 x - * the SAME {@link MessagesBundleGroup}!) - * - * @param oldBundleGroup - * {@link IMessagesBundleGroup} - * @param newBundleGroup - * {@link IMessagesBundleGroup} - * @return <code>true</code> if same {@link IMessagesBundleGroup}, else - * <code>false</code> - */ - private boolean equalHash(IMessagesBundleGroup oldBundleGroup, - IMessagesBundleGroup newBundleGroup) { - return oldBundleGroup.hashCode() == newBundleGroup.hashCode(); - } - - /** - * 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 - - 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); - - } - - /** - * If TapiJI needs to delete sth. - * - * @param resourceBundleId - * The resourceBundleId - */ - public void deleteMessagesBundleGroup(String resourceBundleId) { - // TODO: Try to unify it some time - if (resourceBundles.containsKey(resourceBundleId)) { - resourceBundles.remove(resourceBundleId); - } else { - logger.log(Level.SEVERE, - "deleteMessagesBundleGroup with non-existing Id: " - + resourceBundleId); - } - } - - /** - * @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 synchronized 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(); - - refactorService = getRefactoringService(); - } - - 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 : 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)) { - return getInstance(PDEUtils.getFragmentHost(project)); - } else { - return getInstance(project); - } - } - } - return null; - } - - /** - * @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.isOpen() && (ignoreNature || p.hasNature(TAPIJI_NATURE))) { - projs.add(p); - } - } catch (CoreException e) { - 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()); - } - } - - /** - * 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) { - 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 = 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 void writeToFile(IMessagesBundleGroup bundleGroup) { - for (IMessagesBundle bundle : bundleGroup.getMessagesBundles()) { - FileUtils.writeToFile(bundle); - fireResourceChanged(bundle); - } - } - - private static IRefactoringService getRefactoringService() { - IExtensionPoint extp = Platform.getExtensionRegistry() - .getExtensionPoint( - "org.eclipse.babel.core" + ".refactoringService"); - IConfigurationElement[] elements = extp.getConfigurationElements(); - - if (elements.length != 0) { - try { - return (IRefactoringService) elements[0] - .createExecutableExtension("class"); - } catch (CoreException e) { - e.printStackTrace(); - } - } - return null; - } - - public static IRefactoringService getRefactorService() { - return refactorService; - } -} 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 deleted file mode 100644 index fdf3ac51..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java +++ /dev/null @@ -1,160 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * Alexej Strelzow - detection if isResourceBundleFile - ******************************************************************************/ - -package org.eclipse.babel.core.message.manager; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.StringTokenizer; - -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.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 RBManager manager = null; - - public ResourceBundleDetectionVisitor(RBManager manager) { - this.manager = manager; - } - - public boolean visit(IResource resource) throws CoreException { - try { - if (isResourceBundleFile(resource)) { - manager.addBundleResource(resource); - return false; - } else - return true; - } catch (Exception e) { - e.printStackTrace(); - 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.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")) { - 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(); - if (configuration != null) { - return convertStringToList(configuration.getNonRbPattern()); - } else { - return new ArrayList<CheckItem>(); - } - } - - 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.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 deleted file mode 100644 index fb839c49..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/IMessagesResource.java +++ /dev/null @@ -1,86 +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.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/internal/AbstractMessagesResource.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.java deleted file mode 100644 index 8d48ce27..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractMessagesResource.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.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 deleted file mode 100644 index 13153830..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/AbstractPropertiesResource.java +++ /dev/null @@ -1,81 +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.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 deleted file mode 100644 index cc382768..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesFileResource.java +++ /dev/null @@ -1,192 +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.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 deleted file mode 100644 index 058be453..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesIFileResource.java +++ /dev/null @@ -1,156 +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.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 deleted file mode 100644 index 08e1b290..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/internal/PropertiesReadOnlyResource.java +++ /dev/null @@ -1,97 +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.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 deleted file mode 100644 index 13c8bd8b..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 { - - /** - * Defaults true. - * - * @return Returns the unicodeUnescapeEnabled. - */ - boolean isUnicodeUnescapeEnabled(); - -} \ No newline at end of file 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 deleted file mode 100644 index 3a6fcba6..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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. */ - 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.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 deleted file mode 100644 index 7a78106d..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java +++ /dev/null @@ -1,272 +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.ser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Locale; - -import org.eclipse.babel.core.message.IMessage; -import org.eclipse.babel.core.message.IMessagesBundle; -import org.eclipse.babel.core.message.internal.Message; -import org.eclipse.babel.core.message.internal.MessagesBundle; -import org.eclipse.babel.core.util.BabelUtils; - -/** - * Class responsible for deserializing {@link Properties}-like text into a - * {@link MessagesBundle}. - * - * @author Pascal Essiembre ([email protected]) - */ -public class PropertiesDeserializer { - - /** System line separator. */ - private static final String SYSTEM_LINE_SEPARATOR = System - .getProperty("line.separator"); //$NON-NLS-1$ - - /** Characters accepted as key value separators. */ - private static final String KEY_VALUE_SEPARATORS = "=:"; //$NON-NLS-1$ - - /** MessagesBundle deserializer configuration. */ - private IPropertiesDeserializerConfig config; - - /** - * Constructor. - */ - public PropertiesDeserializer(IPropertiesDeserializerConfig config) { - super(); - this.config = config; - } - - /** - * Parses a string and populates a <code>MessagesBundle</code>. The string - * is expected to match the documented structure of a properties file. - * - * @param messagesBundle - * the target {@link MessagesBundle} - * @param properties - * the string containing the properties to parse - */ - public void deserialize(IMessagesBundle messagesBundle, String properties) { - Locale locale = messagesBundle.getLocale(); - - Collection<String> oldKeys = new ArrayList<String>( - Arrays.asList(messagesBundle.getKeys())); - Collection<String> newKeys = new ArrayList<String>(); - - String[] lines = properties.split("\r\n|\r|\n"); //$NON-NLS-1$ - - boolean doneWithFileComment = false; - StringBuffer fileComment = new StringBuffer(); - StringBuffer lineComment = new StringBuffer(); - StringBuffer lineBuf = new StringBuffer(); - for (int i = 0; i < lines.length; i++) { - String line = lines[i]; - lineBuf.setLength(0); - lineBuf.append(line); - - int equalPosition = findKeyValueSeparator(line); - boolean isRegularLine = line.matches("^[^#].*"); //$NON-NLS-1$ - boolean isCommentedLine = doneWithFileComment - && line.matches("^##[^#].*"); //$NON-NLS-1$ - - // parse regular and commented lines - if (equalPosition >= 1 && (isRegularLine || isCommentedLine)) { - doneWithFileComment = true; - String comment = ""; //$NON-NLS-1$ - if (lineComment.length() > 0) { - comment = lineComment.toString(); - lineComment.setLength(0); - } - - if (isCommentedLine) { - lineBuf.delete(0, 2); // remove ## - equalPosition -= 2; - } - String backslash = "\\"; //$NON-NLS-1$ - while (lineBuf.lastIndexOf(backslash) == lineBuf.length() - 1) { - int lineBreakPosition = lineBuf.lastIndexOf(backslash); - lineBuf.replace(lineBreakPosition, lineBreakPosition + 1, - ""); //$NON-NLS-1$ - if (++i < lines.length) { - String wrappedLine = lines[i].replaceFirst("^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$ - if (isCommentedLine) { - lineBuf.append(wrappedLine.replaceFirst("^##", "")); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - lineBuf.append(wrappedLine); - } - } - } - String key = lineBuf.substring(0, equalPosition).trim(); - key = unescapeKey(key); - - String value = lineBuf.substring(equalPosition + 1) - .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$ - // Unescape leading spaces - if (value.startsWith("\\ ")) { //$NON-NLS-1$ - value = value.substring(1); - } - - if (this.config != null && config.isUnicodeUnescapeEnabled()) { - key = convertEncodedToUnicode(key); - value = convertEncodedToUnicode(value); - } else { - value = value.replaceAll("\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$ - value = value.replaceAll("\\\\n", "\n"); //$NON-NLS-1$//$NON-NLS-2$ - } - IMessage entry = messagesBundle.getMessage(key); - if (entry == null) { - entry = new Message(key, locale); - messagesBundle.addMessage(entry); - } - entry.setActive(!isCommentedLine); - entry.setComment(comment); - entry.setText(value); - newKeys.add(key); - // parse comment line - } else if (lineBuf.indexOf("#") == 0) { //$NON-NLS-1$ - if (!doneWithFileComment) { - fileComment.append(lineBuf); - fileComment.append(SYSTEM_LINE_SEPARATOR); - } else { - lineComment.append(lineBuf); - lineComment.append(SYSTEM_LINE_SEPARATOR); - } - // handle blank or unsupported line - } else { - doneWithFileComment = true; - } - } - oldKeys.removeAll(newKeys); - messagesBundle - .removeMessages(oldKeys.toArray(BabelUtils.EMPTY_STRINGS)); - messagesBundle.setComment(fileComment.toString()); - } - - /** - * Converts encoded &#92;uxxxx to unicode chars and changes special saved - * chars to their original forms - * - * @param str - * the string to convert - * @return converted string - * @see java.util.Properties - */ - private String convertEncodedToUnicode(String str) { - char aChar; - int len = str.length(); - StringBuffer outBuffer = new StringBuffer(len); - - for (int x = 0; x < len;) { - aChar = str.charAt(x++); - if (aChar == '\\' && x + 1 <= len) { - aChar = str.charAt(x++); - if (aChar == 'u' && x + 4 <= len) { - // Read the xxxx - int value = 0; - for (int i = 0; i < 4; i++) { - aChar = str.charAt(x++); - switch (aChar) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - value = (value << 4) + aChar - '0'; - break; - case 'a': - case 'b': - case 'c': - case 'd': - case 'e': - case 'f': - value = (value << 4) + 10 + aChar - 'a'; - break; - case 'A': - case 'B': - case 'C': - case 'D': - case 'E': - case 'F': - value = (value << 4) + 10 + aChar - 'A'; - break; - default: - value = aChar; - System.err.println("PropertiesDeserializer: " //$NON-NLS-1$ - + "bad character " //$NON-NLS-1$ - + "encoding for string:" //$NON-NLS-1$ - + str); - } - } - outBuffer.append((char) value); - } else { - if (aChar == 't') { - aChar = '\t'; - } else if (aChar == 'r') { - aChar = '\r'; - } else if (aChar == 'n') { - aChar = '\n'; - } else if (aChar == 'f') { - aChar = '\f'; - } else if (aChar == 'u') { - outBuffer.append("\\"); //$NON-NLS-1$ - } - outBuffer.append(aChar); - } - } else { - outBuffer.append(aChar); - } - } - return outBuffer.toString(); - } - - /** - * Finds the separator symbol that separates keys and values. - * - * @param str - * the string on which to find seperator - * @return the separator index or -1 if no separator was found - */ - private int findKeyValueSeparator(String str) { - int index = -1; - int length = str.length(); - for (int i = 0; i < length; i++) { - char currentChar = str.charAt(i); - if (currentChar == '\\') { - i++; - } else if (KEY_VALUE_SEPARATORS.indexOf(currentChar) != -1) { - index = i; - break; - } - } - return index; - } - - private String unescapeKey(String key) { - int length = key.length(); - StringBuffer buf = new StringBuffer(); - for (int index = 0; index < length; index++) { - char currentChar = key.charAt(index); - if (currentChar != '\\') { - buf.append(currentChar); - } - } - return buf.toString(); - } - -} - diff --git a/org.eclipse.babel.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 deleted file mode 100644 index bc1aa5ae..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesSerializer.java +++ /dev/null @@ -1,398 +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.ser; - -import java.util.Arrays; -import java.util.Properties; - -import org.eclipse.babel.core.message.IMessage; -import org.eclipse.babel.core.message.IMessagesBundle; -import org.eclipse.babel.core.message.internal.MessagesBundle; - -/** - * 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 &#92;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.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 deleted file mode 100644 index c8f3b457..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/IMessagesBundleGroupStrategy.java +++ /dev/null @@ -1,70 +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 - * Alexej Strelzow - TapJI integration, messagesBundleId - ******************************************************************************/ -package org.eclipse.babel.core.message.strategy; - -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; - -/** - * 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.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 deleted file mode 100644 index 8aff394e..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java +++ /dev/null @@ -1,210 +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 - * Alexej Strelzow - TapJI integration, messagesBundleId - ******************************************************************************/ -package org.eclipse.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.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.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; - -/** - * 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"); - if (index == -1) - return ""; - 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 NameUtils.getResourceBundleId(f); - } - - 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); - - if (file != null) { - return ResourcesPlugin.getWorkspace().getRoot() - .getProject(file.getFullPath().segments()[0]).getName(); - } else { - return null; - } - - } - - // 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.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 deleted file mode 100644 index 3b0cbb36..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.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/IKeyTreeNode.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java deleted file mode 100644 index 552774d3..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.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 deleted file mode 100644 index 5bdd8089..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeVisitor.java +++ /dev/null @@ -1,27 +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; - -/** - * 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/TreeType.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java deleted file mode 100644 index c2e771c1..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 8e242b70..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/AbstractKeyTreeModel.java +++ /dev/null @@ -1,376 +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 - * 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 deleted file mode 100644 index 34af800e..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/IKeyTreeModelListener.java +++ /dev/null @@ -1,35 +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.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 deleted file mode 100644 index 9c9d982b..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/internal/KeyTreeNode.java +++ /dev/null @@ -1,234 +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.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 deleted file mode 100644 index 9dc96eb9..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/IKeyCheck.java +++ /dev/null @@ -1,34 +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.visitor; - -import org.eclipse.babel.core.message.internal.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.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 deleted file mode 100644 index bdf51f74..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/KeyCheckVisitor.java +++ /dev/null @@ -1,110 +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.visitor; - -import java.util.ArrayList; -import java.util.Collection; - -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; - -/** - * 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.internal.tree.visitor.IKeyTreeVisitor - * #visitKeyTreeNode(org.eclipse.babel.core.message.internal.tree.internal.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.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 deleted file mode 100644 index 9098a643..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/visitor/NodePathRegexVisitor.java +++ /dev/null @@ -1,81 +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.visitor; - -import java.util.ArrayList; -import java.util.List; - -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. - * - * @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.internal.tree.visitor.IKeyTreeVisitor - * #visitKeyTreeNode(org.eclipse.babel.core.message.internal.tree.internal.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.eclipse.babel.core/src/org/eclipse/babel/core/refactoring/IRefactoringService.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/refactoring/IRefactoringService.java deleted file mode 100644 index 31ddb0a8..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/refactoring/IRefactoringService.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.core.refactoring; - -import java.util.Locale; - -import org.eclipse.babel.core.message.manager.RBManager; -import org.eclipse.core.resources.IFile; - -/** - * Service class, which can be used to execute key refactorings. This can be - * retrieved via:<br> - * {@link RBManager#getRefactorService()} - * - * @author Alexej Strelzow - */ -public interface IRefactoringService { - - /** - * Executes following steps:<br> - * <ol> - * <li>Changes the {@link CompilationUnit}s, which must be changed</li> - * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> - * <li>Displays the summary dialog</li> - * </ol> - * <br> - * - * @param projectName - * The project the resource bundle is in. - * @param resourceBundleId - * The resource bundle, which contains the key to be refactored. - * @param selectedLocale - * The selected {@link Locale} to change. - * @param oldKey - * The old key name - * @param newKey - * The new key name, which should overwrite the old one - * @param enumPath - * The path of the enum file to change - */ - void refactorKey(String projectName, String resourceBundleId, - String selectedLocale, String oldKey, String newKey, String enumName); - - /** - * Executes following steps:<br> - * <ol> - * <li>Displays the initial refactoring dialog</li> - * <li>Changes the {@link CompilationUnit}s, which must be changed</li> - * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> - * <li>Displays the summary dialog</li> - * </ol> - * <br> - * - * @param projectName - * The project the resource bundle is in. - * @param resourceBundleId - * The resource bundle, which contains the key to be refactored. - * @param selectedLocale - * The selected {@link Locale} to change. - * @param oldKey - * The old key name - * @param newKey - * The new key name, which should overwrite the old one - * @param enumPath - * The path of the enum file to change - */ - void openRefactorDialog(String projectName, String resourceBundleId, - String oldKey, String enumName); - - /** - * Executes following steps:<br> - * <ol> - * <li>Displays the initial refactoring dialog</li> - * <li>Changes the {@link CompilationUnit}s, which must be changed</li> - * <li>Changes the data mgmt. (backend -> {@link RBManager})</li> - * <li>Displays the summary dialog</li> - * </ol> - * <br> - * - * @param file - * The file, of the editor input - * @param selectionOffset - * The position of the cursor - */ - void openRefactorDialog(IFile file, int selectionOffset); -} diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java deleted file mode 100644 index 5aeb8379..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/BabelUtils.java +++ /dev/null @@ -1,107 +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.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.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.java deleted file mode 100644 index a550bcee..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileChangeListener.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.eclipse.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.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.java deleted file mode 100644 index 38a727cd..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileMonitor.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.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.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java deleted file mode 100644 index 784cdb15..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 6920ff76..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java deleted file mode 100644 index 521fe415..00000000 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Stefan Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Stefan Reiterer - initial API and implementation - ******************************************************************************/ - -package org.eclipse.babel.core.util; - -import java.util.Collections; -import java.util.List; - -import org.eclipse.core.resources.IProject; - -/** - * This class provides common functionality to access eclipse plug-in - * properties. - * - * NOTE: Eclipse PDE core dependency is optional. Without PDE installed, the - * methods of this class return null or empty data structures. (It is not usual - * to manage eclipse plug-in projects, without PDE installed. - * - * NOTE: The real implementation of this class is in the fragment - * org.eclipse.babel.core.pdeutils. - * - * @author stefan - * - */ -public class PDEUtils { - - /** - * Get the project's plug-in Id if the given project is an eclipse plug-in. - * - * @param project - * the workspace project. - * @return the project's plug-in Id. Null if the project is no plug-in - * project. - */ - public static String getPluginId(IProject project) { - return null; - } - - /** - * Check if the given plug-in project is a fragment. - * - * @param pluginProject - * the plug-in project in the workspace. - * @return true if it is a fragment, otherwise false. - */ - public static boolean isFragment(IProject pluginProject) { - return false; - } - - /** - * Get all fragments for the given host project. - * - * @param hostProject - * the host plug-in project in the workspace. - * @return a list of all fragment projects for the given host project which - * are in the same workspace as the host project. - */ - public static List<IProject> getFragments(IProject hostProject) { - return Collections.emptyList(); - } - - /** - * 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) { - 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) { - return null; - } - - public static IProject[] lookupFragment(IProject fragment) { - return null; - } - -} diff --git a/org.eclipse.babel.editor.nls/.project b/org.eclipse.babel.editor.nls/.project deleted file mode 100644 index 194dcc2a..00000000 --- a/org.eclipse.babel.editor.nls/.project +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.editor.nls</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.pde.ManifestBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.SchemaBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - </natures> -</projectDescription> - diff --git a/org.eclipse.babel.editor.nls/META-INF/CVS/Entries b/org.eclipse.babel.editor.nls/META-INF/CVS/Entries deleted file mode 100644 index 34ce4862..00000000 --- a/org.eclipse.babel.editor.nls/META-INF/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -/MANIFEST.MF/1.2/Fri Aug 14 19:53:03 2009// diff --git a/org.eclipse.babel.editor.nls/META-INF/CVS/Repository b/org.eclipse.babel.editor.nls/META-INF/CVS/Repository deleted file mode 100644 index a4fe293f..00000000 --- a/org.eclipse.babel.editor.nls/META-INF/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor.nls/META-INF diff --git a/org.eclipse.babel.editor.nls/META-INF/CVS/Root b/org.eclipse.babel.editor.nls/META-INF/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor.nls/META-INF/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor.nls/META-INF/MANIFEST.MF b/org.eclipse.babel.editor.nls/META-INF/MANIFEST.MF deleted file mode 100644 index 03c96dfb..00000000 --- a/org.eclipse.babel.editor.nls/META-INF/MANIFEST.MF +++ /dev/null @@ -1,6 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Babel Nls Fragment -Bundle-SymbolicName: org.eclipse.babel.editor.nls -Bundle-Version: 0.8.0.qualifier -Fragment-Host: org.eclipse.babel.editor;bundle-version="[0.8,1.0)" diff --git a/org.eclipse.babel.editor.nls/about.html b/org.eclipse.babel.editor.nls/about.html deleted file mode 100644 index c258ef55..00000000 --- a/org.eclipse.babel.editor.nls/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.editor.nls/build.properties b/org.eclipse.babel.editor.nls/build.properties deleted file mode 100644 index 5db3b7e1..00000000 --- a/org.eclipse.babel.editor.nls/build.properties +++ /dev/null @@ -1,8 +0,0 @@ -bin.includes = META-INF/,\ - nl/,\ - plugin_fr.properties,\ - about.html -src.includes = nl/,\ - plugin_fr.properties,\ - about.html - diff --git a/org.eclipse.babel.editor.nls/nl/CVS/Entries b/org.eclipse.babel.editor.nls/nl/CVS/Entries deleted file mode 100644 index 9c1bedc5..00000000 --- a/org.eclipse.babel.editor.nls/nl/CVS/Entries +++ /dev/null @@ -1,8 +0,0 @@ -D/de//// -D/es//// -D/fr//// -D/it//// -D/ja//// -D/nn//// -D/no//// -D/pt//// diff --git a/org.eclipse.babel.editor.nls/nl/CVS/Repository b/org.eclipse.babel.editor.nls/nl/CVS/Repository deleted file mode 100644 index d53a77e8..00000000 --- a/org.eclipse.babel.editor.nls/nl/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor.nls/nl diff --git a/org.eclipse.babel.editor.nls/nl/CVS/Root b/org.eclipse.babel.editor.nls/nl/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor.nls/nl/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor.nls/nl/fr/CVS/Entries b/org.eclipse.babel.editor.nls/nl/fr/CVS/Entries deleted file mode 100644 index 00bf2b16..00000000 --- a/org.eclipse.babel.editor.nls/nl/fr/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -/messages.properties/1.6/Tue Jan 29 03:51:55 2008// diff --git a/org.eclipse.babel.editor.nls/nl/fr/CVS/Repository b/org.eclipse.babel.editor.nls/nl/fr/CVS/Repository deleted file mode 100644 index 60c52403..00000000 --- a/org.eclipse.babel.editor.nls/nl/fr/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor.nls/nl/fr diff --git a/org.eclipse.babel.editor.nls/nl/fr/CVS/Root b/org.eclipse.babel.editor.nls/nl/fr/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor.nls/nl/fr/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor.nls/nl/fr/messages.properties b/org.eclipse.babel.editor.nls/nl/fr/messages.properties deleted file mode 100644 index af50cb54..00000000 --- a/org.eclipse.babel.editor.nls/nl/fr/messages.properties +++ /dev/null @@ -1,119 +0,0 @@ -#Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) - -dialog.add.body = Ajouter la cl\u00E9 suivante : -dialog.add.head = Ajouter une cl\u00E9. -dialog.delete.body.multiple = \u00CAtes-vous s\u00FBr de vouloir effacer toutes les cl\u00E9s du group \u00AB {0} \u00BB? -dialog.delete.body.single = \u00CAtes-vous s\u00FBr de vouloir effacer \u00AB {0} \u00BB ? -dialog.delete.head.multiple = Effacer un groupe de cl\u00E9s -dialog.delete.head.single = Effacer une cl\u00E9 -dialog.duplicate.body.multiple = Dupliquer le group de cl\u00E9s \u00AB {0} \u00BB \u00E0 (tout les cl\u00E9s sousjacente vont \u00EAtre dupliqu\u00E9es) : -dialog.duplicate.body.single = Dupliquer \u00AB {0} \u00BB \u00E0: -dialog.duplicate.head.multiple = Dupliquer un groupe de cl\u00E9s -dialog.duplicate.head.single = Dupliquer une cl\u00E9 -dialog.error.exists = Cette cl\u00E9 esiste déjà. -dialog.identical.body = Ci-dessous sont les cl\u00E9s ayant des valeurs identique \u00E0 la cl\u00E9 \u00AB {0} \u00BB pour le locale \u00AB {1} \u00BB : -dialog.identical.head = Valeur(s) id(s) trouv\u00E9e(s). -dialog.rename.body.multiple = Renommer le group de cl\u00E9s \u00AB {0} \u00BB \u00E0 (tout les cl\u00E9s sousjacente vont \u00EAtre renomm\u00E9es) : -dialog.rename.body.single = Renommer \u00AB {0} \u00BB \u00E0: -dialog.rename.head.multiple = Renommer un groupe de cl\u00E9s -dialog.rename.head.single = Renommer une cl\u00E9 -dialog.similar.body = Ci-dessous sont les cl\u00E9s ayant des valeurs similaires \u00E0 la cl\u00E9 \u00AB {0} \u00BB pour le locale \u00AB {1} \u00BB : -dialog.similar.head = Valeur(s) similaire(s) trouv\u00E9e(s). - -editor.content.desc = \u00C9diteur pour le ResourceBundle : -editor.default = d\u00E9faut -editor.i18nentry.rootlocale.label = d\u00E9faut -editor.i18nentry.resourcelocation = Endroit de la resource : {0} -editor.new.create = Cr\u00E9er -editor.new.tab = Nouveau... -editor.new.title = Nouveau fichier de propri\u00E9t\u00E9s : -editor.properties = Propri\u00E9t\u00E9s -editor.readOnly = lecture seulement -editor.wiz.add = Ajouter --> -editor.wiz.browse = Naviguer... -editor.wiz.bundleName = Nom de base: -editor.wiz.creating = Cr\u00E9ation de -editor.wiz.desc = Cet assistant cr\u00E9er un ensemble de nouveau fichiers avec l'extension *.properties qui peuvent \u00EAtre ouverts par l'\u00E9diteur de ResourceBundle. -editor.wiz.error.bundleName = Le nom de base doit \u00EAtre sp\u00E9cifi\u00E9. -editor.wiz.error.container = Le conteneur du fichier doit \u00EAtre sp\u00E9cifi\u00E9. -editor.wiz.error.extension = Vous ne pouvez sp\u00E9cifier un extension. Il sera ajouter pour vous. -editor.wiz.folder = &Dossier: -editor.wiz.opening = Ouverture de fichiers de propri\u00E9t\u00E9s pour \u00E9dition... -editor.wiz.remove = <-- Supprimer -editor.wiz.selectFolder = S\u00E9lectionner un dossier -editor.wiz.selected = Locales s\u00E9lection\u00E9es -editor.wiz.title = ResourceBundle (Fichiers de propri\u00E9t\u00E9s) - -error.init.badencoding = Malformed \\uxxxx encoding found in this string: -error.init.ui = Impossible d'initializer unes composante visuelle. -error.newfile.cannotCreate = Impossible de cr\u00E9er un nouveau fichier. -error.newfile.cannotOpen = Impossible d'ouvrir le nouveau fichier. -error.seeLogs = Voir le fichier journal. - -key.add = &Ajouter -key.collapseAll = &Fermer tous -key.comment = Co&mmenter -key.delete = &Supprimer -key.duplicate = Du&pliquer -key.expandAll = &Ouvrir tous -key.layout.flat = Plat -key.layout.tree = Arborescence -key.rename = &Renommer -key.uncomment = &D\u00E9commenter - -prefs.alignEquals = Aligner les symboles d'\u00E9gals -prefs.convertEncoded = Convertir les valeurs \\uXXXX \u00E0 unicode lors de la lecture de fichiers de propri\u00E9t\u00E9s -prefs.convertUnicode = Convertir les valeurs unicode \u00E0 \\uXXXX -prefs.convertUnicode.upper = Utiliser des lettres majuscules pour les lettres hexadecimales -prefs.fieldTabInserts = La touche de tabulation ins\u00E8re une tabulation dans les champs textes localis\u00E9s -prefs.filterLocales.label = Locales affich\u00E9es: -prefs.filterLocales.tooltip = List des locales \u00E0 afficher, s\u00E9par\u00E9es par des virgules, '*' et '?' sont accept\u00E9s. -prefs.groupAlignEquals = Aligner les symboles d'\u00E9gal \u00E0 l'int\u00E9rieur des groupes -prefs.groupKeys = Grouper les cl\u00E9s -prefs.groupSep = S\u00E9parateur pour groupes de cl\u00E9s : -prefs.keepEmptyFields = Garder les cl\u00E9s sans valeurs -prefs.keysSorted = Trier les cl\u00E9s -prefs.keyTree.expanded = L'arborescence des cl\u00E9s est d\u00E9velopp\u00E9 par d\u00E9faut -prefs.keyTree.hierarchical = L'arborescence des cl\u00E9s est hi\u00E9rarchique par d\u00E9faut -prefs.levelDeep = Combien de niveau profond : -prefs.levelDeep.error = Le champ 'Combien de niveau profond' doit \u00EAtre num\u00E9rique -prefs.linesBetween = Combien de lignes entre les groupes : -prefs.linesBetween.error = Le champ 'Combien de lignes entre les groupes' doit \u00EAtre num\u00E9rique -prefs.newline.force = Forcer le style des nouvelles lignes: -prefs.newline.nice = Couper les lignes apr\u00E8s les caract\u00E8res de nouvelles lignes -prefs.perform.duplVals = Rapporter les cl\u00E9s partageant des valeurs identiques pour le m\u00EAme locale -prefs.perform.intro1 = Les fonctionalit\u00E9s suivantes peuvent avoir un impacte significatif sur la performance -prefs.perform.intro2 = Particuli\u00E8rement sur de larges fichiers. Utilisez-les avec dicernement -prefs.perform.missingVals = Rapporter les cl\u00E9s manquant une ou plusieurs valeurs -prefs.perform.simVals = Rapporter les cl\u00E9s partageant des valeurs similaires pour le m\u00EAme locale -prefs.perform.simVals.levensthein = Utiliser la distance Levensthein -prefs.perform.simVals.precision = Niveau de pr\u00E9cision (entre 0 et 1) : -prefs.perform.simVals.precision.error = Le niveau de pr\u00E9cision doit \u00EAtre entre 0 et 1 -prefs.perform.simVals.wordCount = Utiliser le compte des mots identiques -prefs.perform.message.ignore = Ignorer -prefs.perform.message.info = Info -prefs.perform.message.warning = Attention -prefs.perform.message.error = Erreur -prefs.removeAlreadyInstalledValidators.title = Retirer les validateurs d\u00E9ja install\u00E9s -prefs.removeAlreadyInstalledValidators.text = Voulez-vous retirer les validateurs d\u00E9ja install\u00E9s? -prefs.setupValidationBuilderAutomatically = Ajouter automatiquement le validateur sur les projets java -prefs.showGeneratedBy = Afficher le commentaire d'en-t\u00EAte "Generated By..." (affichez votre support!) -prefs.spacesAroundEquals = Au moins un espace chaque c\u00F4t\u00E9 des symboles d'\u00E9gal -prefs.supportNL = Supporter la structure "nl" d'Eclipse pour l'internationalization des rustines -prefs.wrapAlignEquals = Aligner les lignes coup\u00E9es avec les symboles d'\u00E9gal -prefs.wrapIndent = Combien d'espaces \u00E0 utiliser pour l'indentation : -prefs.wrapIndent.error = Le champ 'Combien d'espace \u00E0 utiliser...' doit \u00EAtre num\u00E9rique -prefs.wrapLines = Couper les longues lignes -prefs.wrapLinesChar = Couper les lignes apr\u00E8s combien de caract\u00E8res : -prefs.wrapLinesChar.error = Le champ 'Couper les lignes apr\u00E8s...' doit \u00EAtre num\u00E9rique - -selector.country = Pays -selector.language = Lang. -selector.title = Choisir ou entrer un \u00AB Locale \u00BB. -selector.variant = Variante - -value.comment.tooltip = Cocher pour commenter cette entr\u00E9e. -value.duplicate.tooltip = Valeurs identiques trouv\u00E9s. Cliquer pour plus de d\u00E9tails. -value.goto.tooltip = Cliquer pour aller au fichier de propri\u00E9t\u00E9s correspondant. -value.similar.tooltip = Valeurs similaires trouv\u00E9s. Cliquer pour plus de d\u00E9tails. -value.uncomment.tooltip = D\u00E9cocher pour d\u00E9commenter cette entr\u00E9e. diff --git a/org.eclipse.babel.editor.nls/plugin_fr.properties b/org.eclipse.babel.editor.nls/plugin_fr.properties deleted file mode 100644 index e9907781..00000000 --- a/org.eclipse.babel.editor.nls/plugin_fr.properties +++ /dev/null @@ -1,12 +0,0 @@ -editor.title = \u00C9diteur de Messages - -plugin.name = Rustine \u00C9diteur de Messages -plugin.provider = Eclipse - -prefs.formatting = Format -prefs.performance = Performance - -wizard.category = Éditeur de messages - -wizard.rb.description = Cr\u00E9er un ou plusieurs groupes de fichiers de propri\u00E9t\u00E9s. -wizard.rb.title = ResourceBundle diff --git a/org.eclipse.babel.editor.nls/pom.xml b/org.eclipse.babel.editor.nls/pom.xml deleted file mode 100644 index 7bdbb01c..00000000 --- a/org.eclipse.babel.editor.nls/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.editor.nls</artifactId> - <version>0.8.0-SNAPSHOT</version> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file diff --git a/org.eclipse.babel.editor.swt.compat/.classpath b/org.eclipse.babel.editor.swt.compat/.classpath deleted file mode 100644 index ad32c83a..00000000 --- a/org.eclipse.babel.editor.swt.compat/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> diff --git a/org.eclipse.babel.editor.swt.compat/.project b/org.eclipse.babel.editor.swt.compat/.project deleted file mode 100644 index 5c03016e..00000000 --- a/org.eclipse.babel.editor.swt.compat/.project +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.editor.swt.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> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.editor.swt.compat/META-INF/MANIFEST.MF b/org.eclipse.babel.editor.swt.compat/META-INF/MANIFEST.MF deleted file mode 100644 index 7700da35..00000000 --- a/org.eclipse.babel.editor.swt.compat/META-INF/MANIFEST.MF +++ /dev/null @@ -1,13 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: RCP Compatibility for Babel Editor -Bundle-SymbolicName: org.eclipse.babel.editor.swt.compat -Bundle-Version: 0.8.0.qualifier -Bundle-Activator: org.eclipse.babel.editor.swt.compat.Activator -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: org.eclipse.swt, - org.eclipse.swt.widgets, - org.eclipse.ui.forms, - org.eclipse.ui.forms.widgets, - org.osgi.framework;version="1.3.0" -Export-Package: org.eclipse.babel.editor.compat diff --git a/org.eclipse.babel.editor.swt.compat/build.properties b/org.eclipse.babel.editor.swt.compat/build.properties deleted file mode 100644 index 34d2e4d2..00000000 --- a/org.eclipse.babel.editor.swt.compat/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/org.eclipse.babel.editor.swt.compat/pom.xml b/org.eclipse.babel.editor.swt.compat/pom.xml deleted file mode 100644 index 7153ff37..00000000 --- a/org.eclipse.babel.editor.swt.compat/pom.xml +++ /dev/null @@ -1,13 +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> - <groupId>org.eclipse.babel.editor</groupId> - <artifactId>org.eclipse.babel.editor.rcp.compat</artifactId> - <version>0.8.0-SNAPSHOT</version> - <packaging>eclipse-plugin</packaging> - <parent> - <groupId>org.eclipse.babel.tapiji.tools</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> - </parent> -</project> \ No newline at end of file diff --git a/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/compat/SwtRapCompatibilityFormToolkit.java b/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/compat/SwtRapCompatibilityFormToolkit.java deleted file mode 100644 index e7365ee2..00000000 --- a/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/compat/SwtRapCompatibilityFormToolkit.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Matthias Lettmayer - initial API and implementation - ******************************************************************************/ -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 SwtRapCompatibilityFormToolkit extends FormToolkit { - - public SwtRapCompatibilityFormToolkit(FormColors colors) { - super(colors); - } - - public SwtRapCompatibilityFormToolkit(Display display) { - super(display); - } -} diff --git a/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/compat/SwtRapCompatibilitySWT.java b/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/compat/SwtRapCompatibilitySWT.java deleted file mode 100644 index 5ae30c0f..00000000 --- a/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/compat/SwtRapCompatibilitySWT.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Matthias Lettmayer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.editor.compat; - -import org.eclipse.swt.SWT; - -public class SwtRapCompatibilitySWT extends SWT { - -} diff --git a/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/swt/compat/Activator.java b/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/swt/compat/Activator.java deleted file mode 100644 index c771b3d4..00000000 --- a/org.eclipse.babel.editor.swt.compat/src/org/eclipse/babel/editor/swt/compat/Activator.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Matthias Lettmayer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.editor.swt.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.swt/.classpath b/org.eclipse.babel.editor.swt/.classpath deleted file mode 100644 index ad32c83a..00000000 --- a/org.eclipse.babel.editor.swt/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> diff --git a/org.eclipse.babel.editor.swt/.project b/org.eclipse.babel.editor.swt/.project deleted file mode 100644 index d35cf687..00000000 --- a/org.eclipse.babel.editor.swt/.project +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.editor.swt</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.swt/META-INF/MANIFEST.MF b/org.eclipse.babel.editor.swt/META-INF/MANIFEST.MF deleted file mode 100644 index fe123772..00000000 --- a/org.eclipse.babel.editor.swt/META-INF/MANIFEST.MF +++ /dev/null @@ -1,10 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: RCP fragment for the Babel Editor -Bundle-SymbolicName: org.eclipse.babel.editor.swt;singleton:=true -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 -Export-Package: org.eclipse.babel.editor.internal diff --git a/org.eclipse.babel.editor.swt/OSGI-INF/l10n/bundle.properties b/org.eclipse.babel.editor.swt/OSGI-INF/l10n/bundle.properties deleted file mode 100644 index 25bd92c2..00000000 --- a/org.eclipse.babel.editor.swt/OSGI-INF/l10n/bundle.properties +++ /dev/null @@ -1,2 +0,0 @@ -#Properties file for org.eclipse.babel.editor.swt -command.name = Refactor... \ No newline at end of file diff --git a/org.eclipse.babel.editor.swt/build.properties b/org.eclipse.babel.editor.swt/build.properties deleted file mode 100644 index 4664e356..00000000 --- a/org.eclipse.babel.editor.swt/build.properties +++ /dev/null @@ -1,6 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - fragment.xml,\ - OSGI-INF/l10n/bundle.properties diff --git a/org.eclipse.babel.editor.swt/fragment.xml b/org.eclipse.babel.editor.swt/fragment.xml deleted file mode 100644 index d8e3cc80..00000000 --- a/org.eclipse.babel.editor.swt/fragment.xml +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?eclipse version="3.4"?> -<fragment> - <extension - point="org.eclipse.ui.handlers"> - <handler - class="org.eclipse.babel.editor.refactoring.RefactoringHandler" - commandId="org.eclipse.babel.editor.command.refactoring"> - </handler> - </extension> - <extension - point="org.eclipse.ui.commands"> - <command - id="org.eclipse.babel.editor.command.refactoring" - name="%command.name"> - </command> - </extension> - <extension - point="org.eclipse.ui.bindings"> - <key - commandId="org.eclipse.babel.editor.command.refactoring" - schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - sequence="M1+R"> - </key> - </extension> -</fragment> diff --git a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/i18n/I18NEntry.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/i18n/I18NEntry.java deleted file mode 100644 index 09a3459e..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/i18n/I18NEntry.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Pascal Essiembre, Alexej Strelow, Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Pascal Essiembre - initial API and implementation - * Alexej Strelzow - updateKey - * Matthias Lettmayer - extracted I18NEntry into own class for SWT specific implementation - ******************************************************************************/ -package org.eclipse.babel.editor.i18n; - -import java.util.Locale; - -import org.eclipse.babel.core.message.IMessage; -import org.eclipse.babel.core.message.IMessagesBundleGroup; -import org.eclipse.babel.core.util.BabelUtils; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.widgets.Composite; - -public class I18NEntry extends AbstractI18NEntry { - - public I18NEntry(Composite parent, AbstractMessagesEditor editor, - Locale locale) { - super(parent, editor, locale); - } - - @Override - void updateKey(String key) { - IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); - 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); - } - } - - @Override - KeyListener getKeyListener() { - return 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); - // } - // } - // - // }); - // } - } -} diff --git a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/internal/MessagesEditor.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/internal/MessagesEditor.java deleted file mode 100644 index a5203e6e..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/internal/MessagesEditor.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Pascal Essiembre, Alexej Strelzow, Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 - * Matthias Lettmayer - extracted messages editor into own class for SWT specific implementation - ******************************************************************************/ - -package org.eclipse.babel.editor.internal; - -import org.eclipse.babel.core.message.internal.IMessagesBundleGroupListener; -import org.eclipse.babel.core.message.internal.MessagesBundle; -import org.eclipse.babel.core.message.internal.MessagesBundleGroupAdapter; -import org.eclipse.ui.editors.text.TextEditor; -import org.eclipse.ui.texteditor.ITextEditor; - -public class MessagesEditor extends AbstractMessagesEditor { - - @Override - protected IMessagesBundleGroupListener getMsgBundleGroupListner() { - return new MessagesBundleGroupAdapter() { - @Override - public void messagesBundleAdded(MessagesBundle messagesBundle) { - addMessagesBundle(messagesBundle); - } - }; - } - - @Override - protected void initRAP() { - // nothing to do - } - - @Override - protected void disposeRAP() { - // nothing to do - } - - @Override - public void setEnabled(boolean enabled) { - i18nPage.setEnabled(enabled); - for (ITextEditor textEditor : textEditorsIndex) { - // TODO disable editors - } - } - -} diff --git a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RefactoringHandler.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RefactoringHandler.java deleted file mode 100644 index cfc74401..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RefactoringHandler.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.editor.refactoring; - -import org.eclipse.babel.core.message.internal.MessagesBundleGroup; -import org.eclipse.babel.core.message.manager.RBManager; -import org.eclipse.babel.core.message.tree.internal.AbstractKeyTreeModel; -import org.eclipse.babel.core.message.tree.internal.KeyTreeNode; -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeItem; -import org.eclipse.swt.widgets.Widget; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.ISelectionService; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.part.FileEditorInput; - -/** - * Handler for the key binding M1 (= Ctrl) + R. This handler triggers the - * refactoring process. - * - * @author Alexej Strelzow - */ -public class RefactoringHandler extends AbstractHandler { - - /** - * Gets called if triggered - * - * @param event - * The {@link ExecutionEvent} - */ - public Object execute(ExecutionEvent event) throws ExecutionException { - - Event e = ((Event) event.getTrigger()); - Widget widget = e.widget; - - ISelectionService selectionService = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow().getSelectionService(); - ISelection selection = selectionService.getSelection(); - - if (selection instanceof TextSelection && widget instanceof StyledText) { // Java-File - TextSelection txtSel = (TextSelection) selection; - IEditorPart activeEditor = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow().getActivePage() - .getActiveEditor(); - FileEditorInput input = (FileEditorInput) activeEditor - .getEditorInput(); - IFile file = input.getFile(); - - RBManager.getRefactorService().openRefactorDialog(file, - txtSel.getOffset()); - } - - if (widget != null && widget instanceof Tree) { // Messages-Editor or - // TapiJI-View - Tree tree = (Tree) widget; - TreeItem[] treeItems = tree.getSelection(); - if (treeItems.length == 1) { - TreeItem item = treeItems[0]; - Object data = item.getData(); - String oldKey = item.getText(); - if (data != null && data instanceof KeyTreeNode) { - oldKey = ((KeyTreeNode)data).getMessageKey(); - } - if (tree.getData() instanceof AbstractKeyTreeModel) { - AbstractKeyTreeModel model = (AbstractKeyTreeModel) tree - .getData(); - MessagesBundleGroup messagesBundleGroup = model - .getMessagesBundleGroup(); - String projectName = messagesBundleGroup.getProjectName(); - String resourceBundleId = messagesBundleGroup - .getResourceBundleId(); - - RBManager.getRefactorService().openRefactorDialog( - projectName, resourceBundleId, oldKey, null); - - } - } - } - - return null; - } - -} diff --git a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java deleted file mode 100644 index ba647968..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyArguments.java +++ /dev/null @@ -1,82 +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.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.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java deleted file mode 100644 index f30272eb..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyChange.java +++ /dev/null @@ -1,183 +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.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.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java deleted file mode 100644 index 168b6185..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyDescriptor.java +++ /dev/null @@ -1,150 +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.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.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java deleted file mode 100644 index d477287d..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyProcessor.java +++ /dev/null @@ -1,311 +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.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.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java deleted file mode 100644 index 8cad851b..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/refactoring/RenameKeyWizard.java +++ /dev/null @@ -1,189 +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.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.swt/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java b/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java deleted file mode 100644 index 091b4c92..00000000 --- a/org.eclipse.babel.editor.swt/src/org/eclipse/babel/editor/tree/actions/RenameKeyAction.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Pascal Essiembre, Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Pascal Essiembre - initial API and implementation - * Matthias Lettmayer - extracted RenameKeyAction into own class for SWT specific implementation - ******************************************************************************/ -package org.eclipse.babel.editor.tree.actions; - -import org.eclipse.babel.core.message.tree.internal.KeyTreeNode; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -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(AbstractMessagesEditor 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/.classpath b/org.eclipse.babel.editor/.classpath deleted file mode 100644 index 3a95b200..00000000 --- a/org.eclipse.babel.editor/.classpath +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src/"/> - <classpathentry kind="output" path="target/classes"/> -</classpath> - diff --git a/org.eclipse.babel.editor/.cvsignore b/org.eclipse.babel.editor/.cvsignore deleted file mode 100644 index 60b00fed..00000000 --- a/org.eclipse.babel.editor/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -bin -.settings diff --git a/org.eclipse.babel.editor/.project b/org.eclipse.babel.editor/.project deleted file mode 100644 index 1edb7667..00000000 --- a/org.eclipse.babel.editor/.project +++ /dev/null @@ -1,40 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.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> - <buildCommand> - <name>org.eclipse.babel.editor.rbeBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - <nature>org.eclipse.babel.editor.rbeNature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.editor/.settings/CVS/Entries b/org.eclipse.babel.editor/.settings/CVS/Entries deleted file mode 100644 index cd182531..00000000 --- a/org.eclipse.babel.editor/.settings/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -/org.eclipse.jdt.core.prefs/1.1/Sun Aug 17 17:51:19 2008// diff --git a/org.eclipse.babel.editor/.settings/CVS/Repository b/org.eclipse.babel.editor/.settings/CVS/Repository deleted file mode 100644 index 79c60ddf..00000000 --- a/org.eclipse.babel.editor/.settings/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/.settings diff --git a/org.eclipse.babel.editor/.settings/CVS/Root b/org.eclipse.babel.editor/.settings/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/.settings/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/CHANGES b/org.eclipse.babel.editor/CHANGES deleted file mode 100644 index c0637ecf..00000000 --- a/org.eclipse.babel.editor/CHANGES +++ /dev/null @@ -1,18 +0,0 @@ -2008-01-10: ---------------- -* New: Wizard for creating new resource bundles. -* Added some support for NL structures. -* Added resource location tooltips to locale. - -2007-12-16: ---------------- -* New: Option to sort keys or not when serializing properties files. -* New: "Add key" action added to key contextual menu. -* Fix: No longer trying to add a key that already exists when pressing the enter - key in the quick-add field below the key tree. -* Fix: Added text validation on key rename action dialog. - -2007-12-12: ---------------- -* Messages Editor markers now updated upon leaving fields. -* Delete and Rename actions now functional. diff --git a/org.eclipse.babel.editor/META-INF/CVS/Entries b/org.eclipse.babel.editor/META-INF/CVS/Entries deleted file mode 100644 index 1d1cc3e5..00000000 --- a/org.eclipse.babel.editor/META-INF/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -/MANIFEST.MF/1.5/Sat Oct 3 20:06:11 2009// diff --git a/org.eclipse.babel.editor/META-INF/CVS/Repository b/org.eclipse.babel.editor/META-INF/CVS/Repository deleted file mode 100644 index bc78f95c..00000000 --- a/org.eclipse.babel.editor/META-INF/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/META-INF diff --git a/org.eclipse.babel.editor/META-INF/CVS/Root b/org.eclipse.babel.editor/META-INF/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/META-INF/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/META-INF/MANIFEST.MF b/org.eclipse.babel.editor/META-INF/MANIFEST.MF deleted file mode 100644 index c6b67a71..00000000 --- a/org.eclipse.babel.editor/META-INF/MANIFEST.MF +++ /dev/null @@ -1,40 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -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;resolution:=optional, - org.eclipse.babel.editor.swt.compat;bundle-version="0.8.0";resolution:=optional, - org.eclipse.core.runtime, - 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";resolution:=optional, - org.eclipse.ltk.core.refactoring;resolution:=optional, - org.eclipse.ltk.ui.refactoring;resolution:=optional, - org.junit;resolution:=optional, - 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, - org.eclipselabs.tapiji.translator.rap.model;bundle-version="0.0.2";resolution:=optional, - org.eclipselabs.tapiji.translator.rap.helpers;bundle-version="1.0.0";resolution:=optional -Bundle-ActivationPolicy: lazy -Bundle-Vendor: %plugin.provider -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Bundle-Localization: plugin -Export-Package: org.eclipse.babel.editor, - org.eclipse.babel.editor.api, - org.eclipse.babel.editor.util, - org.eclipse.babel.editor.widgets, - org.eclipse.babel.editor.wizards -Import-Package: org.eclipse.ui.forms.widgets diff --git a/org.eclipse.babel.editor/build.properties b/org.eclipse.babel.editor/build.properties deleted file mode 100644 index fdad6ae8..00000000 --- a/org.eclipse.babel.editor/build.properties +++ /dev/null @@ -1,13 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - icons/,\ - plugin.properties,\ - messages.properties,\ - CHANGES -src.includes = icons/,\ - messages.properties,\ - plugin.properties,\ - plugin.xml diff --git a/org.eclipse.babel.editor/icons/CVS/Entries b/org.eclipse.babel.editor/icons/CVS/Entries deleted file mode 100644 index 3d371d24..00000000 --- a/org.eclipse.babel.editor/icons/CVS/Entries +++ /dev/null @@ -1,39 +0,0 @@ -/add.png/1.1/Mon Dec 17 03:46:18 2007/-kb/ -/all_translation.png/1.1/Sat Mar 8 19:57:50 2008/-kb/ -/collapseall.png/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/comment.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -D/countries//// -/duplicate.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -D/elcl16//// -/empty.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/error_co.gif/1.1/Sat Mar 8 19:57:50 2008/-kb/ -/expandall.png/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/flatLayout.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/hierarchicalLayout.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/key.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/keyCommented.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/keyCommented.png/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/keyDefault.png/1.2/Sat Mar 8 20:08:06 2008/-kb/ -/keyDefaultBlue.png/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/keyNone.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/keyVirtual.png/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/locale.gif/1.1/Mon Apr 21 03:31:51 2008/-kb/ -/minus.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/missing_translation.png/1.1/Sat Mar 8 19:57:50 2008/-kb/ -/newLocale.gif/1.1/Mon Apr 21 03:31:51 2008/-kb/ -/newpropertiesfile.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/null.bmp/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/null.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/null.png/1.1/Sun Nov 18 15:49:21 2007/-kb/ -D/obj16//// -/plus.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/propertiesfile.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/rename.gif/1.1/Mon Apr 21 03:31:51 2008/-kb/ -/resourcebundle.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/similar.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/unused_and_missing_translations.png/1.1/Sat Mar 8 19:57:50 2008/-kb/ -/unused_translation.png/1.1/Sat Mar 8 19:57:50 2008/-kb/ -/viewLeft.gif/1.1/Mon Apr 21 03:31:51 2008/-kb/ -/warned_translation.png/1.1/Sat Mar 8 19:57:50 2008/-kb/ -/warning.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ -/warningGrey.gif/1.1/Sun Nov 18 15:49:21 2007/-kb/ diff --git a/org.eclipse.babel.editor/icons/CVS/Repository b/org.eclipse.babel.editor/icons/CVS/Repository deleted file mode 100644 index 101684cb..00000000 --- a/org.eclipse.babel.editor/icons/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/icons diff --git a/org.eclipse.babel.editor/icons/CVS/Root b/org.eclipse.babel.editor/icons/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/icons/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/icons/add.png b/org.eclipse.babel.editor/icons/add.png deleted file mode 100644 index 269aaa63..00000000 Binary files a/org.eclipse.babel.editor/icons/add.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/all_translation.png b/org.eclipse.babel.editor/icons/all_translation.png deleted file mode 100644 index 7b55cd61..00000000 Binary files a/org.eclipse.babel.editor/icons/all_translation.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/collapseall.png b/org.eclipse.babel.editor/icons/collapseall.png deleted file mode 100644 index 611a8c5c..00000000 Binary files a/org.eclipse.babel.editor/icons/collapseall.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/comment.gif b/org.eclipse.babel.editor/icons/comment.gif deleted file mode 100644 index 3180fa54..00000000 Binary files a/org.eclipse.babel.editor/icons/comment.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/CVS/Entries b/org.eclipse.babel.editor/icons/countries/CVS/Entries deleted file mode 100644 index 7ffd9ada..00000000 --- a/org.eclipse.babel.editor/icons/countries/CVS/Entries +++ /dev/null @@ -1,208 +0,0 @@ -/__.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/_f.gif/1.1/Sun Nov 18 15:49:10 2007/-kb/ -/ad.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/ae.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/af.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/ag.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/al.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/am.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/ao.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/aq.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/ar.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/at.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/au.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/az.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/ba.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/bb.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/bd.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/be.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/bf.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/bg.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/bh.gif/1.1/Wed Feb 8 22:20:20 2012/-kb/ -/bi.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/bj.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/blank.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/bn.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/bo.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/br.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/bs.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/bt.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/bw.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/by.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/bz.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/ca.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/cd.gif/1.1/Sun Nov 18 15:49:14 2007/-kb/ -/cf.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/cg.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/ch.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/ci.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/cl.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/cm.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/cn.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/co.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/cr.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/cs.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/cu.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/cv.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/cy.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/cz.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/dd.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/de.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/dj.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/dk.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/dm.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/do.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/dz.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/ec.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/ee.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/eg.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/eh.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/er.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/es.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/et.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/eu.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/fi.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/fj.gif/1.1/Sun Nov 18 15:49:14 2007/-kb/ -/fm.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/fr.gif/1.1/Sun Nov 18 15:49:10 2007/-kb/ -/ga.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/gb.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/gd.gif/1.1/Sun Nov 18 15:49:13 2007/-kb/ -/ge.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/gh.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/gm.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/gn.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/gq.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/gr.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/gt.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/gw.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/gy.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/hk.gif/1.1/Wed Feb 8 22:20:20 2012/-kb/ -/hn.gif/1.1/Wed Feb 8 22:20:20 2012/-kb/ -/hr.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/ht.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/hu.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/id.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/ie.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/il.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/in.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/iq.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/ir.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/is.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/it.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/jm.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/jo.gif/1.1/Wed Feb 8 22:20:20 2012/-kb/ -/jp.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/ke.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/kg.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/kh.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/ki.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/km.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/kn.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/kp.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/kr.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/kw.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/kz.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/la.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/lb.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/lc.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/li.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/lk.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/lr.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/ls.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/lt.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/lu.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/lv.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/ly.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/ma.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/mc.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/md.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/mg.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/mh.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/mk.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/ml.gif/1.1/Sun Nov 18 15:49:13 2007/-kb/ -/mm.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/mn.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/mr.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/mt.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/mu.gif/1.1/Sun Nov 18 15:49:13 2007/-kb/ -/mv.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/mw.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/mx.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/my.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/mz.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/na.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/ne.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/ng.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/ni.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/nl.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/no.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/np.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/nr.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/nu.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/nz.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/om.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/pa.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/pe.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/pg.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/ph.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/pk.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/pl.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/ps.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/pt.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/pw.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/py.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/qa.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/ro.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/ru.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/rw.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/sa.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/sb.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/sc.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/sd.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/se.gif/1.1/Sun Nov 18 15:49:14 2007/-kb/ -/sg.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/si.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/sk.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/sl.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/sm.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/sn.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/so.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/sr.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/st.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/su.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/sv.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/sy.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/sz.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/td.gif/1.1/Sun Nov 18 15:49:18 2007/-kb/ -/tg.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/th.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/tj.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/tm.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/tn.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/to.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/tp.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/tr.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/tt.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/tv.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/tw.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/tz.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/ua.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/ug.gif/1.1/Sun Nov 18 15:49:17 2007/-kb/ -/un.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/us.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/uy.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/uz.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/va.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/vc.gif/1.1/Sun Nov 18 15:49:12 2007/-kb/ -/ve.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/vn.gif/1.1/Sun Nov 18 15:49:11 2007/-kb/ -/vu.gif/1.1/Sun Nov 18 15:49:20 2007/-kb/ -/ws.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/ya.gif/1.1/Sun Nov 18 15:49:19 2007/-kb/ -/ye.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/ye0.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/yu.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ -/za.gif/1.1/Sun Nov 18 15:49:15 2007/-kb/ -/zm.gif/1.1/Sun Nov 18 15:49:14 2007/-kb/ -/zw.gif/1.1/Sun Nov 18 15:49:16 2007/-kb/ diff --git a/org.eclipse.babel.editor/icons/countries/CVS/Repository b/org.eclipse.babel.editor/icons/countries/CVS/Repository deleted file mode 100644 index 52a1d9ff..00000000 --- a/org.eclipse.babel.editor/icons/countries/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/icons/countries diff --git a/org.eclipse.babel.editor/icons/countries/CVS/Root b/org.eclipse.babel.editor/icons/countries/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/icons/countries/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/icons/countries/__.gif b/org.eclipse.babel.editor/icons/countries/__.gif deleted file mode 100644 index 65167847..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/__.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/_f.gif b/org.eclipse.babel.editor/icons/countries/_f.gif deleted file mode 100644 index a5f340d4..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/_f.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ad.gif b/org.eclipse.babel.editor/icons/countries/ad.gif deleted file mode 100644 index 0b240549..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ad.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ae.gif b/org.eclipse.babel.editor/icons/countries/ae.gif deleted file mode 100644 index a4a82ff8..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ae.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/af.gif b/org.eclipse.babel.editor/icons/countries/af.gif deleted file mode 100644 index 70e1a15b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/af.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ag.gif b/org.eclipse.babel.editor/icons/countries/ag.gif deleted file mode 100644 index 2dc04e5e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ag.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/al.gif b/org.eclipse.babel.editor/icons/countries/al.gif deleted file mode 100644 index 1384f59b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/al.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/am.gif b/org.eclipse.babel.editor/icons/countries/am.gif deleted file mode 100644 index eda901ed..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/am.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ao.gif b/org.eclipse.babel.editor/icons/countries/ao.gif deleted file mode 100644 index 56f02bbc..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ao.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/aq.gif b/org.eclipse.babel.editor/icons/countries/aq.gif deleted file mode 100644 index d8e99da6..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/aq.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ar.gif b/org.eclipse.babel.editor/icons/countries/ar.gif deleted file mode 100644 index 0231d503..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ar.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/at.gif b/org.eclipse.babel.editor/icons/countries/at.gif deleted file mode 100644 index ecf48b9b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/at.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/au.gif b/org.eclipse.babel.editor/icons/countries/au.gif deleted file mode 100644 index 77761249..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/au.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/az.gif b/org.eclipse.babel.editor/icons/countries/az.gif deleted file mode 100644 index bc77ff24..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/az.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ba.gif b/org.eclipse.babel.editor/icons/countries/ba.gif deleted file mode 100644 index 8e4e5499..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ba.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bb.gif b/org.eclipse.babel.editor/icons/countries/bb.gif deleted file mode 100644 index 54928a68..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bb.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bd.gif b/org.eclipse.babel.editor/icons/countries/bd.gif deleted file mode 100644 index 25890b90..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bd.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/be.gif b/org.eclipse.babel.editor/icons/countries/be.gif deleted file mode 100644 index f917f396..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/be.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bf.gif b/org.eclipse.babel.editor/icons/countries/bf.gif deleted file mode 100644 index 53afd44c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bf.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bg.gif b/org.eclipse.babel.editor/icons/countries/bg.gif deleted file mode 100644 index 5ce1db10..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bh.gif b/org.eclipse.babel.editor/icons/countries/bh.gif deleted file mode 100644 index ba39230e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bh.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bi.gif b/org.eclipse.babel.editor/icons/countries/bi.gif deleted file mode 100644 index ee3d6a48..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bi.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bj.gif b/org.eclipse.babel.editor/icons/countries/bj.gif deleted file mode 100644 index 55463ef0..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bj.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/blank.gif b/org.eclipse.babel.editor/icons/countries/blank.gif deleted file mode 100644 index 314b8633..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/blank.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bn.gif b/org.eclipse.babel.editor/icons/countries/bn.gif deleted file mode 100644 index ed11638b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bo.gif b/org.eclipse.babel.editor/icons/countries/bo.gif deleted file mode 100644 index f1796980..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bo.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/br.gif b/org.eclipse.babel.editor/icons/countries/br.gif deleted file mode 100644 index e1069e08..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/br.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bs.gif b/org.eclipse.babel.editor/icons/countries/bs.gif deleted file mode 100644 index 30c32c32..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bs.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bt.gif b/org.eclipse.babel.editor/icons/countries/bt.gif deleted file mode 100644 index b53dddfb..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bt.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bw.gif b/org.eclipse.babel.editor/icons/countries/bw.gif deleted file mode 100644 index d73ad712..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/by.gif b/org.eclipse.babel.editor/icons/countries/by.gif deleted file mode 100644 index 3335ae02..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/by.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/bz.gif b/org.eclipse.babel.editor/icons/countries/bz.gif deleted file mode 100644 index ec056372..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/bz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ca.gif b/org.eclipse.babel.editor/icons/countries/ca.gif deleted file mode 100644 index 547011ac..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ca.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cd.gif b/org.eclipse.babel.editor/icons/countries/cd.gif deleted file mode 100644 index 44fa4411..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cd.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cf.gif b/org.eclipse.babel.editor/icons/countries/cf.gif deleted file mode 100644 index 41405ce0..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cf.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cg.gif b/org.eclipse.babel.editor/icons/countries/cg.gif deleted file mode 100644 index 00fa29c0..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ch.gif b/org.eclipse.babel.editor/icons/countries/ch.gif deleted file mode 100644 index b0dc176e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ch.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ci.gif b/org.eclipse.babel.editor/icons/countries/ci.gif deleted file mode 100644 index b1167c0d..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ci.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cl.gif b/org.eclipse.babel.editor/icons/countries/cl.gif deleted file mode 100644 index 31dcb03e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cl.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cm.gif b/org.eclipse.babel.editor/icons/countries/cm.gif deleted file mode 100644 index f361dbd7..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cn.gif b/org.eclipse.babel.editor/icons/countries/cn.gif deleted file mode 100644 index f12f17d1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/co.gif b/org.eclipse.babel.editor/icons/countries/co.gif deleted file mode 100644 index d9f14e79..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/co.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cr.gif b/org.eclipse.babel.editor/icons/countries/cr.gif deleted file mode 100644 index 2a5f0b93..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cs.gif b/org.eclipse.babel.editor/icons/countries/cs.gif deleted file mode 100644 index 580d26f5..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cs.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cu.gif b/org.eclipse.babel.editor/icons/countries/cu.gif deleted file mode 100644 index 823befcc..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cv.gif b/org.eclipse.babel.editor/icons/countries/cv.gif deleted file mode 100644 index d21a45cb..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cv.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cy.gif b/org.eclipse.babel.editor/icons/countries/cy.gif deleted file mode 100644 index 1a332d90..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cy.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/cz.gif b/org.eclipse.babel.editor/icons/countries/cz.gif deleted file mode 100644 index 2faee5e1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/cz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/dd.gif b/org.eclipse.babel.editor/icons/countries/dd.gif deleted file mode 100644 index 99eda38f..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/dd.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/de.gif b/org.eclipse.babel.editor/icons/countries/de.gif deleted file mode 100644 index c7b28406..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/de.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/dj.gif b/org.eclipse.babel.editor/icons/countries/dj.gif deleted file mode 100644 index 94fc2eb3..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/dj.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/dk.gif b/org.eclipse.babel.editor/icons/countries/dk.gif deleted file mode 100644 index 4f01ec95..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/dk.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/dm.gif b/org.eclipse.babel.editor/icons/countries/dm.gif deleted file mode 100644 index b4fed906..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/dm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/do.gif b/org.eclipse.babel.editor/icons/countries/do.gif deleted file mode 100644 index 85d7be8b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/do.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/dz.gif b/org.eclipse.babel.editor/icons/countries/dz.gif deleted file mode 100644 index 622ff6ba..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/dz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ec.gif b/org.eclipse.babel.editor/icons/countries/ec.gif deleted file mode 100644 index 5d1641b1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ec.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ee.gif b/org.eclipse.babel.editor/icons/countries/ee.gif deleted file mode 100644 index c678c73c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ee.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/eg.gif b/org.eclipse.babel.editor/icons/countries/eg.gif deleted file mode 100644 index a740c668..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/eg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/eh.gif b/org.eclipse.babel.editor/icons/countries/eh.gif deleted file mode 100644 index 6a75cc3c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/eh.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/er.gif b/org.eclipse.babel.editor/icons/countries/er.gif deleted file mode 100644 index 71297d62..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/er.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/es.gif b/org.eclipse.babel.editor/icons/countries/es.gif deleted file mode 100644 index 6dee15c1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/es.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/et.gif b/org.eclipse.babel.editor/icons/countries/et.gif deleted file mode 100644 index 4188e4ff..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/et.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/eu.gif b/org.eclipse.babel.editor/icons/countries/eu.gif deleted file mode 100644 index 45caabf2..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/eu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/fi.gif b/org.eclipse.babel.editor/icons/countries/fi.gif deleted file mode 100644 index b8311cac..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/fi.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/fj.gif b/org.eclipse.babel.editor/icons/countries/fj.gif deleted file mode 100644 index f5481b79..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/fj.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/fm.gif b/org.eclipse.babel.editor/icons/countries/fm.gif deleted file mode 100644 index 050eca09..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/fm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/fr.gif b/org.eclipse.babel.editor/icons/countries/fr.gif deleted file mode 100644 index a2a2354d..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/fr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ga.gif b/org.eclipse.babel.editor/icons/countries/ga.gif deleted file mode 100644 index 54fb2514..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ga.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gb.gif b/org.eclipse.babel.editor/icons/countries/gb.gif deleted file mode 100644 index 4ae2d0f8..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gb.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gd.gif b/org.eclipse.babel.editor/icons/countries/gd.gif deleted file mode 100644 index 0095032c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gd.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ge.gif b/org.eclipse.babel.editor/icons/countries/ge.gif deleted file mode 100644 index f3927c8a..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ge.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gh.gif b/org.eclipse.babel.editor/icons/countries/gh.gif deleted file mode 100644 index 6d3b6142..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gh.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gm.gif b/org.eclipse.babel.editor/icons/countries/gm.gif deleted file mode 100644 index 2ecf0b0b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gn.gif b/org.eclipse.babel.editor/icons/countries/gn.gif deleted file mode 100644 index 83179352..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gq.gif b/org.eclipse.babel.editor/icons/countries/gq.gif deleted file mode 100644 index 6c2bc475..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gq.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gr.gif b/org.eclipse.babel.editor/icons/countries/gr.gif deleted file mode 100644 index 1599add4..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gt.gif b/org.eclipse.babel.editor/icons/countries/gt.gif deleted file mode 100644 index c306f25d..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gt.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gw.gif b/org.eclipse.babel.editor/icons/countries/gw.gif deleted file mode 100644 index 6cba5901..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/gy.gif b/org.eclipse.babel.editor/icons/countries/gy.gif deleted file mode 100644 index a4b4da97..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/gy.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/hk.gif b/org.eclipse.babel.editor/icons/countries/hk.gif deleted file mode 100644 index 230723af..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/hk.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/hn.gif b/org.eclipse.babel.editor/icons/countries/hn.gif deleted file mode 100644 index 05501572..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/hn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/hr.gif b/org.eclipse.babel.editor/icons/countries/hr.gif deleted file mode 100644 index 893778a1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/hr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ht.gif b/org.eclipse.babel.editor/icons/countries/ht.gif deleted file mode 100644 index e5cf7803..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ht.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/hu.gif b/org.eclipse.babel.editor/icons/countries/hu.gif deleted file mode 100644 index 07778839..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/hu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/id.gif b/org.eclipse.babel.editor/icons/countries/id.gif deleted file mode 100644 index 9fed7642..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/id.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ie.gif b/org.eclipse.babel.editor/icons/countries/ie.gif deleted file mode 100644 index 82ec5535..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ie.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/il.gif b/org.eclipse.babel.editor/icons/countries/il.gif deleted file mode 100644 index 554a7612..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/il.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/in.gif b/org.eclipse.babel.editor/icons/countries/in.gif deleted file mode 100644 index 430b37b9..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/in.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/iq.gif b/org.eclipse.babel.editor/icons/countries/iq.gif deleted file mode 100644 index dae4d593..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/iq.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ir.gif b/org.eclipse.babel.editor/icons/countries/ir.gif deleted file mode 100644 index 50f5432a..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ir.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/is.gif b/org.eclipse.babel.editor/icons/countries/is.gif deleted file mode 100644 index e9580e07..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/is.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/it.gif b/org.eclipse.babel.editor/icons/countries/it.gif deleted file mode 100644 index 4256b464..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/it.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/jm.gif b/org.eclipse.babel.editor/icons/countries/jm.gif deleted file mode 100644 index f1459feb..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/jm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/jo.gif b/org.eclipse.babel.editor/icons/countries/jo.gif deleted file mode 100644 index a9d36128..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/jo.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/jp.gif b/org.eclipse.babel.editor/icons/countries/jp.gif deleted file mode 100644 index ddad6e3b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/jp.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ke.gif b/org.eclipse.babel.editor/icons/countries/ke.gif deleted file mode 100644 index 6e06f4a7..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ke.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/kg.gif b/org.eclipse.babel.editor/icons/countries/kg.gif deleted file mode 100644 index e47fb0f2..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/kg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/kh.gif b/org.eclipse.babel.editor/icons/countries/kh.gif deleted file mode 100644 index 31f5be16..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/kh.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ki.gif b/org.eclipse.babel.editor/icons/countries/ki.gif deleted file mode 100644 index 9f12bb0d..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ki.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/km.gif b/org.eclipse.babel.editor/icons/countries/km.gif deleted file mode 100644 index 027276bf..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/km.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/kn.gif b/org.eclipse.babel.editor/icons/countries/kn.gif deleted file mode 100644 index f690875e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/kn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/kp.gif b/org.eclipse.babel.editor/icons/countries/kp.gif deleted file mode 100644 index 42584efa..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/kp.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/kr.gif b/org.eclipse.babel.editor/icons/countries/kr.gif deleted file mode 100644 index 800c6cdd..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/kr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/kw.gif b/org.eclipse.babel.editor/icons/countries/kw.gif deleted file mode 100644 index ff083b5e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/kw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/kz.gif b/org.eclipse.babel.editor/icons/countries/kz.gif deleted file mode 100644 index 9b13afe0..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/kz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/la.gif b/org.eclipse.babel.editor/icons/countries/la.gif deleted file mode 100644 index 3c6f2f15..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/la.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/lb.gif b/org.eclipse.babel.editor/icons/countries/lb.gif deleted file mode 100644 index f3c45527..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/lb.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/lc.gif b/org.eclipse.babel.editor/icons/countries/lc.gif deleted file mode 100644 index fdcbd97f..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/lc.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/li.gif b/org.eclipse.babel.editor/icons/countries/li.gif deleted file mode 100644 index eb9d9384..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/li.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/lk.gif b/org.eclipse.babel.editor/icons/countries/lk.gif deleted file mode 100644 index 3aa25aa8..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/lk.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/lr.gif b/org.eclipse.babel.editor/icons/countries/lr.gif deleted file mode 100644 index f54468fc..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/lr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ls.gif b/org.eclipse.babel.editor/icons/countries/ls.gif deleted file mode 100644 index c1ad8d2f..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ls.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/lt.gif b/org.eclipse.babel.editor/icons/countries/lt.gif deleted file mode 100644 index 78447f07..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/lt.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/lu.gif b/org.eclipse.babel.editor/icons/countries/lu.gif deleted file mode 100644 index d74df5ab..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/lu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/lv.gif b/org.eclipse.babel.editor/icons/countries/lv.gif deleted file mode 100644 index 5f7419c6..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/lv.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ly.gif b/org.eclipse.babel.editor/icons/countries/ly.gif deleted file mode 100644 index 8ca9e0a0..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ly.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ma.gif b/org.eclipse.babel.editor/icons/countries/ma.gif deleted file mode 100644 index 3aab8cbb..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ma.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mc.gif b/org.eclipse.babel.editor/icons/countries/mc.gif deleted file mode 100644 index c22c1717..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mc.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/md.gif b/org.eclipse.babel.editor/icons/countries/md.gif deleted file mode 100644 index 4951b21a..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/md.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mg.gif b/org.eclipse.babel.editor/icons/countries/mg.gif deleted file mode 100644 index 24281d87..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mh.gif b/org.eclipse.babel.editor/icons/countries/mh.gif deleted file mode 100644 index c472aee6..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mh.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mk.gif b/org.eclipse.babel.editor/icons/countries/mk.gif deleted file mode 100644 index 88c077fa..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mk.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ml.gif b/org.eclipse.babel.editor/icons/countries/ml.gif deleted file mode 100644 index 4eb75ae1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ml.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mm.gif b/org.eclipse.babel.editor/icons/countries/mm.gif deleted file mode 100644 index bd378555..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mn.gif b/org.eclipse.babel.editor/icons/countries/mn.gif deleted file mode 100644 index de3029b3..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mr.gif b/org.eclipse.babel.editor/icons/countries/mr.gif deleted file mode 100644 index d7cbb38a..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mt.gif b/org.eclipse.babel.editor/icons/countries/mt.gif deleted file mode 100644 index 677969a7..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mt.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mu.gif b/org.eclipse.babel.editor/icons/countries/mu.gif deleted file mode 100644 index d102ab7e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mv.gif b/org.eclipse.babel.editor/icons/countries/mv.gif deleted file mode 100644 index 69ac6863..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mv.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mw.gif b/org.eclipse.babel.editor/icons/countries/mw.gif deleted file mode 100644 index a0f0320b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mx.gif b/org.eclipse.babel.editor/icons/countries/mx.gif deleted file mode 100644 index bbcb376b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mx.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/my.gif b/org.eclipse.babel.editor/icons/countries/my.gif deleted file mode 100644 index 8874751b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/my.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/mz.gif b/org.eclipse.babel.editor/icons/countries/mz.gif deleted file mode 100644 index b63af289..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/mz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/na.gif b/org.eclipse.babel.editor/icons/countries/na.gif deleted file mode 100644 index bee7072e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/na.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ne.gif b/org.eclipse.babel.editor/icons/countries/ne.gif deleted file mode 100644 index fc1b74b8..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ne.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ng.gif b/org.eclipse.babel.editor/icons/countries/ng.gif deleted file mode 100644 index 43af12c9..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ng.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ni.gif b/org.eclipse.babel.editor/icons/countries/ni.gif deleted file mode 100644 index cac0042d..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ni.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/nl.gif b/org.eclipse.babel.editor/icons/countries/nl.gif deleted file mode 100644 index c4258e62..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/nl.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/no.gif b/org.eclipse.babel.editor/icons/countries/no.gif deleted file mode 100644 index 873baca1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/no.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/np.gif b/org.eclipse.babel.editor/icons/countries/np.gif deleted file mode 100644 index f01f2f9e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/np.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/nr.gif b/org.eclipse.babel.editor/icons/countries/nr.gif deleted file mode 100644 index d485c4b1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/nr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/nu.gif b/org.eclipse.babel.editor/icons/countries/nu.gif deleted file mode 100644 index 73177056..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/nu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/nz.gif b/org.eclipse.babel.editor/icons/countries/nz.gif deleted file mode 100644 index 49f8464e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/nz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/om.gif b/org.eclipse.babel.editor/icons/countries/om.gif deleted file mode 100644 index d90ca333..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/om.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/pa.gif b/org.eclipse.babel.editor/icons/countries/pa.gif deleted file mode 100644 index cae5432f..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/pa.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/pe.gif b/org.eclipse.babel.editor/icons/countries/pe.gif deleted file mode 100644 index e6cc7348..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/pe.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/pg.gif b/org.eclipse.babel.editor/icons/countries/pg.gif deleted file mode 100644 index 108204f3..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/pg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ph.gif b/org.eclipse.babel.editor/icons/countries/ph.gif deleted file mode 100644 index b141cd81..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ph.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/pk.gif b/org.eclipse.babel.editor/icons/countries/pk.gif deleted file mode 100644 index f612b977..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/pk.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/pl.gif b/org.eclipse.babel.editor/icons/countries/pl.gif deleted file mode 100644 index 6ff3ba6f..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/pl.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ps.gif b/org.eclipse.babel.editor/icons/countries/ps.gif deleted file mode 100644 index 71717cc9..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ps.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/pt.gif b/org.eclipse.babel.editor/icons/countries/pt.gif deleted file mode 100644 index 9bfc8ca4..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/pt.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/pw.gif b/org.eclipse.babel.editor/icons/countries/pw.gif deleted file mode 100644 index 0a520911..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/pw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/py.gif b/org.eclipse.babel.editor/icons/countries/py.gif deleted file mode 100644 index b52de243..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/py.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/qa.gif b/org.eclipse.babel.editor/icons/countries/qa.gif deleted file mode 100644 index e078e46c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/qa.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ro.gif b/org.eclipse.babel.editor/icons/countries/ro.gif deleted file mode 100644 index 6bdbad14..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ro.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ru.gif b/org.eclipse.babel.editor/icons/countries/ru.gif deleted file mode 100644 index cf4d30c8..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ru.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/rw.gif b/org.eclipse.babel.editor/icons/countries/rw.gif deleted file mode 100644 index 02cf0cb1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/rw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sa.gif b/org.eclipse.babel.editor/icons/countries/sa.gif deleted file mode 100644 index 4b7632ee..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sa.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sb.gif b/org.eclipse.babel.editor/icons/countries/sb.gif deleted file mode 100644 index eb8acc08..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sb.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sc.gif b/org.eclipse.babel.editor/icons/countries/sc.gif deleted file mode 100644 index 4324c21f..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sc.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sd.gif b/org.eclipse.babel.editor/icons/countries/sd.gif deleted file mode 100644 index 2d74f622..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sd.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/se.gif b/org.eclipse.babel.editor/icons/countries/se.gif deleted file mode 100644 index 9bbcb1fa..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/se.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sg.gif b/org.eclipse.babel.editor/icons/countries/sg.gif deleted file mode 100644 index b81f461e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/si.gif b/org.eclipse.babel.editor/icons/countries/si.gif deleted file mode 100644 index f6afb67d..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/si.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sk.gif b/org.eclipse.babel.editor/icons/countries/sk.gif deleted file mode 100644 index b0c4ab19..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sk.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sl.gif b/org.eclipse.babel.editor/icons/countries/sl.gif deleted file mode 100644 index 00d59d3b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sl.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sm.gif b/org.eclipse.babel.editor/icons/countries/sm.gif deleted file mode 100644 index 8d9d76b3..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sn.gif b/org.eclipse.babel.editor/icons/countries/sn.gif deleted file mode 100644 index 1a541741..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/so.gif b/org.eclipse.babel.editor/icons/countries/so.gif deleted file mode 100644 index 7f1dba35..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/so.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sr.gif b/org.eclipse.babel.editor/icons/countries/sr.gif deleted file mode 100644 index de781c13..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/st.gif b/org.eclipse.babel.editor/icons/countries/st.gif deleted file mode 100644 index cd9036fb..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/st.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/su.gif b/org.eclipse.babel.editor/icons/countries/su.gif deleted file mode 100644 index 23e162a1..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/su.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sv.gif b/org.eclipse.babel.editor/icons/countries/sv.gif deleted file mode 100644 index bef488e2..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sv.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sy.gif b/org.eclipse.babel.editor/icons/countries/sy.gif deleted file mode 100644 index a3a53cd4..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sy.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/sz.gif b/org.eclipse.babel.editor/icons/countries/sz.gif deleted file mode 100644 index b3a20ba5..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/sz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/td.gif b/org.eclipse.babel.editor/icons/countries/td.gif deleted file mode 100644 index 3ccc8dff..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/td.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tg.gif b/org.eclipse.babel.editor/icons/countries/tg.gif deleted file mode 100644 index 674e68f0..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tg.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/th.gif b/org.eclipse.babel.editor/icons/countries/th.gif deleted file mode 100644 index 83318c0c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/th.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tj.gif b/org.eclipse.babel.editor/icons/countries/tj.gif deleted file mode 100644 index 1f44255c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tj.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tm.gif b/org.eclipse.babel.editor/icons/countries/tm.gif deleted file mode 100644 index a603afd2..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tn.gif b/org.eclipse.babel.editor/icons/countries/tn.gif deleted file mode 100644 index 083238da..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/to.gif b/org.eclipse.babel.editor/icons/countries/to.gif deleted file mode 100644 index 603aa8e3..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/to.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tp.gif b/org.eclipse.babel.editor/icons/countries/tp.gif deleted file mode 100644 index 40599d56..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tp.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tr.gif b/org.eclipse.babel.editor/icons/countries/tr.gif deleted file mode 100644 index 2eac7305..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tr.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tt.gif b/org.eclipse.babel.editor/icons/countries/tt.gif deleted file mode 100644 index f7154195..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tt.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tv.gif b/org.eclipse.babel.editor/icons/countries/tv.gif deleted file mode 100644 index 9b018e87..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tv.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tw.gif b/org.eclipse.babel.editor/icons/countries/tw.gif deleted file mode 100644 index 57a04829..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/tz.gif b/org.eclipse.babel.editor/icons/countries/tz.gif deleted file mode 100644 index 6d28d408..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/tz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ua.gif b/org.eclipse.babel.editor/icons/countries/ua.gif deleted file mode 100644 index bebd6705..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ua.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ug.gif b/org.eclipse.babel.editor/icons/countries/ug.gif deleted file mode 100644 index 151e3037..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ug.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/un.gif b/org.eclipse.babel.editor/icons/countries/un.gif deleted file mode 100644 index 135b5281..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/un.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/us.gif b/org.eclipse.babel.editor/icons/countries/us.gif deleted file mode 100644 index 850094ea..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/us.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/uy.gif b/org.eclipse.babel.editor/icons/countries/uy.gif deleted file mode 100644 index 4d129fc5..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/uy.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/uz.gif b/org.eclipse.babel.editor/icons/countries/uz.gif deleted file mode 100644 index d9cc88eb..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/uz.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/va.gif b/org.eclipse.babel.editor/icons/countries/va.gif deleted file mode 100644 index 5db146d6..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/va.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/vc.gif b/org.eclipse.babel.editor/icons/countries/vc.gif deleted file mode 100644 index 6519018d..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/vc.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ve.gif b/org.eclipse.babel.editor/icons/countries/ve.gif deleted file mode 100644 index 4abf999b..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ve.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/vn.gif b/org.eclipse.babel.editor/icons/countries/vn.gif deleted file mode 100644 index e7d1e5b9..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/vn.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/vu.gif b/org.eclipse.babel.editor/icons/countries/vu.gif deleted file mode 100644 index f8736a18..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/vu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ws.gif b/org.eclipse.babel.editor/icons/countries/ws.gif deleted file mode 100644 index b2bc2f76..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ws.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ya.gif b/org.eclipse.babel.editor/icons/countries/ya.gif deleted file mode 100644 index 91536134..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ya.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ye.gif b/org.eclipse.babel.editor/icons/countries/ye.gif deleted file mode 100644 index f183847c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ye.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/ye0.gif b/org.eclipse.babel.editor/icons/countries/ye0.gif deleted file mode 100644 index b9c28b30..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/ye0.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/yu.gif b/org.eclipse.babel.editor/icons/countries/yu.gif deleted file mode 100644 index c91bf1ef..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/yu.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/za.gif b/org.eclipse.babel.editor/icons/countries/za.gif deleted file mode 100644 index 8579793e..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/za.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/zm.gif b/org.eclipse.babel.editor/icons/countries/zm.gif deleted file mode 100644 index fc686bb8..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/zm.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/countries/zw.gif b/org.eclipse.babel.editor/icons/countries/zw.gif deleted file mode 100644 index 9821c41c..00000000 Binary files a/org.eclipse.babel.editor/icons/countries/zw.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/duplicate.gif b/org.eclipse.babel.editor/icons/duplicate.gif deleted file mode 100644 index 3366a273..00000000 Binary files a/org.eclipse.babel.editor/icons/duplicate.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/elcl16/CVS/Entries b/org.eclipse.babel.editor/icons/elcl16/CVS/Entries deleted file mode 100644 index b715eb47..00000000 --- a/org.eclipse.babel.editor/icons/elcl16/CVS/Entries +++ /dev/null @@ -1,5 +0,0 @@ -/clear_co.gif/1.1/Sun Aug 17 05:21:11 2008/-kb/ -/conf_columns.gif/1.1/Sun Aug 17 05:21:11 2008/-kb/ -/export.gif/1.1/Sun Aug 17 05:21:11 2008/-kb/ -/filter_obj.gif/1.1/Sun Aug 17 05:21:11 2008/-kb/ -/refresh.gif/1.1/Sun Aug 17 05:21:11 2008/-kb/ diff --git a/org.eclipse.babel.editor/icons/elcl16/CVS/Repository b/org.eclipse.babel.editor/icons/elcl16/CVS/Repository deleted file mode 100644 index 416f66c3..00000000 --- a/org.eclipse.babel.editor/icons/elcl16/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/icons/elcl16 diff --git a/org.eclipse.babel.editor/icons/elcl16/CVS/Root b/org.eclipse.babel.editor/icons/elcl16/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/icons/elcl16/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/icons/elcl16/clear_co.gif b/org.eclipse.babel.editor/icons/elcl16/clear_co.gif deleted file mode 100644 index af30a42f..00000000 Binary files a/org.eclipse.babel.editor/icons/elcl16/clear_co.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/elcl16/conf_columns.gif b/org.eclipse.babel.editor/icons/elcl16/conf_columns.gif deleted file mode 100644 index 5ef0ed7f..00000000 Binary files a/org.eclipse.babel.editor/icons/elcl16/conf_columns.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/elcl16/export.gif b/org.eclipse.babel.editor/icons/elcl16/export.gif deleted file mode 100644 index 3465699b..00000000 Binary files a/org.eclipse.babel.editor/icons/elcl16/export.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/elcl16/filter_obj.gif b/org.eclipse.babel.editor/icons/elcl16/filter_obj.gif deleted file mode 100644 index ef51bd54..00000000 Binary files a/org.eclipse.babel.editor/icons/elcl16/filter_obj.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/elcl16/refresh.gif b/org.eclipse.babel.editor/icons/elcl16/refresh.gif deleted file mode 100644 index 3ca04d06..00000000 Binary files a/org.eclipse.babel.editor/icons/elcl16/refresh.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/empty.gif b/org.eclipse.babel.editor/icons/empty.gif deleted file mode 100644 index 997486fa..00000000 Binary files a/org.eclipse.babel.editor/icons/empty.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/error_co.gif b/org.eclipse.babel.editor/icons/error_co.gif deleted file mode 100644 index 119dcccd..00000000 Binary files a/org.eclipse.babel.editor/icons/error_co.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/expandall.png b/org.eclipse.babel.editor/icons/expandall.png deleted file mode 100644 index 494c77ce..00000000 Binary files a/org.eclipse.babel.editor/icons/expandall.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/flatLayout.gif b/org.eclipse.babel.editor/icons/flatLayout.gif deleted file mode 100644 index 1ef74cf9..00000000 Binary files a/org.eclipse.babel.editor/icons/flatLayout.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/hierarchicalLayout.gif b/org.eclipse.babel.editor/icons/hierarchicalLayout.gif deleted file mode 100644 index 23448617..00000000 Binary files a/org.eclipse.babel.editor/icons/hierarchicalLayout.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/key.gif b/org.eclipse.babel.editor/icons/key.gif deleted file mode 100644 index bdb8e971..00000000 Binary files a/org.eclipse.babel.editor/icons/key.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/keyCommented.gif b/org.eclipse.babel.editor/icons/keyCommented.gif deleted file mode 100644 index 869eb6bd..00000000 Binary files a/org.eclipse.babel.editor/icons/keyCommented.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/keyCommented.png b/org.eclipse.babel.editor/icons/keyCommented.png deleted file mode 100644 index d6080106..00000000 Binary files a/org.eclipse.babel.editor/icons/keyCommented.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/keyDefault.png b/org.eclipse.babel.editor/icons/keyDefault.png deleted file mode 100644 index a3f1926f..00000000 Binary files a/org.eclipse.babel.editor/icons/keyDefault.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/keyDefaultBlue.png b/org.eclipse.babel.editor/icons/keyDefaultBlue.png deleted file mode 100644 index 75bbea20..00000000 Binary files a/org.eclipse.babel.editor/icons/keyDefaultBlue.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/keyNone.gif b/org.eclipse.babel.editor/icons/keyNone.gif deleted file mode 100644 index dd1bd7c2..00000000 Binary files a/org.eclipse.babel.editor/icons/keyNone.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/keyVirtual.png b/org.eclipse.babel.editor/icons/keyVirtual.png deleted file mode 100644 index f557842e..00000000 Binary files a/org.eclipse.babel.editor/icons/keyVirtual.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/locale.gif b/org.eclipse.babel.editor/icons/locale.gif deleted file mode 100644 index 679a43c8..00000000 Binary files a/org.eclipse.babel.editor/icons/locale.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/minus.gif b/org.eclipse.babel.editor/icons/minus.gif deleted file mode 100644 index 90d1d341..00000000 Binary files a/org.eclipse.babel.editor/icons/minus.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/missing_translation.gif b/org.eclipse.babel.editor/icons/missing_translation.gif deleted file mode 100644 index af27508a..00000000 Binary files a/org.eclipse.babel.editor/icons/missing_translation.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/missing_translation.png b/org.eclipse.babel.editor/icons/missing_translation.png deleted file mode 100644 index 7cc7392c..00000000 Binary files a/org.eclipse.babel.editor/icons/missing_translation.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/newLocale.gif b/org.eclipse.babel.editor/icons/newLocale.gif deleted file mode 100644 index 9e282f92..00000000 Binary files a/org.eclipse.babel.editor/icons/newLocale.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/newpropertiesfile.gif b/org.eclipse.babel.editor/icons/newpropertiesfile.gif deleted file mode 100644 index 11e436b8..00000000 Binary files a/org.eclipse.babel.editor/icons/newpropertiesfile.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/null.bmp b/org.eclipse.babel.editor/icons/null.bmp deleted file mode 100644 index f3dc1edb..00000000 Binary files a/org.eclipse.babel.editor/icons/null.bmp and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/null.gif b/org.eclipse.babel.editor/icons/null.gif deleted file mode 100644 index 760c3e22..00000000 Binary files a/org.eclipse.babel.editor/icons/null.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/null.png b/org.eclipse.babel.editor/icons/null.png deleted file mode 100644 index 304a5149..00000000 Binary files a/org.eclipse.babel.editor/icons/null.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/obj16/CVS/Entries b/org.eclipse.babel.editor/icons/obj16/CVS/Entries deleted file mode 100644 index 1818f626..00000000 --- a/org.eclipse.babel.editor/icons/obj16/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -/nls_editor.gif/1.1/Sun Aug 17 05:21:11 2008/-kb/ diff --git a/org.eclipse.babel.editor/icons/obj16/CVS/Repository b/org.eclipse.babel.editor/icons/obj16/CVS/Repository deleted file mode 100644 index 7d489e0b..00000000 --- a/org.eclipse.babel.editor/icons/obj16/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/icons/obj16 diff --git a/org.eclipse.babel.editor/icons/obj16/CVS/Root b/org.eclipse.babel.editor/icons/obj16/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/icons/obj16/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/icons/obj16/nls_editor.gif b/org.eclipse.babel.editor/icons/obj16/nls_editor.gif deleted file mode 100644 index e6913d02..00000000 Binary files a/org.eclipse.babel.editor/icons/obj16/nls_editor.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/plus.gif b/org.eclipse.babel.editor/icons/plus.gif deleted file mode 100644 index 014671fc..00000000 Binary files a/org.eclipse.babel.editor/icons/plus.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/propertiesfile.gif b/org.eclipse.babel.editor/icons/propertiesfile.gif deleted file mode 100644 index 9090c04d..00000000 Binary files a/org.eclipse.babel.editor/icons/propertiesfile.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/refactoring.png b/org.eclipse.babel.editor/icons/refactoring.png deleted file mode 100644 index 5242fdf5..00000000 Binary files a/org.eclipse.babel.editor/icons/refactoring.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/rename.gif b/org.eclipse.babel.editor/icons/rename.gif deleted file mode 100644 index 3f22ef96..00000000 Binary files a/org.eclipse.babel.editor/icons/rename.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/resourcebundle.gif b/org.eclipse.babel.editor/icons/resourcebundle.gif deleted file mode 100644 index fe05bad9..00000000 Binary files a/org.eclipse.babel.editor/icons/resourcebundle.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/similar.gif b/org.eclipse.babel.editor/icons/similar.gif deleted file mode 100644 index 74cf98e5..00000000 Binary files a/org.eclipse.babel.editor/icons/similar.gif and /dev/null 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 deleted file mode 100644 index 19a18b89..00000000 Binary files a/org.eclipse.babel.editor/icons/unused_and_missing_translations.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/unused_translation.png b/org.eclipse.babel.editor/icons/unused_translation.png deleted file mode 100644 index d449d03c..00000000 Binary files a/org.eclipse.babel.editor/icons/unused_translation.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/viewLeft.gif b/org.eclipse.babel.editor/icons/viewLeft.gif deleted file mode 100644 index 210830d3..00000000 Binary files a/org.eclipse.babel.editor/icons/viewLeft.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/warned_translation.png b/org.eclipse.babel.editor/icons/warned_translation.png deleted file mode 100644 index 1713d913..00000000 Binary files a/org.eclipse.babel.editor/icons/warned_translation.png and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/warning.gif b/org.eclipse.babel.editor/icons/warning.gif deleted file mode 100644 index 801a1f81..00000000 Binary files a/org.eclipse.babel.editor/icons/warning.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/icons/warningGrey.gif b/org.eclipse.babel.editor/icons/warningGrey.gif deleted file mode 100644 index e11147e9..00000000 Binary files a/org.eclipse.babel.editor/icons/warningGrey.gif and /dev/null differ diff --git a/org.eclipse.babel.editor/messages.properties b/org.eclipse.babel.editor/messages.properties deleted file mode 100644 index 0c533da1..00000000 --- a/org.eclipse.babel.editor/messages.properties +++ /dev/null @@ -1,126 +0,0 @@ -#Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) - -dialog.add.body = Add the following key : -dialog.add.head = Add key -dialog.delete.body.multiple = Are you sure you want to delete all keys in "{0}" group? -dialog.delete.body.single = Are you sure you want to delete "{0}"? -dialog.delete.head.multiple = Delete key group -dialog.delete.head.single = Delete key -dialog.duplicate.body.multiple = Duplicate key group "{0}" to (all nested keys will be duplicated): -dialog.duplicate.body.single = Duplicate "{0}" to: -dialog.duplicate.head.multiple = Duplicate key group -dialog.duplicate.head.single = Duplicate key -dialog.error.exists = This key already exists. -dialog.identical.body = Below are keys having identical value as key "{0}" within the locale "{1}": -dialog.identical.head = Identical value(s) found. -dialog.rename.body.multiple = Rename key group "{0}" to (all nested keys will be renamed): -dialog.rename.body.single = Rename "{0}" to: -dialog.rename.head.multiple = Rename key group -dialog.rename.head.single = Rename key -dialog.similar.body = Below are keys having similar value as key "{0}" within the locale "{1}": -dialog.similar.head = Similar value(s) found. - -editor.content.desc = Editor for ResourceBundle: -editor.default = Default -editor.i18nentry.rootlocale.label = Default -editor.i18nentry.resourcelocation = Resource location: {0} -editor.new.create = Create -editor.new.tab = New... -editor.new.title = New properties file: -editor.properties = Properties -editor.readOnly = read-only -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 -editor.wiz.selectFolder = Select a folder -editor.wiz.selected = Selected locales -editor.wiz.title = ResourceBundle (Properties Files) - -error.init.badencoding = Malformed \\uxxxx encoding found in this string: -error.init.ui = Cannot initialize visual component. -error.newfile.cannotCreate = Cannot create new file. -error.newfile.cannotOpen = Cannot open newly created file. -error.seeLogs = See log file for details. - -key.add = &Add -key.collapseAll = Co&llapse All -key.comment = Co&mment -key.delete = &Delete -key.duplicate = Du&plicate -key.expandAll = &Expand All -key.layout.flat = Flat -key.layout.tree = Tree -key.rename = &Rename -key.refactor = Refactor -key.uncomment = &Uncomment - -prefs.alignEquals = Align equal signs -prefs.convertEncoded = Convert \\uXXXX values to unicode when reading from properties file -prefs.convertUnicode = Convert unicode values to \\uXXXX -prefs.convertUnicode.upper = Use uppercase for hexadecimal letters -prefs.fieldTabInserts = Tab key inserts a tab in localized text fields -prefs.filterLocales.label = Displayed locales: -prefs.filterLocales.tooltip = Comma separated list of locales to display, '*' and '?' can be used. -prefs.groupAlignEquals = Align equal signs within groups -prefs.groupKeys = Group keys -prefs.groupSep = Key group separator: -prefs.keepEmptyFields = Keep keys without values -prefs.keysSorted = Sort keys -prefs.keyTree.expanded = Key tree is expanded by default -prefs.keyTree.hierarchical = Key tree is hierarchical by default -prefs.levelDeep = How many level deep: -prefs.levelDeep.error = The 'How many level deep' field must be numeric -prefs.linesBetween = How many lines between groups: -prefs.linesBetween.error = The 'How many lines between groups' field must be numeric -prefs.newline.force = Force new line escape style: -prefs.newline.nice = Wrap lines after escaped new line characters -prefs.perform.duplVals = Report keys sharing duplicate values within the same locale file -prefs.perform.intro1 = The following features can have a significant impact on performance -prefs.perform.intro2 = Especially on large files. Use them wisely -prefs.perform.missingVals = Report keys having one or more missing values -prefs.perform.simVals = Report keys sharing similar values within the same locale file -prefs.perform.simVals.levensthein = Use Levensthein distance -prefs.perform.simVals.precision = Precision level (between 0 and 1): -prefs.perform.simVals.precision.error = Precision level must be between 0 and 1 -prefs.perform.simVals.wordCount = Use identical word count -prefs.removeAlreadyInstalledValidators.title = Remove installed i18n validators -prefs.removeAlreadyInstalledValidators.text = Would you like to remove the currently installed i18n builders? -prefs.perform.message.ignore = Ignore -prefs.perform.message.info = Info -prefs.perform.message.warning = Warning -prefs.perform.message.error = Error -prefs.setupValidationBuilderAutomatically = Setup validation builder on java projects automatically -prefs.showGeneratedBy = Show "Generated By..." header comment (show your support!) -prefs.spacesAroundEquals = At least one space each side of equal signs -prefs.supportNL = Support Eclipse "nl" structure for plugin internationalization -prefs.wrapAlignEquals = Align wrapped lines with equal signs -prefs.wrapIndent = How many spaces to use for indentation: -prefs.wrapIndent.error = The 'How many spaces to use...' field must be numeric -prefs.wrapLines = Wrap long lines -prefs.wrapLinesChar = Wrap lines after how many characters: -prefs.wrapLinesChar.error = The 'Wrap lines after...' field must be numeric - -selector.country = Country -selector.language = Lang. -selector.title = Choose or type a Locale -selector.variant = Variant - -value.comment.tooltip = Check to comment this entry. -value.duplicate.tooltip = Duplicate value(s) found. Click for details. -value.goto.tooltip = Click to go to corresponding properties file. -value.similar.tooltip = Similar value(s) found. Click for details. -value.uncomment.tooltip = Uncheck to uncomment this entry. diff --git a/org.eclipse.babel.editor/plugin.properties b/org.eclipse.babel.editor/plugin.properties deleted file mode 100644 index 53fd0c9c..00000000 --- a/org.eclipse.babel.editor/plugin.properties +++ /dev/null @@ -1,22 +0,0 @@ -editor.title = Messages Editor - -plugin.name = Messages Editor Plug-in -plugin.provider = Eclipse.org - -prefs.formatting = Formatting -prefs.performance = Reports - -wizard.category = Messages Editor - -wizard.rb.description = Creates one or a group of properties files. -wizard.rb.title = ResourceBundle - -addNatureAction.label = Enable &localization properties validator -addNatureAction.tooltip = Setup the localization validator builder - -removeNatureAction.label = Disable &localization properties validator -removeNatureAction.tooltip = Remove the localization validator builder - -localizationEditorName = Localization Editor -command_openLocalizationEditor_name = Open Localization Editor -command_openLocalizationEditor_mnemonic = L \ No newline at end of file diff --git a/org.eclipse.babel.editor/plugin.xml b/org.eclipse.babel.editor/plugin.xml deleted file mode 100644 index f749efc8..00000000 --- a/org.eclipse.babel.editor/plugin.xml +++ /dev/null @@ -1,203 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?eclipse version="3.2"?> -<plugin> - <extension - point="org.eclipse.ui.editors"> - <editor - class="org.eclipse.babel.editor.internal.MessagesEditor" - contributorClass="org.eclipse.babel.editor.internal.MessagesEditorContributor" - default="true" - extensions="properties" - icon="icons/propertiesfile.gif" - id="com.essiembre.rbe.eclipse.editor.ResourceBundleEditor" - name="%editor.title"/> - </extension> - <extension - point="org.eclipse.ui.preferencePages"> - <page - name="%editor.title" - class="org.eclipse.babel.editor.preferences.GeneralPrefPage" - id="org.eclipse.babel.editor.preferences.GeneralPrefPage"> - </page> - <page - class="org.eclipse.babel.editor.preferences.FormattingPrefPage" - category="org.eclipse.babel.editor.preferences.GeneralPrefPage" - name="%prefs.formatting" - id="org.eclipse.babel.editor.preferences.FormattingPrefPage"/> - <page - class="org.eclipse.babel.editor.preferences.ReportingPrefPage" - category="org.eclipse.babel.editor.preferences.GeneralPrefPage" - name="%prefs.performance" - id="com.essiembre.eclipse.rbe.ui.preferences.RBEReportingPrefPage"/> - </extension> - <extension - point="org.eclipse.ui.perspectiveExtensions"> - <perspectiveExtension - targetID="org.eclipse.ui.resourcePerspective"> - <view - ratio="0.5" - relative="org.eclipse.ui.views.TaskList" - id="org.eclipse.babel.editor.views.ResourceBundleView" - relationship="right"> - </view> - </perspectiveExtension> - </extension> - <extension - point="org.eclipse.core.runtime.preferences"> - <initializer - class="org.eclipse.babel.editor.preferences.PreferenceInitializer"> - </initializer> - </extension> - - <extension id="nlsmarker" point="org.eclipse.core.resources.markers"/> - <extension - id="nlsproblem" - name="ResourceBundle Editor problems" - point="org.eclipse.core.resources.markers"> - <super type="org.eclipse.core.resources.problemmarker"/> - <super type="org.eclipse.babel.editor.nlsmarker"/> - <attribute name="bundleId"/> - <persistent value="true"/> - </extension> - <extension - id="rbeBuilder" - name="RBE Project Builder" - point="org.eclipse.core.resources.builders"> - <builder hasNature="true"> - <run class="org.eclipse.babel.editor.builder.Builder"/> - </builder> - </extension> - <extension - id="rbeNature" - name="RBE Project Nature" - point="org.eclipse.core.resources.natures"> - <runtime> - <run class="org.eclipse.babel.editor.builder.Nature"/> - </runtime> - <builder id="org.eclipse.babel.editor.rbeBuilder"/> - </extension> - <extension - point="org.eclipse.ui.popupMenus"> - <!--objectContribution - adaptable="true" - id="com.essiembre.rbe.eclipse.contribution1" - nameFilter="*" - objectClass="org.eclipse.core.resources.IProject"> - <action - class="org.eclipse.babel.editor.builder.ToggleNatureAction" - enablesFor="+" - id="com.essiembre.rbe.eclipse.addRemoveNatureAction" - label="Unable/Disable i18n properties validator builder" - menubarPath="additions"/> - </objectContribution--> - - <objectContribution - adaptable="true" - id="com.essiembre.rbe.eclipse.objectContribution2" - objectClass="org.eclipse.core.resources.IProject"> - <visibility> - <and> - <objectState - name="open" - value="true"/> - <not> - <objectState - name="nature" - value="org.eclipse.babel.editor.rbeNature"/> - </not> - </and> - </visibility> - <action - class="org.eclipse.babel.editor.builder.ToggleNatureActionAdd" - enablesFor="1" - id="com.essiembre.rbe.eclipse.addNatureAction" - label="%addNatureAction.label" - menubarPath="additions" - tooltip="%addNatureAction.tooltip"/> - </objectContribution> - <objectContribution - adaptable="true" - id="com.essiembre.rbe.eclipse.objectContribution3" - objectClass="org.eclipse.core.resources.IProject"> - <visibility> - <and> - <objectState - name="open" - value="true"/> - <objectState - name="nature" - value="org.eclipse.babel.editor.rbeNature"/> - </and> - </visibility> - <action - class="org.eclipse.babel.editor.builder.ToggleNatureActionRemove" - enablesFor="1" - id="com.essiembre.rbe.eclipse.removeNatureAction" - label="%removeNatureAction.label" - menubarPath="additions" - tooltip="%removeNatureAction.tooltip"/> - </objectContribution> - </extension> - <extension - id="com.essiembre.rbe.startup" - name="RBE Startup" - point="org.eclipse.ui.startup"> - <startup class="org.eclipse.babel.editor.plugin.Startup"/> - </extension> - <extension - point="org.eclipse.ui.newWizards"> - <category - id="org.eclipse.babel.editor.wizards.ResourceBundle" - name="%wizard.category"> - </category> - <wizard - category="org.eclipse.babel.editor.wizards.ResourceBundle" - class="org.eclipse.babel.editor.wizards.internal.ResourceBundleWizard" - icon="icons/resourcebundle.gif" - id="org.eclipse.babel.editor.wizards.internal.ResourceBundleWizard" - name="%wizard.rb.title"> - <description> - %wizard.rb.description - </description> - </wizard> - </extension> - - - - <extension - point="org.eclipse.ui.elementFactories"> - <factory - class="org.eclipse.pde.nls.internal.ui.editor.LocalizationEditorInputFactory" - id="org.eclipse.pde.nls.ui.LocalizationEditorInputFactory"/> - </extension> - - <extension - point="org.eclipse.ui.editors"> - <editor - class="org.eclipse.pde.nls.internal.ui.editor.LocalizationEditor" - icon="icons/obj16/nls_editor.gif" - id="org.eclipse.pde.nls.ui.LocalizationEditor" - name="%localizationEditorName"/> - </extension> - - <extension - point="org.eclipse.ui.commands"> - <command - defaultHandler="org.eclipse.pde.nls.internal.ui.OpenLocalizationEditorHandler" - id="org.eclipse.pde.nls.ui.OpenLocalizationEditor" - name="%command_openLocalizationEditor_name"> - </command> - </extension> - - <extension - point="org.eclipse.ui.menus"> - <menuContribution - locationURI="menu:edit?after=additions"> - <command - commandId="org.eclipse.pde.nls.ui.OpenLocalizationEditor" - mnemonic="%command_openLocalizationEditor_mnemonic" - style="push"> - </command> - </menuContribution> - </extension> -</plugin> diff --git a/org.eclipse.babel.editor/pom.xml b/org.eclipse.babel.editor/pom.xml deleted file mode 100644 index 29828289..00000000 --- a/org.eclipse.babel.editor/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.editor</artifactId> - <version>0.8.0-SNAPSHOT</version> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file 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 deleted file mode 100644 index 9d397d4c..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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; - -import org.eclipse.babel.core.message.internal.MessagesBundleGroup; - -public interface IMessagesEditor { - String getSelectedKey(); - - void setSelectedKey(String key); - - MessagesBundleGroup getBundleGroup(); - - void setTitleName(String string); - - void setEnabled(boolean enabled); -} 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 deleted file mode 100644 index cce87368..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditorChangeListener.java +++ /dev/null @@ -1,36 +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.internal.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.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java deleted file mode 100644 index a470bb06..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/FilterKeysAction.java +++ /dev/null @@ -1,161 +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.actions; - -import org.eclipse.babel.editor.IMessagesEditorChangeListener; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -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; - -/** - * - * @author Hugues Malphettes - */ -public class FilterKeysAction extends Action { - - private AbstractMessagesEditor 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(ImageDescriptor.createFromImage(getImage())); - - } - - 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; 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(AbstractMessagesEditor 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.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java deleted file mode 100644 index f1df1e55..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/KeyTreeVisibleAction.java +++ /dev/null @@ -1,59 +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.actions; - -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -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; - -/** - * @author Pascal Essiembre - * - */ -public class KeyTreeVisibleAction extends Action { - - private AbstractMessagesEditor 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(AbstractMessagesEditor 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.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java deleted file mode 100644 index 4531a86e..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/actions/NewLocaleAction.java +++ /dev/null @@ -1,103 +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 - * Matthias Lettmayer - implemented action and created dialog - ******************************************************************************/ -package org.eclipse.babel.editor.actions; - -import java.util.Locale; - -import org.eclipse.babel.core.message.internal.MessagesBundleGroup; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.babel.editor.widgets.LocaleSelector; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; - -/** - * @author Pascal Essiembre - * - */ -public class NewLocaleAction extends Action { - - private AbstractMessagesEditor editor; - - /** - * - */ - public NewLocaleAction() { - super("New &Locale..."); - 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(AbstractMessagesEditor editor) { - this.editor = editor; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - // created choose locale dialog - Dialog localeDialog = new Dialog(editor.getSite().getShell()) { - LocaleSelector selector; - - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Add new local"); - } - - @Override - protected Control createDialogArea(Composite parent) { - Composite comp = (Composite) super.createDialogArea(parent); - selector = new LocaleSelector(comp); - return comp; - } - - @Override - protected void okPressed() { - // add local to bundleGroup - MessagesBundleGroup bundleGroup = editor.getBundleGroup(); - Locale newLocal = selector.getSelectedLocale(); - - // exists local already? - boolean existsLocal = false; - Locale[] locales = bundleGroup.getLocales(); - for (Locale locale : locales) { - if (locale == null) { - if (newLocal == null) { - existsLocal = true; - break; - } - } else if (locale.equals(newLocal)) { - existsLocal = true; - break; - } - } - - if (!existsLocal) - bundleGroup.addMessagesBundle(newLocal); - - super.okPressed(); - } - }; - // open dialog - localeDialog.open(); - } -} 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 deleted file mode 100644 index 6e117f55..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.checks.proximity.IProximityAnalyzer; -import org.eclipse.babel.core.message.checks.proximity.LevenshteinDistanceAnalyzer; - -/** - * Provides the {@link IProximityAnalyzer} <br> - * <br> - * - * @author Alexej Strelzow - */ -public class AnalyzerFactory { - - /** - * @return An instance of the {@link LevenshteinDistanceAnalyzer} - */ - public static IProximityAnalyzer getLevenshteinDistanceAnalyzer() { - return (IProximityAnalyzer) 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 deleted file mode 100644 index 335c8e40..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/EditorUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.eclipse.babel.editor.api; - -import org.eclipse.babel.core.message.tree.IKeyTreeNode; -import org.eclipse.babel.editor.i18n.I18NPage; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.IWorkbenchPage; - -/** - * 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) { - AbstractMessagesEditor editor = (AbstractMessagesEditor) 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.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java deleted file mode 100644 index f2e6173b..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.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 deleted file mode 100644 index 5c16b9b6..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.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); - } - - /** - * @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/ValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java deleted file mode 100644 index 2e3eef9b..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.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.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 { - - 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 void setValue(Locale locale, String newValue) { - if (values.containsKey(locale)) - values.remove(locale); - addValue(locale, newValue); - } - - 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.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java deleted file mode 100644 index 779824ff..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Builder.java +++ /dev/null @@ -1,319 +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.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.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; -import org.eclipse.babel.editor.resource.validator.FileMarkerStrategy; -import org.eclipse.babel.editor.resource.validator.IValidationMarkerStrategy; -import org.eclipse.babel.editor.resource.validator.MessagesBundleGroupValidator; -import org.eclipse.babel.editor.util.UIUtils; -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; - -/** - * @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.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java deleted file mode 100644 index 6436f902..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/Nature.java +++ /dev/null @@ -1,92 +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.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.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java deleted file mode 100644 index fdc796b1..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureAction.java +++ /dev/null @@ -1,156 +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.builder; - -import org.eclipse.babel.core.util.BabelUtils; -import org.eclipse.babel.editor.util.UIUtils; -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; - -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.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java deleted file mode 100644 index 3e02bac2..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionAdd.java +++ /dev/null @@ -1,17 +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.builder; - -/** - * @author hmalphettes - */ -public class ToggleNatureActionAdd extends ToggleNatureAction { -} diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.java deleted file mode 100644 index 0574b6ab..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/builder/ToggleNatureActionRemove.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.eclipse.babel.editor.builder; - -/** - * @author hmalphettes - */ -public class ToggleNatureActionRemove extends ToggleNatureAction { - -} 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 deleted file mode 100644 index 36c9b95f..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/BundleGroupRegistry.java +++ /dev/null @@ -1,26 +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.bundle; - -import org.eclipse.babel.core.message.internal.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.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java deleted file mode 100644 index 98f055f9..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/DefaultBundleGroupStrategy.java +++ /dev/null @@ -1,291 +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 - * Alexej Strelzow - TapJI integration, messagesBundleId - ******************************************************************************/ -package org.eclipse.babel.editor.bundle; - -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -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; -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; -import org.eclipse.babel.core.util.BabelUtils; -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.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.core.runtime.IPath; -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; - -/** - * 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.internal.strategy.IMessagesBundleGroupStrategy - * #createMessagesBundleGroupName() - */ - public String createMessagesBundleGroupName() { - return getProjectName() + "*.properties"; - } - - 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) { - // create new empty locale file - IFile openedFile = getOpenedFile(); - IPath path = openedFile.getProjectRelativePath(); - String localeStr = locale != null ? "_" + locale.toString() : ""; - String newFilename = getBaseName() + localeStr + "." - + openedFile.getFileExtension(); - IFile newFile = openedFile.getProject() - .getFile( - path.removeLastSegments(1).addTrailingSeparator() - + newFilename); - - if (!newFile.exists()) { - try { - // create new ifile with an empty input stream - newFile.create(new ByteArrayInputStream(new byte[0]), - IResource.NONE, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } - return createBundle(locale, newFile); - } - - /** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java deleted file mode 100644 index 2b6b5768..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/MessagesBundleGroupFactory.java +++ /dev/null @@ -1,271 +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.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.internal.MessagesBundleGroup; -import org.eclipse.babel.editor.preferences.MsgEditorPreferences; -import org.eclipse.babel.editor.util.UIUtils; -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; - -/** - * @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(); - try { - if (proj == null || !proj.hasNature(UIUtils.PDE_NATURE)) { //$NON-NLS-1$ - return createDefaultBundleGroup(site, file); - } - } catch (CoreException e) { - } - - 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); - } - -} 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 deleted file mode 100644 index d4a78077..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLFragmentBundleGroupStrategy.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.eclipse.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.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; -import org.eclipse.babel.editor.preferences.MsgEditorPreferences; -import org.eclipse.babel.editor.resource.EclipsePropertiesEditorResource; -import org.eclipse.babel.editor.util.UIUtils; -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.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.internal.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.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java deleted file mode 100644 index f1d096a3..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/bundle/NLPluginBundleGroupStrategy.java +++ /dev/null @@ -1,436 +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.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.internal.MessagesBundle; -import org.eclipse.babel.core.util.BabelUtils; -import org.eclipse.babel.editor.util.UIUtils; -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; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/AbstractI18NEntry.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/AbstractI18NEntry.java deleted file mode 100755 index b6c1fd8f..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/AbstractI18NEntry.java +++ /dev/null @@ -1,804 +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 - * Alexej Strelzow - updateKey - ******************************************************************************/ -package org.eclipse.babel.editor.i18n; - -import java.util.Locale; - -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.IMessagesEditorChangeListener; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.babel.editor.widgets.NullableText; -import org.eclipse.jface.bindings.keys.IKeyLookup; -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.KeyListener; -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; - -/** - * Tree for displaying and navigating through resource bundle keys. - * - * @author Pascal Essiembre - */ -public abstract class AbstractI18NEntry extends Composite { - - protected final AbstractMessagesEditor editor; - private final String bundleGroupId; - private final String projectName; - protected final Locale locale; - - private boolean expanded = true; - protected NullableText textBox; - private CBanner banner; - protected String focusGainedText; - - public static final String INSTANCE_CLASS = "org.eclipse.babel.editor.i18n.I18NEntry"; - - private IMessagesEditorChangeListener msgEditorUpdateKey = new MessagesEditorChangeAdapter() { - public void selectedKeyChanged(String oldKey, String newKey) { - updateKey(newKey); - } - }; - - /** - * Constructor. - * - * @param parent - * parent composite - * @param keyTree - * key tree - */ - public AbstractI18NEntry(Composite parent, - final AbstractMessagesEditor 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 AbstractMessagesEditor 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 = editor.getBundleGroup(); - IMessagesBundle bundle = messagesBundleGroup.getMessagesBundle(locale); - return ((TextEditor) bundle.getResource().getSource()).isEditable(); - } - - public String getResourceLocationLabel() { - IMessagesBundleGroup messagesBundleGroup = editor.getBundleGroup(); - 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(getKeyListener()); - - editor.addChangeListener(msgEditorUpdateKey); - } - - abstract void updateKey(String key); - - abstract KeyListener getKeyListener(); - - protected void updateModel() { - if (editor.getSelectedKey() != null) { - if (!BabelUtils.equals(focusGainedText, textBox.getText())) { - // IMessagesBundleGroup messagesBundleGroup = - // RBManager.getInstance(projectName).getMessagesBundleGroup(bundleGroupId); - IMessagesBundleGroup messagesBundleGroup = editor - .getBundleGroup(); - String key = editor.getSelectedKey(); - IMessage entry = messagesBundleGroup.getMessage(key, locale); - if (entry == null) { - entry = new Message(key, locale); - IMessagesBundle messagesBundle = messagesBundleGroup - .getMessagesBundle(locale); - if (messagesBundle != null) { - messagesBundle.addMessage(entry); - } - } - entry.setText(textBox.getText()); - } - } - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - textBox.setEnabled(enabled); - } - - @Override - public void dispose() { - editor.removeChangeListener(msgEditorUpdateKey); - super.dispose(); - } - -} - -// 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.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java deleted file mode 100644 index eae73818..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryLeftBanner.java +++ /dev/null @@ -1,115 +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.i18n; - -import java.util.Locale; - -import org.eclipse.babel.editor.i18n.actions.FoldingAction; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.babel.editor.widgets.ActionButton; -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; - -/** - * 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 AbstractI18NEntry 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.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java deleted file mode 100644 index 48a077eb..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/EntryRightBanner.java +++ /dev/null @@ -1,161 +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.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.IMessageCheck; -import org.eclipse.babel.core.message.checks.internal.DuplicateValueCheck; -import org.eclipse.babel.core.message.checks.internal.MissingValueCheck; -import org.eclipse.babel.editor.IMessagesEditorChangeListener; -import org.eclipse.babel.editor.i18n.actions.ShowDuplicateAction; -import org.eclipse.babel.editor.i18n.actions.ShowMissingAction; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter; -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.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.ui.ISharedImages; -import org.eclipse.ui.PlatformUI; - -/** - * 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 AbstractMessagesEditor editor; - private final AbstractI18NEntry i18nEntry; - private final Locale locale; - private final Observer observer = new Observer() { - public void update(Observable o, Object arg) { - updateMarkers(); - } - }; - private final IMessagesEditorChangeListener msgEditorChangeListener = new MessagesEditorChangeAdapter() { - public void selectedKeyChanged(String oldKey, String newKey) { - updateMarkers(); - } - }; - - /** - * Constructor. - * - * @param parent - * parent composite - * @param keyTree - * key tree - */ - public EntryRightBanner(Composite parent, final AbstractI18NEntry 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(msgEditorChangeListener); - editor.getMarkers().addObserver(observer); - } - - /** - * @param warningIcon - * @param colon - */ - private void updateMarkers() { - Display display = toolBarMgr.getControl().getDisplay(); - // [RAP] only update markers, which belong to this UIThread - if (display.equals(Display.getCurrent()) && !isDisposed()) { - display.asyncExec(new Runnable() { - public void run() { - if (isDisposed()) - return; - // 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; - } - - @Override - public void dispose() { - editor.removeChangeListener(msgEditorChangeListener); - editor.getMarkers().deleteObserver(observer); - super.dispose(); - } -} 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 deleted file mode 100644 index f9c65a57..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java +++ /dev/null @@ -1,295 +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 - * Alexej Strelzow - TapiJI integration, fixed issues 37, 48 - ******************************************************************************/ -package org.eclipse.babel.editor.i18n; - -import java.lang.reflect.Constructor; -import java.util.Collection; -import java.util.HashMap; -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.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.internal.MessagesEditorChangeAdapter; -import org.eclipse.babel.editor.tree.actions.AbstractRenameKeyAction; -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; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IPartListener; -import org.eclipse.ui.IWorkbenchPart; - -/** - * 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; - - protected final AbstractMessagesEditor editor; - protected final SideNavComposite keysComposite; - private final Composite valuesComposite; - private final Map<Locale, AbstractI18NEntry> entryComposites = new HashMap<Locale, AbstractI18NEntry>(); - private Composite entriesComposite; - - // 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 AbstractMessagesEditor 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) { - // [RAP] only update tree, which belongs to this UIThread - if (!keysComposite.isDisposed()) { - Display display = keysComposite.getTreeViewer().getTree() - .getDisplay(); - if (display.equals(Display.getCurrent())) { - AbstractI18NEntry 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); - - 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]; - addI18NEntry(locale); - } - - 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 addI18NEntry(Locale locale) { - AbstractI18NEntry i18NEntry = null; - try { - Class<?> clazz = Class.forName(AbstractI18NEntry.INSTANCE_CLASS); - Constructor<?> cons = clazz.getConstructor(Composite.class, - AbstractMessagesEditor.class, Locale.class); - i18NEntry = (AbstractI18NEntry) cons.newInstance(entriesComposite, - editor, locale); - } catch (Exception e) { - e.printStackTrace(); - } - // entryComposite.addFocusListener(localBehaviour); - entryComposites.put(locale, i18NEntry); - entriesComposite.layout(); - } - - public void removeI18NEntry(Locale locale) { - AbstractI18NEntry i18NEntry = entryComposites.get(locale); - if (i18NEntry != null) { - i18NEntry.dispose(); - entryComposites.remove(locale); - entriesComposite.layout(); - } - } - - public void selectLocale(Locale locale) { - Collection<Locale> locales = entryComposites.keySet(); - for (Locale entryLocale : locales) { - AbstractI18NEntry 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); - } - - public TreeViewer getTreeViewer() { - return keysComposite.getTreeViewer(); - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - for (AbstractI18NEntry entry : entryComposites.values()) - entry.setEnabled(enabled); - } - - public void setEnabled(boolean enabled, Locale locale) { - // super.setEnabled(enabled); - for (AbstractI18NEntry entry : entryComposites.values()) { - if (locale == entry.getLocale() - || (locale != null && locale.equals(entry.getLocale()))) { - entry.setEnabled(enabled); - break; - } - } - } - - public SideNavTextBoxComposite getSidNavTextBoxComposite() { - return keysComposite.getSidNavTextBoxComposite(); - } -} 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 deleted file mode 100644 index b31a4f86..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavComposite.java +++ /dev/null @@ -1,137 +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.i18n; - -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -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; -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; - -/** - * Tree for displaying and navigating through resource bundle keys. - * - * @author Pascal Essiembre - */ -public class SideNavComposite extends Composite { - - /** Key Tree Viewer. */ - private TreeViewer treeViewer; - - private AbstractMessagesEditor editor; - - private SideNavTextBoxComposite textBoxComp; - - /** - * Constructor. - * - * @param parent - * parent composite - * @param keyTree - * key tree - */ - public SideNavComposite(Composite parent, - final AbstractMessagesEditor 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(); - textBoxComp = 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); - - } - - public SideNavTextBoxComposite getSidNavTextBoxComposite() { - return textBoxComp; - } -} 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 deleted file mode 100644 index fcca5ca8..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/SideNavTextBoxComposite.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.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.internal.AbstractMessagesEditor; -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; -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; - -/** - * 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 Button addButton; - private AbstractMessagesEditor editor; - - /** - * Constructor. - * - * @param parent - * parent composite - * @param keyTree - * key tree - */ - public SideNavTextBoxComposite(Composite parent, - final AbstractMessagesEditor 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 - 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; - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - addButton.setEnabled(enabled); - } -} diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.java deleted file mode 100644 index b59c3304..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/FoldingAction.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.editor.i18n.actions; - -import org.eclipse.babel.editor.i18n.AbstractI18NEntry; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.action.Action; - -/** - * @author Pascal Essiembre - * - */ -public class FoldingAction extends Action { - - private final AbstractI18NEntry i18NEntry; - private boolean expanded; - - /** - * - */ - public FoldingAction(AbstractI18NEntry 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.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 deleted file mode 100644 index 54d873ac..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowDuplicateAction.java +++ /dev/null @@ -1,70 +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.i18n.actions; - -import java.util.Locale; - -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.action.Action; -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; - - /** - * - */ - 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"); - - 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/i18n/actions/ShowMissingAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.java deleted file mode 100644 index 91ce116e..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowMissingAction.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.editor.i18n.actions; - -import java.util.Locale; - -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.widgets.Display; - -/** - * @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.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.java deleted file mode 100644 index 4766da56..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/actions/ShowSimilarAction.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.eclipse.babel.editor.i18n.actions; - -import java.util.Locale; - -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.widgets.Display; - -/** - * @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.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java deleted file mode 100755 index 678639c1..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java +++ /dev/null @@ -1,614 +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 - * 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.IMessagesBundleGroupListener; -import org.eclipse.babel.core.message.internal.IMessagesBundleListener; -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.internal.MessagesBundleGroupAdapter; -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.swt.graphics.Image; -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 abstract class AbstractMessagesEditor 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$ - - protected String selectedKey; - protected List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>( - 2); - - /** MessagesBundle group. */ - protected MessagesBundleGroup messagesBundleGroup; - - /** Page with key tree and text fields for all locales. */ - protected I18NPage i18nPage; - protected final List<Locale> localesIndex = new ArrayList<Locale>(); - protected final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>(); - - protected MessagesBundleGroupOutline outline; - - protected MessagesEditorMarkers markers; - - protected AbstractKeyTreeModel keyTreeModel; - - protected IFile file; // init - - protected boolean updateSelectedKey; - - /** - * Creates a multi-page editor example. - */ - public AbstractMessagesEditor() { - 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$ - } - messagesBundleGroup - .addMessagesBundleGroupListener(getMsgBundleGroupListner()); - 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$ - } - initRAP(); - } - - // 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 - 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); - createMessagesBundlePage(messagesBundle); - } - } - - /** - * Creates a new text editor for the messages bundle, which gets added to a new page - */ - protected void createMessagesBundlePage(MessagesBundle messagesBundle) { - try { - IMessagesResource resource = messagesBundle.getResource(); - final TextEditor textEditor = (TextEditor) resource.getSource(); - int index = addPage(textEditor, textEditor.getEditorInput()); - setPageText(index, - UIUtils.getDisplayName(messagesBundle.getLocale())); - setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE)); - localesIndex.add(messagesBundle.getLocale()); - textEditorsIndex.add(textEditor); - } catch (PartInitException e) { - ErrorDialog.openError(getSite().getShell(), - "Error creating text editor page.", //$NON-NLS-1$ - null, e.getStatus()); - } - } - - /** - * Adds a new messages bundle to an opened messages editor. Creates a new text edtor page - * and a new entry in the i18n page for the given locale and messages bundle. - */ - protected void addMessagesBundle(MessagesBundle messagesBundle) { - createMessagesBundlePage(messagesBundle); - i18nPage.addI18NEntry(messagesBundle.getLocale()); - } - - /** - * Removes the text editor page + the entry from the i18n page of the given locale and messages bundle. - */ - protected void removeMessagesBundle(MessagesBundle messagesBundle) { - IMessagesResource resource = messagesBundle.getResource(); - final TextEditor textEditor = (TextEditor) resource.getSource(); - // index + 1 because of i18n page - int pageIndex = textEditorsIndex.indexOf(textEditor) + 1; - removePage(pageIndex); - - textEditorsIndex.remove(textEditor); - localesIndex.remove(messagesBundle.getLocale()); - - textEditor.dispose(); - - // remove entry from i18n page - i18nPage.removeI18NEntry(messagesBundle.getLocale()); - } - - /** - * 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? - } - - protected 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; - } - - protected 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 AbstractMessagesEditor) { - AbstractMessagesEditor rbe = (AbstractMessagesEditor) 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(); - } - - disposeRAP(); - } - - /** - * @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); - } - - // Needed for RAP, otherwise super implementation of getTitleImage always - // returns - // same image with same device and same session context, and when this - // session ends - // -> NPE at org.eclipse.swt.graphics.Image.getImageData(Image.java:348) - @Override - public Image getTitleImage() { - // create new image with current display - return UIUtils.getImageDescriptor(UIUtils.IMAGE_RESOURCE_BUNDLE) - .createImage(); - } - - public void setTitleName(String name) { - setPartName(name); - } - - abstract public void setEnabled(boolean enabled); - - abstract protected void initRAP(); - - abstract protected void disposeRAP(); - - abstract protected IMessagesBundleGroupListener getMsgBundleGroupListner(); -} 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 deleted file mode 100644 index f98eb3da..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorChangeAdapter.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.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 deleted file mode 100644 index adc2731c..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorContributor.java +++ /dev/null @@ -1,228 +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.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); - AbstractMessagesEditor me = part instanceof AbstractMessagesEditor ? (AbstractMessagesEditor) part - : null; - toggleKeyTreeAction.setEditor(me); - ((FilterKeysActionGroup) FILTERS).setActiveEditor(part); - newLocaleAction.setEditor(me); - } - - /** - * 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) { - AbstractMessagesEditor me = part instanceof AbstractMessagesEditor ? (AbstractMessagesEditor) 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 deleted file mode 100644 index 8f234595..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditorMarkers.java +++ /dev/null @@ -1,239 +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.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 deleted file mode 100644 index 9a1a9ba5..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/MessagesEditorPlugin.java +++ /dev/null @@ -1,398 +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.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 java.util.Stack; - -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; -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.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; - -/** - * 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>>(); - } - - 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(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); - try { - Display.getDefault().asyncExec(new Runnable() { - - public void run() { - Display.getDefault().addFilter(SWT.KeyUp, - new UndoKeyListener()); - - } - }); - } catch (NullPointerException e) { - // TODO [RAP] Non UI-Thread, no default display available, in RAP - // multiple clients and displays - } - } - - /** - * @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.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/plugin/Startup.java deleted file mode 100644 index b577b710..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java deleted file mode 100644 index 751f80d7..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/AbstractPrefPage.java +++ /dev/null @@ -1,183 +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.preferences; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.babel.editor.util.UIUtils; -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; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/FormattingPrefPage.java deleted file mode 100644 index d20f0798..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.babel.editor.preferences; - -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java deleted file mode 100644 index bd9775e2..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/GeneralPrefPage.java +++ /dev/null @@ -1,228 +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.preferences; - -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java deleted file mode 100644 index ff802eb4..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/MsgEditorPreferences.java +++ /dev/null @@ -1,762 +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 - * Alexej Strelzow - externalized IPropertiesSerializerConfig and - * IPropertiesDeserializerConfig for better reuse - ******************************************************************************/ -package org.eclipse.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.babel.editor.IMessagesEditorChangeListener; -import org.eclipse.babel.editor.builder.Builder; -import org.eclipse.babel.editor.builder.ToggleNatureAction; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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; - -/** - * 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 AbstractMessagesEditor) { - // the editor was loaded. reload it: - AbstractMessagesEditor meToReload = (AbstractMessagesEditor) 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java deleted file mode 100644 index 94cc2ac3..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PreferenceInitializer.java +++ /dev/null @@ -1,109 +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.preferences; - -import org.eclipse.babel.editor.IMessagesEditorChangeListener; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.java deleted file mode 100644 index e610cf31..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesDeserializerConfig.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 - * Alexej Strelzow - moved code to here - ******************************************************************************/ -package org.eclipse.babel.editor.preferences; - -import org.eclipse.babel.core.configuration.ConfigurationManager; -import org.eclipse.babel.core.message.resource.ser.IPropertiesDeserializerConfig; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.core.runtime.Preferences; - -/** - * The concrete implementation of {@link IPropertiesDeserializerConfig}. - * - * @author Alexej Strelzow - */ -public class PropertiesDeserializerConfig implements - IPropertiesDeserializerConfig { // Moved from MsgEditorPreferences, to - // make it more flexible. - - /** 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.java deleted file mode 100644 index ee975d7f..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/PropertiesSerializerConfig.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 - * Alexej Strelzow - moved code to here - ******************************************************************************/ -package org.eclipse.babel.editor.preferences; - -import org.eclipse.babel.core.configuration.ConfigurationManager; -import org.eclipse.babel.core.message.resource.ser.IPropertiesSerializerConfig; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.core.runtime.Preferences; - -/** - * 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 = 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.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java deleted file mode 100644 index 1180acad..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/preferences/ReportingPrefPage.java +++ /dev/null @@ -1,222 +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.preferences; - -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java deleted file mode 100644 index 576f862c..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/EclipsePropertiesEditorResource.java +++ /dev/null @@ -1,199 +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 - * 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.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; -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.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 deleted file mode 100644 index e05f634a..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.babel.editor.resource.validator; - -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; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; - -/** - * @author Pascal Essiembre - * - */ -public class FileMarkerStrategy implements IValidationMarkerStrategy { - - /** - * @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) { - 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.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java deleted file mode 100644 index 8da937ef..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/IValidationMarkerStrategy.java +++ /dev/null @@ -1,20 +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.resource.validator; - -/** - * @author Pascal Essiembre - * - */ -public interface IValidationMarkerStrategy { - - void markFailed(ValidationFailureEvent event); -} 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 deleted file mode 100644 index 72422115..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/MessagesBundleGroupValidator.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.eclipse.babel.editor.resource.validator; - -import java.util.Locale; - -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; - -/** - * @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.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 deleted file mode 100644 index df34cb92..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/resource/validator/ValidationFailureEvent.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.eclipse.babel.editor.resource.validator; - -import java.util.Locale; - -import org.eclipse.babel.core.message.checks.IMessageCheck; -import org.eclipse.babel.core.message.internal.MessagesBundleGroup; - -/** - * @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.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java deleted file mode 100644 index 3ba1a290..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java +++ /dev/null @@ -1,23 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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/actions/AbstractRenameKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractRenameKeyAction.java deleted file mode 100644 index f52f0656..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractRenameKeyAction.java +++ /dev/null @@ -1,39 +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.editor.internal.AbstractMessagesEditor; -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(AbstractMessagesEditor 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 deleted file mode 100644 index ddc8b1c2..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AbstractTreeAction.java +++ /dev/null @@ -1,93 +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.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.AbstractMessagesEditor; -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; - -/** - * @author Pascal Essiembre - * - */ -public abstract class AbstractTreeAction extends Action { - - // private static final KeyTreeNode[] EMPTY_TREE_NODES = new - // KeyTreeNode[]{}; - - protected final TreeViewer treeViewer; - protected final AbstractMessagesEditor editor; - - /** - * - */ - public AbstractTreeAction(AbstractMessagesEditor editor, - TreeViewer treeViewer) { - super(); - this.treeViewer = treeViewer; - this.editor = editor; - } - - /** - * - */ - public AbstractTreeAction(AbstractMessagesEditor 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 AbstractMessagesEditor getEditor() { - return editor; - } - - protected Shell getShell() { - return treeViewer.getTree().getShell(); - } -} 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 deleted file mode 100644 index 663a72c6..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/AddKeyAction.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.eclipse.babel.editor.tree.actions; - -import org.eclipse.babel.core.message.internal.MessagesBundleGroup; -import org.eclipse.babel.core.message.tree.internal.KeyTreeNode; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.dialogs.IInputValidator; -import org.eclipse.jface.dialogs.InputDialog; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.window.Window; - -/** - * @author Pascal Essiembre - * - */ -public class AddKeyAction extends AbstractTreeAction { - - /** - * - */ - public AddKeyAction(AbstractMessagesEditor 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() - */ - @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); - } - } - -} 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 deleted file mode 100644 index 81eadbe8..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/CollapseAllAction.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.editor.tree.actions; - -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.viewers.TreeViewer; - -/** - * @author Pascal Essiembre - * - */ -public class CollapseAllAction extends AbstractTreeAction { - - /** - * @param editor - * @param treeViewer - */ - public CollapseAllAction(AbstractMessagesEditor 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.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 deleted file mode 100644 index ab62966d..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.babel.editor.tree.actions; - -import org.eclipse.babel.core.message.internal.MessagesBundleGroup; -import org.eclipse.babel.core.message.tree.internal.KeyTreeNode; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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; - -/** - * @author Pascal Essiembre - * - */ -public class DeleteKeyAction extends AbstractTreeAction { - - /** - * - */ - public DeleteKeyAction(AbstractMessagesEditor 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.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 deleted file mode 100644 index 119e4347..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/ExpandAllAction.java +++ /dev/null @@ -1,41 +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.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.viewers.TreeViewer; - -/** - * @author Pascal Essiembre - * - */ -public class ExpandAllAction extends AbstractTreeAction { - - /** - * @param editor - * @param treeViewer - */ - public ExpandAllAction(AbstractMessagesEditor 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.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 deleted file mode 100644 index 22df9687..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/FlatModelAction.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.editor.tree.actions; - -import org.eclipse.babel.core.message.tree.TreeType; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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; - -/** - * @author Pascal Essiembre - * - */ -public class FlatModelAction extends AbstractTreeAction { - - /** - * @param editor - * @param treeViewer - */ - public FlatModelAction(AbstractMessagesEditor 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.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RefactorKeyAction.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RefactorKeyAction.java deleted file mode 100644 index d85c913e..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/RefactorKeyAction.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.editor.tree.actions; - -import org.eclipse.babel.core.message.manager.RBManager; -import org.eclipse.babel.core.message.tree.internal.KeyTreeNode; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.jface.viewers.TreeViewer; - -/** - * An action, which triggers the refactoring of message keys. - * - * @author Alexej Strelzow - */ -public class RefactorKeyAction extends AbstractTreeAction { - - /** - * Constructor. - * - * @param editor - * The {@link MessagesEditor} - * @param treeViewer - * The {@link TreeViewer} - */ - public RefactorKeyAction(AbstractMessagesEditor editor, - TreeViewer treeViewer) { - super(editor, treeViewer); - setText(MessagesEditorPlugin.getString("key.refactor") + " ..."); //$NON-NLS-1$ - setImageDescriptor(UIUtils - .getImageDescriptor(UIUtils.IMAGE_REFACTORING)); - setToolTipText("Refactor the name of the key"); - } - - /** - * @see org.eclipse.jface.action.Action#run() - */ - @Override - public void run() { - KeyTreeNode node = getNodeSelection(); - - String key = node.getMessageKey(); - String bundleId = node.getMessagesBundleGroup().getResourceBundleId(); - String projectName = node.getMessagesBundleGroup().getProjectName(); - - RBManager.getRefactorService().openRefactorDialog(projectName, - bundleId, key, null); - - } -} 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 deleted file mode 100644 index 6bceab16..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/actions/TreeModelAction.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.eclipse.babel.editor.tree.actions; - -import org.eclipse.babel.core.message.tree.TreeType; -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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; - -/** - * @author Pascal Essiembre - * - */ -public class TreeModelAction extends AbstractTreeAction { - - /** - * @param editor - * @param treeViewer - */ - public TreeModelAction(AbstractMessagesEditor 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.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 deleted file mode 100644 index afec5a35..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContentProvider.java +++ /dev/null @@ -1,143 +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.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 deleted file mode 100644 index 5ba54ca4..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java +++ /dev/null @@ -1,440 +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.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.AbstractMessagesEditor; -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.AbstractRenameKeyAction; -import org.eclipse.babel.editor.tree.actions.AddKeyAction; -import org.eclipse.babel.editor.tree.actions.DeleteKeyAction; -import org.eclipse.babel.editor.tree.actions.RefactorKeyAction; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.viewers.CellEditor; -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.TextCellEditor; -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; - -/** - * @author Pascal Essiembre - * - */ -public class KeyTreeContributor implements IKeyTreeContributor { - - private AbstractMessagesEditor editor; - private AbstractKeyTreeModel treeModel; - private TreeType treeType; - - /** - * - */ - public KeyTreeContributor(final AbstractMessagesEditor 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(); - - treeViewer.setColumnProperties(new String[] { "column1" }); - treeViewer.setCellEditors(new CellEditor[] { new TextCellEditor( - treeViewer.getTree()) }); - } - - 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 display = treeViewer.getTree().getDisplay(); - // [RAP] only refresh tree viewer in this UIThread - if (display.equals(Display.getCurrent())) { - display.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() { - if (!editor.getI18NPage().isDisposed()) { - treeViewer.refresh(true); - } - } - }); - }; - - // public void nodeChanged(KeyTreeNode node) { - // treeViewer.refresh(true); - // }; - public void nodeRemoved(KeyTreeNode node) { - Display.getDefault().asyncExec(new Runnable() { - public void run() { - if (!editor.getI18NPage().isDisposed()) { - 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( - AbstractMessagesEditor.class, TreeViewer.class); - renameKeyAction = (AbstractRenameKeyAction) cons.newInstance( - editor, treeViewer); - } catch (Exception e) { - e.printStackTrace(); - } - final IAction renameAction = renameKeyAction; - menuManager.add(renameAction); - - // Refactor - final IAction refactorAction = new RefactorKeyAction(editor, treeViewer); - menuManager.add(refactorAction); - - 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 deleted file mode 100644 index 8dd3a5a6..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeLabelProvider.java +++ /dev/null @@ -1,277 +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.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.AbstractMessagesEditor; -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 AbstractMessagesEditor 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(AbstractMessagesEditor 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/OverlayImageIcon.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java deleted file mode 100644 index ba9b24b9..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/OverlayImageIcon.java +++ /dev/null @@ -1,97 +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.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.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java deleted file mode 100644 index 1e3d0d5a..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/util/UIUtils.java +++ /dev/null @@ -1,630 +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.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.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -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.babel.editor.compat.SwtRapCompatibilitySWT; -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.Plugin; -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; -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; - -/** - * 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. */ - /** Name of refactoring icon. */ - public static final String IMAGE_REFACTORING = "refactoring.png"; //$NON-NLS-1$ - 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.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 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 = null; - try { - // [RAP] In RAP multiple displays could exist (multiple user), - // therefore image needs to be created every time with the current - // display - Method getImageRAP = Class.forName( - "org.eclipse.babel.editor.util.UIUtilsRAP").getMethod( - "getImage", String.class); - image = (Image) getImageRAP.invoke(null, imageName); - } catch (Exception e) { - // RAP fragment not running --> invoke rcp version - image = getImageRCP(imageName); - } - - return image; - } - - /** - * Gets an image from image registry or creates a new one if it the first - * time. - * - * @param imageName - * image name - * @return image - */ - private static Image getImageRCP(String 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); - } - 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 - * @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 SwtRapCompatibilitySWT.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 { - 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); - 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.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.java deleted file mode 100644 index b6de9381..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/views/MessagesBundleGroupOutline.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.editor.views; - -import org.eclipse.babel.editor.internal.AbstractMessagesEditor; -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; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.views.contentoutline.ContentOutlinePage; - -/** - * This outline provides a view for the property keys coming with with a - * ResourceBundle - */ -public class MessagesBundleGroupOutline extends ContentOutlinePage { - - private final AbstractMessagesEditor editor; - - public MessagesBundleGroupOutline(AbstractMessagesEditor 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.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java deleted file mode 100644 index caffc0e8..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/ActionButton.java +++ /dev/null @@ -1,44 +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.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.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.java deleted file mode 100644 index c7302c2a..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/LocaleSelector.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.eclipse.babel.editor.widgets; - -import java.text.Collator; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Locale; - -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.babel.editor.util.UIUtils; -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; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java deleted file mode 100644 index 4e0678a8..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/widgets/NullableText.java +++ /dev/null @@ -1,207 +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.widgets; - -import java.util.Stack; - -import org.eclipse.babel.editor.util.UIUtils; -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; - -/** - * 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); - text.setData("UNDO", new Stack<String>()); - text.setData("REDO", new Stack<String>()); - 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(); - } - Stack<String> undoCache = (Stack<String>) this.text.getData("UNDO"); - undoCache.push(this.text.getText()); - } - - 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); - } - - // 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 deleted file mode 100644 index 8965166d..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.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/internal/ResourceBundleNewWizardPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java deleted file mode 100644 index 43dde1a1..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java +++ /dev/null @@ -1,484 +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 - * Clemente Lodi-Fè - fixing bugs and setting dialog defaults - ******************************************************************************/ - -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: droy $ $Revision: 1.2 $ $Date: 2012/07/18 20:13:09 $ - */ -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 deleted file mode 100644 index 760b97cc..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleWizard.java +++ /dev/null @@ -1,313 +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 - * 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/OpenLocalizationEditorHandler.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java deleted file mode 100644 index e82c1510..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/OpenLocalizationEditorHandler.java +++ /dev/null @@ -1,46 +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.eclipse.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.pde.nls.internal.ui.editor.LocalizationEditor; -import org.eclipse.pde.nls.internal.ui.editor.LocalizationEditorInput; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.handlers.HandlerUtil; - -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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java deleted file mode 100644 index 837e505e..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/ConfigureColumnsDialog.java +++ /dev/null @@ -1,207 +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.eclipse.pde.nls.internal.ui.dialogs; - -import java.util.ArrayList; - -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.layout.GridDataFactory; -import org.eclipse.pde.nls.internal.ui.parser.LocaleUtil; -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; - -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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.java deleted file mode 100644 index 5345127f..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditMultiLineEntryDialog.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.eclipse.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.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 deleted file mode 100644 index 5be8dada..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/EditResourceBundleEntriesDialog.java +++ /dev/null @@ -1,433 +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.eclipse.pde.nls.internal.ui.dialogs; - -import java.util.ArrayList; -import java.util.Locale; - -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; -import org.eclipse.babel.editor.preferences.MsgEditorPreferences; -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.pde.nls.internal.ui.model.ResourceBundle; -import org.eclipse.pde.nls.internal.ui.model.ResourceBundleKey; -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; - -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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptions.java deleted file mode 100644 index 10dfa09b..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.pde.nls.internal.ui.dialogs; - -public class FilterOptions { - - public boolean filterPlugins; - public String[] pluginPatterns; - public boolean keysWithMissingEntriesOnly; - -} diff --git a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java deleted file mode 100644 index 6c6ab5d9..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/dialogs/FilterOptionsDialog.java +++ /dev/null @@ -1,120 +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.eclipse.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.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 deleted file mode 100644 index 7fd7ed82..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditor.java +++ /dev/null @@ -1,1168 +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.eclipse.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.babel.editor.compat.SwtRapCompatibilityFormToolkit; -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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.pde.nls.internal.ui.dialogs.ConfigureColumnsDialog; -import org.eclipse.pde.nls.internal.ui.dialogs.EditResourceBundleEntriesDialog; -import org.eclipse.pde.nls.internal.ui.dialogs.FilterOptions; -import org.eclipse.pde.nls.internal.ui.dialogs.FilterOptionsDialog; -import org.eclipse.pde.nls.internal.ui.model.ResourceBundle; -import org.eclipse.pde.nls.internal.ui.model.ResourceBundleFamily; -import org.eclipse.pde.nls.internal.ui.model.ResourceBundleKey; -import org.eclipse.pde.nls.internal.ui.model.ResourceBundleKeyList; -import org.eclipse.pde.nls.internal.ui.model.ResourceBundleModel; -import org.eclipse.pde.nls.internal.ui.parser.LocaleUtil; -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; - -// 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; - } - - @Override - 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() - */ - @Override - 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); - 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("")) { - 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); - 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); - 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); - 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]); - 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); - 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)" }); - 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\">&nbsp;</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 SwtRapCompatibilityFormToolkit toolkit = new SwtRapCompatibilityFormToolkit(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() { - @Override - 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("")) { - 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(@SuppressWarnings("rawtypes") 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.java deleted file mode 100644 index 69675ccc..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInput.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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java deleted file mode 100644 index 2dd0d1a6..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/editor/LocalizationEditorInputFactory.java +++ /dev/null @@ -1,32 +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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java deleted file mode 100644 index 0e55482e..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundle.java +++ /dev/null @@ -1,177 +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.eclipse.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.babel.editor.plugin.MessagesEditorPlugin; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jdt.core.IJarEntryResource; - -/** - * 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleElement.java deleted file mode 100644 index 0309b8e7..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java deleted file mode 100644 index aa179990..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleFamily.java +++ /dev/null @@ -1,135 +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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKey.java deleted file mode 100644 index 660f23e1..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleKeyList.java deleted file mode 100644 index df3b846c..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/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.eclipse.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.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 deleted file mode 100644 index c03c9774..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/model/ResourceBundleModel.java +++ /dev/null @@ -1,572 +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.eclipse.pde.nls.internal.ui.model; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Locale; - -import org.eclipse.babel.editor.plugin.MessagesEditorPlugin; -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.osgi.service.resolver.BundleDescription; - -/** - * 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); - } - - /** - * @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; - - 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 - } - - 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); - } - } - } - } - - // 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); - } - } - - } - } 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), - 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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java deleted file mode 100644 index 436a3583..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/CharArraySource.java +++ /dev/null @@ -1,261 +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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java deleted file mode 100644 index b1f422c4..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/IScannerSource.java +++ /dev/null @@ -1,149 +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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java deleted file mode 100644 index 72db6bd1..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LexicalErrorException.java +++ /dev/null @@ -1,87 +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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java deleted file mode 100644 index fd900c98..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/LocaleUtil.java +++ /dev/null @@ -1,57 +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.eclipse.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.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java b/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java deleted file mode 100644 index 7688666b..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/pde/nls/internal/ui/parser/RawBundle.java +++ /dev/null @@ -1,332 +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.eclipse.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.eclipse.babel.editor/tests/CVS/Entries b/org.eclipse.babel.editor/tests/CVS/Entries deleted file mode 100644 index bf15d75c..00000000 --- a/org.eclipse.babel.editor/tests/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -D/org//// diff --git a/org.eclipse.babel.editor/tests/CVS/Repository b/org.eclipse.babel.editor/tests/CVS/Repository deleted file mode 100644 index 4cc4ec8a..00000000 --- a/org.eclipse.babel.editor/tests/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/tests diff --git a/org.eclipse.babel.editor/tests/CVS/Root b/org.eclipse.babel.editor/tests/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/tests/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/tests/org/CVS/Entries b/org.eclipse.babel.editor/tests/org/CVS/Entries deleted file mode 100644 index a6aa022d..00000000 --- a/org.eclipse.babel.editor/tests/org/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -D/eclipse//// diff --git a/org.eclipse.babel.editor/tests/org/CVS/Repository b/org.eclipse.babel.editor/tests/org/CVS/Repository deleted file mode 100644 index d28adedc..00000000 --- a/org.eclipse.babel.editor/tests/org/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/tests/org diff --git a/org.eclipse.babel.editor/tests/org/CVS/Root b/org.eclipse.babel.editor/tests/org/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/tests/org/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/tests/org/eclipse/CVS/Entries b/org.eclipse.babel.editor/tests/org/eclipse/CVS/Entries deleted file mode 100644 index b4ed539f..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -D/nls//// diff --git a/org.eclipse.babel.editor/tests/org/eclipse/CVS/Repository b/org.eclipse.babel.editor/tests/org/eclipse/CVS/Repository deleted file mode 100644 index 678f9670..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/tests/org/eclipse diff --git a/org.eclipse.babel.editor/tests/org/eclipse/CVS/Root b/org.eclipse.babel.editor/tests/org/eclipse/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Entries b/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Entries deleted file mode 100644 index db5b03e7..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -D/ui//// diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Repository b/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Repository deleted file mode 100644 index 66ada60b..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/tests/org/eclipse/nls diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Root b/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Entries b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Entries deleted file mode 100644 index e38c63e4..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Entries +++ /dev/null @@ -1 +0,0 @@ -D/tests//// diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Repository b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Repository deleted file mode 100644 index a6693c83..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/tests/org/eclipse/nls/ui diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Root b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Entries b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Entries deleted file mode 100644 index c1a7df40..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Entries +++ /dev/null @@ -1,2 +0,0 @@ -/PropertiesTest.java/1.2/Tue Feb 10 05:54:12 2009// -/RawBundleTest.java/1.1/Sun Aug 17 05:21:11 2008// diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Repository b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Repository deleted file mode 100644 index e40d3051..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.babel/plugins/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Root b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Root deleted file mode 100644 index b52d3bd3..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:pserver:[email protected]:/cvsroot/technology diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java deleted file mode 100644 index 48640d98..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/PropertiesTest.java +++ /dev/null @@ -1,61 +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.eclipse.nls.ui.tests; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Properties; - -import junit.framework.TestCase; - -public class PropertiesTest extends TestCase { - - private Properties properties; - - public void test() throws IOException { - String input = " # a comment line\r\n" + "key1=value1\r\n" - + "key2=a value \\\r\n" + " on two lines\r\n" - + "key3=a value \\\r\n" + " " - + " with an empty line in between\r\n"; - properties = readProperties(input); - assertValue("value1", "key1"); - assertValue("a value on two lines", "key2"); - assertValue("a value with an empty line in between", "key3"); - } - - public void testKeysWithWhitespace() throws IOException { - String input = "" + "key1\t=key with tab\r\n" - + "key\\ 2 =key with escaped space\r\n" - + "key 3 =key with space\r\n"; - properties = readProperties(input); - assertValue("key with tab", "key1"); - assertValue("key with escaped space", "key 2"); - assertValue("3 =key with space", "key"); - } - - public void testKeysWithMissingValue() throws IOException { - String input = "" + "keyWithoutValue\r\n" + "key=value\r\n"; - properties = readProperties(input); - assertValue("", "keyWithoutValue"); - assertValue("value", "key"); - } - - private void assertValue(String expected, String key) { - assertEquals(expected, properties.get(key)); - } - - private Properties readProperties(String input) throws IOException { - Properties properties = new Properties(); - properties.load(new ByteArrayInputStream(input.getBytes())); - return properties; - } - -} diff --git a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java b/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java deleted file mode 100644 index b6d731ba..00000000 --- a/org.eclipse.babel.editor/tests/org/eclipse/nls/ui/tests/RawBundleTest.java +++ /dev/null @@ -1,78 +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.eclipse.nls.ui.tests; - -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; - -import junit.framework.TestCase; - -import org.eclipse.pde.nls.internal.ui.parser.RawBundle; -import org.eclipse.pde.nls.internal.ui.parser.RawBundle.EntryLine; - -public class RawBundleTest extends TestCase { - - private RawBundle rawBundle; - - public void test() throws IOException { - String input = " # a comment line\r\n" + "key1=value1\r\n" - + "key2=a value \\\r\n" + " on two lines\r\n" - + "key3=a value \\\r\n" + " " - + " with an empty line in between\r\n"; - rawBundle = readRawBundle(input); - assertRawData("key1=value1\r\n", "key1"); - assertRawData("key2=a value \\\r\n" + " on two lines\r\n", "key2"); - assertRawData("key3=a value \\\r\n" + " " - + " with an empty line in between\r\n", "key3"); - } - - public void testKeysWithWhitespace() throws IOException { - String input = "" + "key1\t=key with tab\r\n" - + "key\\ 2 =key with escaped space\r\n" - + "key 3 =key with space\r\n"; - rawBundle = readRawBundle(input); - assertRawData("key1\t=key with tab\r\n", "key1"); - assertRawData("key\\ 2 =key with escaped space\r\n", "key 2"); - assertRawData("key 3 =key with space\r\n", "key"); - } - - public void testKeysWithMissingValue() throws IOException { - String input = "keyWithoutValue\r\n" + "key=value\r\n"; - rawBundle = readRawBundle(input); - assertRawData("keyWithoutValue\r\n", "keyWithoutValue"); - assertRawData("key=value\r\n", "key"); - } - - public void testPut() throws IOException { - String input = "" + "key1=value1\r\n" + "key3=value3\r\n"; - rawBundle = readRawBundle(input); - rawBundle.put("key2", "value2"); - rawBundle.put("key4", "value4"); - rawBundle.put("key0", "value0\\\t"); - StringWriter stringWriter = new StringWriter(); - rawBundle.writeTo(stringWriter); - assertEquals("" + "key0=value0\\\\\\t\r\n" + "key1=value1\r\n" - + "key2=value2\r\n" + "key3=value3\r\n" + "key4=value4\r\n", - stringWriter.toString()); - - } - - private void assertRawData(String expected, String key) { - EntryLine entryLine = rawBundle.getEntryLine(key); - assertEquals(expected, entryLine.getRawData()); - } - - private RawBundle readRawBundle(String input) throws IOException { - return RawBundle.createFrom(new StringReader(input)); - } - -} diff --git a/org.eclipse.babel.repository/category.xml b/org.eclipse.babel.repository/category.xml deleted file mode 100644 index 3ff8e424..00000000 --- a/org.eclipse.babel.repository/category.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<site> - <description url="Eclipse Babel Tools"> - TODO ... add a nice description here - </description> - <feature url="features/org.eclipse.babel.tapiji.tools.java.feature_0.0.0.qualifier.jar" id="org.eclipse.babel.tapiji.tools.java.feature" version="0.0.0" patch="true"> - <category name="Babel Tools Project"/> - </feature> - <category-def name="Babel Tools Project" label="Babel Tools Project"> - <description> - Babel Tools Project - </description> - </category-def> -</site> diff --git a/org.eclipse.babel.repository/pom.xml b/org.eclipse.babel.repository/pom.xml deleted file mode 100644 index 685510f5..00000000 --- a/org.eclipse.babel.repository/pom.xml +++ /dev/null @@ -1,115 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Copyright (C) 2012, Stefan Strobl <[email protected]> - - All rights reserved. This program and the accompanying materials - are made available under the terms 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 Strobl - create repository and signing ---> - -<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"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.repository</artifactId> - <packaging>eclipse-repository</packaging> - <name>Babel P2 Repository</name> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> - - <properties> - <signer-input-directory>/home/data/httpd/download-staging.priv/technology/babel</signer-input-directory> - <download-publish-path>/home/data/httpd/download.eclipse.org/technology/babel/tools-updates-nightly</download-publish-path> - <p2repo-zip-path>${project.build.directory}/org.eclipse.babel.repository-${project.version}.zip</p2repo-zip-path> - </properties> - - <profiles> - <profile> - <id>build-server</id> - <build> - <plugins> - <plugin> - <groupId>org.eclipse.dash.maven</groupId> - <artifactId>eclipse-signing-maven-plugin</artifactId> - <executions> - <execution> - <id>pack</id> - <configuration> - <inputFile>${p2repo-zip-path}</inputFile> - </configuration> - <phase>package</phase> - <goals> - <goal>pack</goal> - </goals> - </execution> - <execution> - <id>sign</id> - <configuration> - <inputFile>${p2repo-zip-path}</inputFile> - <signerInputDirectory>${signer-input-directory}</signerInputDirectory> - </configuration> - <phase>package</phase> - <goals> - <goal>sign</goal> - </goals> - </execution> - <execution> - <id>repack</id> - <configuration> - <inputFile>${project.build.directory}/signed/site_assembly.zip</inputFile> - </configuration> - <phase>package</phase> - <goals> - <goal>pack</goal> - </goals> - </execution> - <execution> - <id>fixCheckSums</id> - <phase>package</phase> - <goals> - <goal>fixCheckSums</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <artifactId>maven-antrun-plugin</artifactId> - <executions> - <execution> - <id>deploy</id> - <phase>install</phase> - <goals> - <goal>run</goal> - </goals> - <configuration> - <tasks> - <delete includeemptydirs="false"> - <fileset - dir="${download-publish-path}"> - <include name="**" /> - </fileset> - </delete> - <copy includeemptydirs="false" - todir="${download-publish-path}"> - <fileset dir="target/checksumFix"> - <include name="**" /> - </fileset> - </copy> - </tasks> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - </profile> - </profiles> -</project> diff --git a/org.eclipse.babel.tapiji.tools.core.ui/.classpath b/org.eclipse.babel.tapiji.tools.core.ui/.classpath deleted file mode 100644 index 0b1bcf94..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src/"/> - <classpathentry kind="output" path="target/classes"/> -</classpath> diff --git a/org.eclipse.babel.tapiji.tools.core.ui/.project b/org.eclipse.babel.tapiji.tools.core.ui/.project deleted file mode 100644 index b8195d4e..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/.project +++ /dev/null @@ -1,34 +0,0 @@ -<?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> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> 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 deleted file mode 100644 index 8f5d6954..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/META-INF/MANIFEST.MF +++ /dev/null @@ -1,42 +0,0 @@ -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/OSGI-INF/l10n/bundle.properties b/org.eclipse.babel.tapiji.tools.core.ui/OSGI-INF/l10n/bundle.properties deleted file mode 100644 index 0d081367..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/OSGI-INF/l10n/bundle.properties +++ /dev/null @@ -1,14 +0,0 @@ -#Properties file for org.eclipse.babel.tapiji.tools.core.ui -extension.nature.name = Internationalization Nature -category.i18n.name = Internationalization -view.rb.name = Resource-Bundle -menu.i18n.label = Internationalization -menu.i18n.tooltip = Java Internationalization assistance -filter.description = Filters only resource bundles -filter.name = ResourceBundleFilter -decorator.label = Resource is excluded from Internationalization -page.general.pref.name = TapiJI -page.file.pref.name = File Settings -page.builder.prefname = Builder Settings -extension.string.marker.name = String Literal Audit Marker -extension.bundle.marker.name = Resource-Bundle Audit Marker \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.core.ui/about.html b/org.eclipse.babel.tapiji.tools.core.ui/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.core.ui/build.properties b/org.eclipse.babel.tapiji.tools.core.ui/build.properties deleted file mode 100644 index 85c6bbdb..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/build.properties +++ /dev/null @@ -1,9 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - plugin.xml,\ - icons/,\ - about.html,\ - OSGI-INF/l10n/bundle.properties -src.includes = icons/,\ - about.html diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_small.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_small.png deleted file mode 100644 index da9f603a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_small.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_warning_small.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_warning_small.png deleted file mode 100644 index ec47a9ac..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16_warning_small.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/exclude.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/exclude.png deleted file mode 100644 index d1105295..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/exclude.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/flatLayout.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/flatLayout.gif deleted file mode 100644 index 1ef74cf9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/flatLayout.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/hierarchicalLayout.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/hierarchicalLayout.gif deleted file mode 100644 index 23448617..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/hierarchicalLayout.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/incomplete.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/incomplete.gif deleted file mode 100644 index 6583d366..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/incomplete.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/int.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/int.gif deleted file mode 100644 index 7d24707e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/int.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/key.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/key.gif deleted file mode 100644 index bdb8e971..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/key.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/newpropertiesfile.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/newpropertiesfile.gif deleted file mode 100644 index 11e436b8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/newpropertiesfile.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/propertiesfile.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/propertiesfile.gif deleted file mode 100644 index 9090c04d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/propertiesfile.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/resourcebundle.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/resourcebundle.gif deleted file mode 100644 index fe05bad9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/resourcebundle.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/plugin.xml b/org.eclipse.babel.tapiji.tools.core.ui/plugin.xml deleted file mode 100644 index 2f76681e..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/plugin.xml +++ /dev/null @@ -1,243 +0,0 @@ -<?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="%extension.nature.name" - 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="%category.i18n.name"> - </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="%view.rb.name"> - </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="%menu.i18n.label" - tooltip="%menu.i18n.tooltip"> - </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="%filter.description" - enabled="false" - id="ResourceBundleFilter" - name="%filter.name"> - </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="%decorator.label" - 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="%page.general.pref.name"> - </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="%page.file.pref.name"> - </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="%page.builder.prefname"> - </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="%extension.string.marker.name" - 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="%extension.bundle.marker.name" - 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/pom.xml b/org.eclipse.babel.tapiji.tools.core.ui/pom.xml deleted file mode 100644 index 69de73e9..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.tapiji.tools.core.ui</artifactId> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file 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 deleted file mode 100644 index 1453eab2..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 8248c03e..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java +++ /dev/null @@ -1,833 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Martin Reiterer - initial API and implementation 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 = "org.eclipse.babel.tapiji.tools.core.ui.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) { - IStateLoader stateLoader = getStateLoader(); - if (stateLoader != null) { - stateLoader.loadState(); - state_loaded = true; - excludedResources = stateLoader.getExcludedResources(); - } else { - Logger.logError("State-Loader uninitialized! Unable to restore project state."); - } - } - - // 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 - Logger.logError(e); - } - } - 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) { - IStateLoader stateLoader = getStateLoader(); - if (stateLoader != null) { - stateLoader.loadState(); - } else { - Logger.logError("State-Loader uninitialized! Unable to restore state."); - } - } - - 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) { - Logger.logError(e); - } - 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; - } - - public static IStateLoader getStateLoader() { - if (stateLoader == null) { - - IExtensionPoint extp = Platform.getExtensionRegistry() - .getExtensionPoint( - "org.eclipse.babel.tapiji.tools.core" - + ".stateLoader"); - IConfigurationElement[] elements = extp.getConfigurationElements(); - - if (elements.length != 0) { - try { - stateLoader = (IStateLoader) elements[0] - .createExecutableExtension("class"); - } catch (CoreException e) { - Logger.logError(e); - } - } - } - - return stateLoader; - - } - - public static void saveManagerState() { - IStateLoader stateLoader = getStateLoader(); - if (stateLoader != null) { - 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 deleted file mode 100644 index 20c3942b..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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; - } - - @Override - public void reset() { - // there is nothing todo - } - -} 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 deleted file mode 100644 index 3ef31509..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 0f73345e..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 313140e6..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java +++ /dev/null @@ -1,134 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 59f277be..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 7daa03a7..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java +++ /dev/null @@ -1,472 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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; - - 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 (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) { - if (ra instanceof I18nResourceAuditor) { - ((I18nResourceAuditor)ra).reset(); - } - } - - 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 deleted file mode 100644 index 7e9fbea6..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 11f84bf3..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index d40dbd60..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java +++ /dev/null @@ -1,109 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. All rights reserved. This program and the - * accompanying materials are made available under the terms of the Eclipse - * Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 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 deleted file mode 100644 index 1cf552c7..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 17f050a6..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 30d4f3f9..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java +++ /dev/null @@ -1,481 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Clemente Lodi-Fe, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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(this.getErrorMessage() == null); - 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 deleted file mode 100644 index c868bc06..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index ae46d9b7..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java +++ /dev/null @@ -1,146 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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/KeyRefactoringDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringDialog.java deleted file mode 100644 index 58110bc8..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringDialog.java +++ /dev/null @@ -1,311 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.core.ui.dialogs; - -import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager; -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.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.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; - -/** - * The dialog between the user and the system. System wants to know what the new - * name of the selected key is. - * - * @author Alexej Strelzow - */ -public class KeyRefactoringDialog extends TitleAreaDialog { - - /*** Dialog Model ***/ - private DialogConfiguration config; - private String selectedKey = ""; - - public static final String ALL_LOCALES = "All available"; - - /** GUI */ - private Button okButton; - private Button cancelButton; - - private Label projectLabel; - private Label resourceBundleLabel; - private Label oldKeyLabel; - private Label newKeyLabel; - private Label languageLabel; - - private Text oldKeyText; - private Text newKeyText; - private Text projectText; - private Text resourceBundleText; - private Text languageText; - - /** - * Meta data for the dialog. - * - * @author Alexej Strelzow - */ - public class DialogConfiguration { - - String projectName; - String preselectedKey; - String preselectedBundle; - - String newKey; - String selectedLocale; - - 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 getPreselectedBundle() { - return preselectedBundle; - } - - public void setPreselectedBundle(String preselectedBundle) { - this.preselectedBundle = preselectedBundle; - } - - public String getNewKey() { - return newKey; - } - - public void setNewKey(String newKey) { - this.newKey = newKey; - } - - public String getSelectedLocale() { - return selectedLocale; - } - - public void setSelectedLocale(String selectedLocale) { - this.selectedLocale = selectedLocale; - } - } - - /** - * Constructor. - * - * @param parentShell - * The parent's shell - */ - public KeyRefactoringDialog(Shell parentShell) { - super(parentShell); - } - - /** - * {@inheritDoc} - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - - return super.createDialogArea(parent); - } - - /** - * Initializes the layout - * - * @param parent - * The parent - */ - private void initLayout(Composite parent) { - final GridLayout layout = new GridLayout(1, true); - parent.setLayout(layout); - - GridLayout gl = new GridLayout(2, true); - GridData gd = new GridData(SWT.CENTER, SWT.CENTER, true, true); - - Composite master = new Composite(parent, SWT.NONE); - master.setLayout(gl); - master.setLayoutData(gd); - - projectLabel = new Label(master, SWT.NONE); - projectLabel.setText("Project:"); - - projectText = new Text(master, SWT.BORDER); - projectText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - projectText.setText(config.getProjectName()); - projectText.setEnabled(false); - - resourceBundleLabel = new Label(master, SWT.NONE); - resourceBundleLabel.setText("Resource-Bundle:"); - - resourceBundleText = new Text(master, SWT.BORDER); - resourceBundleText.setLayoutData(new GridData(GridData.FILL, - GridData.FILL, true, true, 1, 1)); - resourceBundleText.setText(config.getPreselectedBundle()); - resourceBundleText.setEnabled(false); - - languageLabel = new Label(master, SWT.NONE); - languageLabel.setText("Language (Country):"); - - languageText = new Text(master, SWT.BORDER); - languageText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - languageText.setText(ALL_LOCALES); - languageText.setEnabled(false); - - oldKeyLabel = new Label(master, SWT.NONE); - oldKeyLabel.setText("Old key name:"); - - oldKeyText = new Text(master, SWT.BORDER); - oldKeyText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - oldKeyText.setText(config.getPreselectedKey()); - oldKeyText.setEnabled(false); - - newKeyLabel = new Label(master, SWT.NONE); - newKeyLabel.setText("New key name:"); - - newKeyText = new Text(master, SWT.BORDER); - newKeyText.setText(config.getPreselectedKey()); - newKeyText.setSelection(0, newKeyText.getText().length()); - newKeyText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - - newKeyText.setFocus(); - - newKeyText.addModifyListener(new ModifyListener() { - - @Override - public void modifyText(ModifyEvent e) { - selectedKey = newKeyText.getText(); - validate(); - } - }); - } - - /** - * @param config - * Sets the config - */ - public void setDialogConfiguration(DialogConfiguration config) { - this.config = config; - } - - /** - * {@inheritDoc} - */ - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Key refactoring"); - } - - /** - * {@inheritDoc} - */ - @Override - public void create() { - // TODO Auto-generated method stub - super.create(); - this.setTitle("Key refactoring"); - this.setMessage("Please, specify the name of the new key. \r\n" - + "The new value will automatically replace the old ones."); - } - - /** - * @return The config - */ - public DialogConfiguration getConfig() { - return this.config; - } - - /** - * Validates all inputs of the CreateResourceBundleEntryDialog - */ - protected void validate() { - // Check Resource-Bundle ids - boolean keyValid = false; - boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey); - - String resourceBundle = config.getPreselectedBundle(); - - ResourceBundleManager manager = ResourceBundleManager.getManager(config - .getProjectName()); - - if (!manager.isResourceExisting(resourceBundle, selectedKey)) { - keyValid = 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 (okButton != null) - okButton.setEnabled(true); - } - - setErrorMessage(errorMessage); - if (okButton != null && errorMessage != null) { - okButton.setEnabled(false); - } else { - this.config.setNewKey(selectedKey); - this.config.setSelectedLocale(ALL_LOCALES); - } - } - - /** - * {@inheritDoc} - */ - @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/KeyRefactoringSummaryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringSummaryDialog.java deleted file mode 100644 index 7d94563d..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/KeyRefactoringSummaryDialog.java +++ /dev/null @@ -1,159 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.core.ui.dialogs; - -import java.util.List; - -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.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; - -/** - * Summarizes the changes due to the refactoring operation. - * - * @author Alexej Strelzow - */ -public class KeyRefactoringSummaryDialog extends KeyRefactoringDialog { - - /** Dialog Model */ - private List<String> changeSet; - - /** GUI */ - private Button okButton; - - private Label changesLabel; - private Text changesText; - - /** - * Constructor. - * - * @param parentShell - * The parent's shell - */ - public KeyRefactoringSummaryDialog(Shell parentShell) { - super(parentShell); - } - - /** - * {@inheritDoc} - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite dialogArea = new Composite(parent, SWT.NONE); // (Composite) - // super.createDialogArea(parent); - final GridLayout layout = new GridLayout(1, true); - dialogArea.setLayout(layout); - dialogArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, - 1, 1)); - initLayout(dialogArea); - - return dialogArea; - } - - /** - * Initializes the layout - * - * @param parent - * The parent - */ - private void initLayout(Composite parent) { - changesLabel = new Label(parent, SWT.NONE); - changesLabel.setText("Changes:"); - - changesText = new Text(parent, SWT.BORDER | SWT.MULTI); - changesText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, - 1, 1)); - changesText.setEditable(false); - changesText.setText(getChangeSetText()); - } - - /** - * @return The text to display (changes) - */ - private String getChangeSetText() { - - StringBuilder sb = new StringBuilder(); - - for (String s : changeSet) { - sb.append(s + "\r\n"); - } - - return sb.toString(); - } - - /** - * @param changeSet - * The change set of the refactoring operation, which contains - * Resource: line number - */ - public void setChangeSet(List<String> changeSet) { - this.changeSet = changeSet; - } - - /** - * {@inheritDoc} - */ - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Key refactoring summary"); - } - - /** - * {@inheritDoc} - */ - @Override - protected void okPressed() { - setReturnCode(OK); - close(); - } - - /** - * {@inheritDoc} - */ - @Override - public void create() { - super.create(); - DialogConfiguration config = getConfig(); - this.setTitle("Summary of the key refactoring: " - + config.getPreselectedKey() + " -> " + config.getNewKey()); - this.setMessage("The resource bundle " + config.getPreselectedBundle() - + " and " + changeSet.size() + " files of the project " - + config.getProjectName() + " have been successfully modified."); - } - - /** - * {@inheritDoc} - */ - @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(); - } - }); - - okButton.setEnabled(true); - } - -} 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 deleted file mode 100644 index baca62af..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java +++ /dev/null @@ -1,462 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 1f260a34..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 3879c118..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java +++ /dev/null @@ -1,474 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 1e27d912..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index afa72c92..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index eb103821..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nRBAuditor.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index c89f7ac8..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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(); - - /** - * Resets the auditor and clears collected Internationalization errors - */ - public abstract void reset(); - - /** - * 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 deleted file mode 100644 index c9b8729c..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 22a9f008..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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/memento/ResourceBundleManagerStateLoader.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java deleted file mode 100644 index b0482588..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.FileNotFoundException; -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 (FileNotFoundException e) { - Logger.logInfo("Unable to restore internationalization state. Reason: internationalization.xml not found!"); - } catch (Exception e) { - Logger.logError(e); - } - } - - 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 deleted file mode 100644 index 34149f07..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java +++ /dev/null @@ -1,433 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index c972b124..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 42a56c57..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * 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 deleted file mode 100644 index 4f25e422..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java +++ /dev/null @@ -1,227 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index ab346aaa..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 520e4920..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 47b8cc58..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index ebef566c..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java +++ /dev/null @@ -1,201 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 2de8a6f0..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * 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 deleted file mode 100644 index e3751ca9..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index ae220db5..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/EditorUtils.java +++ /dev/null @@ -1,190 +0,0 @@ -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 deleted file mode 100644 index e7b66d4b..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 62e8ddfd..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java +++ /dev/null @@ -1,63 +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 - * Martin Reiterer - extracting image handling from UIUtils - ******************************************************************************/ -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; - -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 deleted file mode 100644 index c4809c98..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java +++ /dev/null @@ -1,137 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 6544b7a8..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 9c4d0089..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java +++ /dev/null @@ -1,249 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 2aa36fb8..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 07e865e9..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java +++ /dev/null @@ -1,541 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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: - // 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 deleted file mode 100644 index 0d82c933..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java +++ /dev/null @@ -1,217 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 70760968..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview; - -import org.eclipse.babel.editor.util.UIUtils; -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 refactorItem; - 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 refactoring the currently selected entry - refactorItem = new MenuItem(menu, SWT.NONE, index + 2); - refactorItem.setText("Refactor ..."); - refactorItem.setImage(UIUtils.getImageDescriptor( - UIUtils.IMAGE_REFACTORING).createImage()); - refactorItem.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - parentView.refactorSelectedItem(); - } - - @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); - refactorItem.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 deleted file mode 100644 index 0ede994a..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 7416afb1..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java +++ /dev/null @@ -1,180 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index b5aa199d..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 8329c589..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index be8e81f7..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * 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 deleted file mode 100644 index 17381c24..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java +++ /dev/null @@ -1,18 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 57ee79c2..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java +++ /dev/null @@ -1,834 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Clemente Lodi-Fe, Matthias Lettmayer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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); - - // highlight the search results - labelProvider.updateTreeViewer(treeViewer); - } - - public SortInfo getSortInfo() { - if (this.sorter != null) - return this.sorter.getSortInfo(); - else - return null; - } - - public void setSortInfo(SortInfo sortInfo) { - sortInfo.setVisibleLocales(visibleLocales); - if (sorter != null) { - sorter.setSortInfo(sortInfo); - treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree - : TreeType.Flat; - treeViewer.refresh(); - } - } - - public String getSearchString() { - return matcher.getPattern(); - } - - public boolean isEditable() { - return editable; - } - - public void setEditable(boolean editable) { - this.editable = editable; - } - - public List<Locale> getVisibleLocales() { - return visibleLocales; - } - - public String getResourceBundle() { - return resourceBundle; - } - - public void editSelectedItem() { - String key = ""; - ISelection selection = treeViewer.getSelection(); - if (selection instanceof IStructuredSelection) { - IStructuredSelection structSel = (IStructuredSelection) selection; - if (structSel.getFirstElement() instanceof IKeyTreeNode) { - IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel - .getFirstElement(); - key = keyTreeNode.getMessageKey(); - } - } - - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - EditorUtils.openEditor(site.getPage(), - manager.getRandomFile(resourceBundle), - EditorUtils.RESOURCE_BUNDLE_EDITOR, key); - } - - public void refactorSelectedItem() { - String key = ""; - String bundleId = ""; - 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(); - bundleId = keyTreeNode.getMessagesBundleGroup() - .getResourceBundleId(); - - RBManager.getRefactorService().openRefactorDialog(projectName, - bundleId, key, null); - } - } - } - - 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 deleted file mode 100644 index bd1466e9..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java +++ /dev/null @@ -1,270 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 955b2a05..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index c2c77473..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 654d4d23..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index e3288015..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter; - -import java.util.Locale; - -import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer; -import org.eclipse.babel.editor.api.AnalyzerFactory; -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 IProximityAnalyzer 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 deleted file mode 100644 index 8affc33d..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java +++ /dev/null @@ -1,496 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 4d8de8ab..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index cbc3eaed..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider; - -import org.eclipse.jface.viewers.IColorProvider; -import org.eclipse.jface.viewers.IFontProvider; -import org.eclipse.jface.viewers.StyledCellLabelProvider; -import org.eclipse.jface.viewers.ViewerCell; -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 Alexej Strelzow - */ -public abstract class KeyTreeLabelProvider extends StyledCellLabelProvider - implements IFontProvider, IColorProvider { - - public KeyTreeLabelProvider() { - setOwnerDrawEnabled(true); - } - - /** - * @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; - } - - public abstract String getColumnText(Object element, int columnIndex); - - public abstract Image getColumnImage(Object element, int columnIndex); - - /** - * {@inheritDoc} - */ - @Override - public void update(ViewerCell cell) { - cell.setText(getColumnText(cell.getElement(), cell.getColumnIndex())); - cell.setImage(getColumnImage(cell.getElement(), cell.getColumnIndex())); - super.update(cell); - } - -} 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 deleted file mode 100644 index ab0e33cb..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java +++ /dev/null @@ -1,230 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * 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 deleted file mode 100644 index 54a8dac5..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * 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.TreeViewer; -import org.eclipse.jface.viewers.ViewerCell; -import org.eclipse.jface.viewers.ViewerRow; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.TreeItem; - -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); - - public ResKeyTreeLabelProvider(List<Locale> locales) { - this.locales = locales; - } - - /** - * {@inheritDoc} - */ - @Override - public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == 0) { - IKeyTreeNode kti = (IKeyTreeNode) element; - IMessage[] be = kti.getMessagesBundleGroup().getMessages( - kti.getMessageKey()); - boolean incomplete = false; - - if (be.length != kti.getMessagesBundleGroup() - .getMessagesBundleCount()) - incomplete = true; - else { - for (IMessage b : be) { - if (b.getValue() == null - || b.getValue().trim().length() == 0) { - incomplete = true; - break; - } - } - } - - if (incomplete) { - return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE); - } else { - return ImageUtils.getImage(ImageUtils.ICON_RESOURCE); - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getColumnText(Object element, int columnIndex) { - if (columnIndex == 0) { - return ((IKeyTreeNode) element).getName(); - } - - 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); - } - - public void updateTreeViewer(TreeViewer treeViewer) { - - for (TreeItem item : treeViewer.getTree().getItems()) { - Rectangle bounds = item.getBounds(); - ViewerCell cell = treeViewer.getCell(new Point(bounds.x, bounds.y)); - ViewerRow viewerRow = cell.getViewerRow(); - - for (int i = 0; i < viewerRow.getColumnCount(); i++) { - updateCell(viewerRow.getCell(i)); - } - } - } - - private void updateCell(ViewerCell cell) { - Object element = cell.getElement(); - int columnIndex = cell.getColumnIndex(); - - if (isSearchEnabled(element)) { - if (isMatchingToPattern(element, columnIndex)) { - List<StyleRange> styleRanges = new ArrayList<StyleRange>(); - FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element) - .getInfo(); - - if (columnIndex > 0) { - for (Region reg : filterInfo.getFoundInLocaleRanges(locales - .get(columnIndex - 1))) { - styleRanges.add(new StyleRange(reg.getOffset(), reg - .getLength(), black, info_color, SWT.BOLD)); - } - } else { - // check if the pattern has been found within the key - // section - if (filterInfo.isFoundInKey()) { - for (Region reg : filterInfo.getKeyOccurrences()) { - StyleRange sr = new StyleRange(reg.getOffset(), - reg.getLength(), black, info_color, - SWT.BOLD); - styleRanges.add(sr); - } - } - } - cell.setStyleRanges(styleRanges - .toArray(new StyleRange[styleRanges.size()])); - } else { - cell.setForeground(gray); - } - } else if (columnIndex == 0) { - super.update(cell); - } - } - -} diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java deleted file mode 100644 index 55938982..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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.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; - } - - /** - * {@inheritDoc} - */ - @Override - public Image getColumnImage(Object element, int columnIndex) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getColumnText(Object element, int columnIndex) { - try { - IKeyTreeNode item = (IKeyTreeNode) element; - IMessage entry = locale.getMessage(item.getMessageKey()); - if (entry != null) { - String value = entry.getValue(); - if (value.length() > 40) - value = value.substring(0, 39) + "..."; - } - } catch (Exception e) { - } - return ""; - } - - /** - * {@inheritDoc} - */ - @Override - public Color getBackground(Object element, int columnIndex) { - return null;// return new Color(Display.getDefault(), 255, 0, 0); - } - - /** - * {@inheritDoc} - */ - @Override - public Color getForeground(Object element, int columnIndex) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Font getFont(Object element, int columnIndex) { - return null; // UIUtils.createFont(SWT.BOLD); - } - -} diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java deleted file mode 100644 index e7d1c194..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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.eclipse.babel.tapiji.tools.core/.classpath b/org.eclipse.babel.tapiji.tools.core/.classpath deleted file mode 100644 index c89ae12c..00000000 --- a/org.eclipse.babel.tapiji.tools.core/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="src" path="src"/> - <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="output" path="target/classes"/> -</classpath> diff --git a/org.eclipse.babel.tapiji.tools.core/.project b/org.eclipse.babel.tapiji.tools.core/.project deleted file mode 100644 index f1bd151e..00000000 --- a/org.eclipse.babel.tapiji.tools.core/.project +++ /dev/null @@ -1,34 +0,0 @@ -<?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> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF deleted file mode 100644 index dcd7fe89..00000000 --- a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF +++ /dev/null @@ -1,28 +0,0 @@ -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.jface;bundle-version="3.6.2" -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -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 -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.eclipse.babel.tapiji.tools.core/about.html b/org.eclipse.babel.tapiji.tools.core/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.tapiji.tools.core/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.core/build.properties b/org.eclipse.babel.tapiji.tools.core/build.properties deleted file mode 100644 index 45aad752..00000000 --- a/org.eclipse.babel.tapiji.tools.core/build.properties +++ /dev/null @@ -1,10 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = plugin.xml,\ - META-INF/,\ - .,\ - schema/,\ - about.html -src.includes = schema/,\ - about.html - diff --git a/org.eclipse.babel.tapiji.tools.core/plugin.xml b/org.eclipse.babel.tapiji.tools.core/plugin.xml deleted file mode 100644 index d940b2bf..00000000 --- a/org.eclipse.babel.tapiji.tools.core/plugin.xml +++ /dev/null @@ -1,6 +0,0 @@ -<?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/pom.xml b/org.eclipse.babel.tapiji.tools.core/pom.xml deleted file mode 100644 index 98b42610..00000000 --- a/org.eclipse.babel.tapiji.tools.core/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.tapiji.tools.core</artifactId> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file 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 deleted file mode 100644 index d01b5bcc..00000000 --- a/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.builderExtension.exsd +++ /dev/null @@ -1,223 +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. - -&lt;pre&gt; -&lt;extension point=&quot;org.eclipselabs.tapiji.tools.core.builderExtension&quot;&gt; - &lt;i18nResourceAuditor - class=&quot;ui.JavaResourceAuditor&quot;&gt; - &lt;/i18nResourceAuditor&gt; -&lt;/extension&gt; -&lt;/pre&gt; - </documentation> - </annotation> - - <annotation> - <appinfo> - <meta.section type="apiinfo"/> - </appinfo> - <documentation> - Extending plug-ins need to extend the abstract class &lt;strong&gt;org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor&lt;/strong&gt;. - -&lt;pre&gt; -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&apos;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&apos;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&lt;ILocation&gt; 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&lt;ILocation&gt; 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&lt;ILocation&gt; 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&lt;IMarkerResolution&gt; 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; - } -} - -&lt;/pre&gt; - </documentation> - </annotation> - - <annotation> - <appinfo> - <meta.section type="implementation"/> - </appinfo> - <documentation> - &lt;ul&gt; - &lt;li&gt;Java Internationalization help: &lt;span style=&quot;font-family:monospace&quot;&gt;org.eclipselabs.tapiji.tools.java&lt;/span&gt;&lt;/li&gt; - &lt;li&gt;JSF Internaization help: &lt;span style=&quot;font-family:monospace&quot;&gt;org.eclipselabs.tapiji.tools.jsf&lt;/span&gt; - &lt;/li&gt; -&lt;/ul&gt; - </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 deleted file mode 100644 index a40e3228..00000000 --- a/org.eclipse.babel.tapiji.tools.core/schema/org.eclipse.babel.tapiji.tools.core.stateLoader.exsd +++ /dev/null @@ -1,119 +0,0 @@ -<?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 deleted file mode 100644 index 8d7bdf97..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java +++ /dev/null @@ -1,159 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.core; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import org.eclipse.babel.core.message.manager.RBManager; -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; - - // detect resource bundles - RBManager.getAllMessagesBundleGroupNames(); - } - - /* - * (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 deleted file mode 100644 index dcbabae0..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. All rights reserved. This program and the - * accompanying materials are made available under the terms of the Eclipse - * Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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.INFO, message, null); - } - - public static void logWarning(String message) { - log(IStatus.WARNING, IStatus.WARNING, message, null); - } - - public static void logError(String message) { - log(IStatus.ERROR, IStatus.ERROR, message, null); - } - - public static void logError(Throwable exception) { - logError("Unexpected Exception", exception); - } - - public static void logError(String message, Throwable exception) { - log(IStatus.ERROR, IStatus.ERROR, 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 deleted file mode 100644 index 1faa7c3b..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 36e21bf6..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 26727ee5..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index cb80a2f5..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 31f913ba..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index fc556c3f..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 5ac24c83..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 482de433..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java +++ /dev/null @@ -1,15 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 767a7614..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 73166a21..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 1196f111..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 66521371..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java +++ /dev/null @@ -1,15 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 1230be27..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 3c7b9209..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 986bded2..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileReader; - -import org.eclipse.babel.tapiji.tools.core.Activator; -import org.eclipse.babel.tapiji.tools.core.Logger; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.OperationCanceledException; - -public class FileUtils { - - public static String readFile(IResource resource) { - return readFileAsString(resource.getRawLocation().toFile()); - } - - protected static String readFileAsString(File filePath) { - String content = ""; - - if (!filePath.exists()) - return content; - try { - BufferedReader fileReader = new BufferedReader(new FileReader( - filePath)); - String line = ""; - - while ((line = fileReader.readLine()) != null) { - content += line + "\n"; - } - - // close filereader - fileReader.close(); - } catch (Exception e) { - // TODO log error output - Logger.logError(e); - } - - return content; - } - - public static File getRBManagerStateFile() { - return Activator.getDefault().getStateLocation() - .append("internationalization.xml").toFile(); - } - - /** - * Don't use that -> causes {@link ResourceException} -> because File out of - * sync - * - * @param file - * @param editorContent - * @throws CoreException - * @throws OperationCanceledException - */ - public synchronized void saveTextFile(IFile file, String editorContent) - throws CoreException, OperationCanceledException { - try { - file.setContents( - new ByteArrayInputStream(editorContent.getBytes()), false, - true, null); - } catch (Exception e) { - e.printStackTrace(); - } - } - -} diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java deleted file mode 100644 index 99c49241..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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 deleted file mode 100644 index 56465ce6..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.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/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java deleted file mode 100644 index 915f70a0..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.eclipse.babel.tapiji.tools.feature/.project b/org.eclipse.babel.tapiji.tools.feature/.project deleted file mode 100644 index c3a11a11..00000000 --- a/org.eclipse.babel.tapiji.tools.feature/.project +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.java.feature</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.wst.common.project.facet.core.builder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.FeatureBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.FeatureNature</nature> - <nature>org.eclipse.wst.common.project.facet.core.nature</nature> - </natures> -</projectDescription> - diff --git a/org.eclipse.babel.tapiji.tools.feature/about.html b/org.eclipse.babel.tapiji.tools.feature/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.tapiji.tools.feature/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.feature/build.properties b/org.eclipse.babel.tapiji.tools.feature/build.properties deleted file mode 100644 index 1fe28114..00000000 --- a/org.eclipse.babel.tapiji.tools.feature/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -bin.includes = feature.xml,\ - epl-v10.html -src.includes = epl-v10.html,\ - feature.xml diff --git a/org.eclipse.babel.tapiji.tools.feature/epl-v10.html b/org.eclipse.babel.tapiji.tools.feature/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipse.babel.tapiji.tools.feature/epl-v10.html +++ /dev/null @@ -1,261 +0,0 @@ -<?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 (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR -DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS -AGREEMENT.</p> - -<p><b>1. DEFINITIONS</b></p> - -<p>&quot;Contribution&quot; means:</p> - -<p class="list">a) in the case of the initial Contributor, the initial -code and documentation distributed under this Agreement, and</p> -<p class="list">b) in the case of each subsequent Contributor:</p> -<p class="list">i) changes to the Program, and</p> -<p class="list">ii) additions to the Program;</p> -<p class="list">where such changes and/or additions to the Program -originate from and are distributed by that particular Contributor. A -Contribution 'originates' from a Contributor if it was added to the -Program by such Contributor itself or anyone acting on such -Contributor's behalf. Contributions do not include additions to the -Program which: (i) are separate modules of software distributed in -conjunction with the Program under their own license agreement, and (ii) -are not derivative works of the Program.</p> - -<p>&quot;Contributor&quot; means any person or entity that distributes -the Program.</p> - -<p>&quot;Licensed Patents&quot; mean patent claims licensable by a -Contributor which are necessarily infringed by the use or sale of its -Contribution alone or when combined with the Program.</p> - -<p>&quot;Program&quot; means the Contributions distributed in accordance -with this Agreement.</p> - -<p>&quot;Recipient&quot; means anyone who receives the Program under -this Agreement, including all Contributors.</p> - -<p><b>2. GRANT OF RIGHTS</b></p> - -<p class="list">a) Subject to the terms of this Agreement, each -Contributor hereby grants Recipient a non-exclusive, worldwide, -royalty-free copyright license to reproduce, prepare derivative works -of, publicly display, publicly perform, distribute and sublicense the -Contribution of such Contributor, if any, and such derivative works, in -source code and object code form.</p> - -<p class="list">b) Subject to the terms of this Agreement, each -Contributor hereby grants Recipient a non-exclusive, worldwide, -royalty-free patent license under Licensed Patents to make, use, sell, -offer to sell, import and otherwise transfer the Contribution of such -Contributor, if any, in source code and object code form. This patent -license shall apply to the combination of the Contribution and the -Program if, at the time the Contribution is added by the Contributor, -such addition of the Contribution causes such combination to be covered -by the Licensed Patents. The patent license shall not apply to any other -combinations which include the Contribution. No hardware per se is -licensed hereunder.</p> - -<p class="list">c) Recipient understands that although each Contributor -grants the licenses to its Contributions set forth herein, no assurances -are provided by any Contributor that the Program does not infringe the -patent or other intellectual property rights of any other entity. Each -Contributor disclaims any liability to Recipient for claims brought by -any other entity based on infringement of intellectual property rights -or otherwise. As a condition to exercising the rights and licenses -granted hereunder, each Recipient hereby assumes sole responsibility to -secure any other intellectual property rights needed, if any. For -example, if a third party patent license is required to allow Recipient -to distribute the Program, it is Recipient's responsibility to acquire -that license before distributing the Program.</p> - -<p class="list">d) Each Contributor represents that to its knowledge it -has sufficient copyright rights in its Contribution, if any, to grant -the copyright license set forth in this Agreement.</p> - -<p><b>3. REQUIREMENTS</b></p> - -<p>A Contributor may choose to distribute the Program in object code -form under its own license agreement, provided that:</p> - -<p class="list">a) it complies with the terms and conditions of this -Agreement; and</p> - -<p class="list">b) its license agreement:</p> - -<p class="list">i) effectively disclaims on behalf of all Contributors -all warranties and conditions, express and implied, including warranties -or conditions of title and non-infringement, and implied warranties or -conditions of merchantability and fitness for a particular purpose;</p> - -<p class="list">ii) effectively excludes on behalf of all Contributors -all liability for damages, including direct, indirect, special, -incidental and consequential damages, such as lost profits;</p> - -<p class="list">iii) states that any provisions which differ from this -Agreement are offered by that Contributor alone and not by any other -party; and</p> - -<p class="list">iv) states that source code for the Program is available -from such Contributor, and informs licensees how to obtain it in a -reasonable manner on or through a medium customarily used for software -exchange.</p> - -<p>When the Program is made available in source code form:</p> - -<p class="list">a) it must be made available under this Agreement; and</p> - -<p class="list">b) a copy of this Agreement must be included with each -copy of the Program.</p> - -<p>Contributors may not remove or alter any copyright notices contained -within the Program.</p> - -<p>Each Contributor must identify itself as the originator of its -Contribution, if any, in a manner that reasonably allows subsequent -Recipients to identify the originator of the Contribution.</p> - -<p><b>4. COMMERCIAL DISTRIBUTION</b></p> - -<p>Commercial distributors of software may accept certain -responsibilities with respect to end users, business partners and the -like. While this license is intended to facilitate the commercial use of -the Program, the Contributor who includes the Program in a commercial -product offering should do so in a manner which does not create -potential liability for other Contributors. Therefore, if a Contributor -includes the Program in a commercial product offering, such Contributor -(&quot;Commercial Contributor&quot;) hereby agrees to defend and -indemnify every other Contributor (&quot;Indemnified Contributor&quot;) -against any losses, damages and costs (collectively &quot;Losses&quot;) -arising from claims, lawsuits and other legal actions brought by a third -party against the Indemnified Contributor to the extent caused by the -acts or omissions of such Commercial Contributor in connection with its -distribution of the Program in a commercial product offering. The -obligations in this section do not apply to any claims or Losses -relating to any actual or alleged intellectual property infringement. In -order to qualify, an Indemnified Contributor must: a) promptly notify -the Commercial Contributor in writing of such claim, and b) allow the -Commercial Contributor to control, and cooperate with the Commercial -Contributor in, the defense and any related settlement negotiations. The -Indemnified Contributor may participate in any such claim at its own -expense.</p> - -<p>For example, a Contributor might include the Program in a commercial -product offering, Product X. That Contributor is then a Commercial -Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance -claims and warranties are such Commercial Contributor's responsibility -alone. Under this section, the Commercial Contributor would have to -defend claims against the other Contributors related to those -performance claims and warranties, and if a court requires any other -Contributor to pay any damages as a result, the Commercial Contributor -must pay those damages.</p> - -<p><b>5. NO WARRANTY</b></p> - -<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS -PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS -OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, -ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY -OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely -responsible for determining the appropriateness of using and -distributing the Program and assumes all risks associated with its -exercise of rights under this Agreement , including but not limited to -the risks and costs of program errors, compliance with applicable laws, -damage to or loss of data, programs or equipment, and unavailability or -interruption of operations.</p> - -<p><b>6. DISCLAIMER OF LIABILITY</b></p> - -<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT -NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING -WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR -DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED -HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> - -<p><b>7. GENERAL</b></p> - -<p>If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement, and without further action -by the parties hereto, such provision shall be reformed to the minimum -extent necessary to make such provision valid and enforceable.</p> - -<p>If Recipient institutes patent litigation against any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the -Program itself (excluding combinations of the Program with other -software or hardware) infringes such Recipient's patent(s), then such -Recipient's rights granted under Section 2(b) shall terminate as of the -date such litigation is filed.</p> - -<p>All Recipient's rights under this Agreement shall terminate if it -fails to comply with any of the material terms or conditions of this -Agreement and does not cure such failure in a reasonable period of time -after becoming aware of such noncompliance. If all Recipient's rights -under this Agreement terminate, Recipient agrees to cease use and -distribution of the Program as soon as reasonably practicable. However, -Recipient's obligations under this Agreement and any licenses granted by -Recipient relating to the Program shall continue and survive.</p> - -<p>Everyone is permitted to copy and distribute copies of this -Agreement, but in order to avoid inconsistency the Agreement is -copyrighted and may only be modified in the following manner. The -Agreement Steward reserves the right to publish new versions (including -revisions) of this Agreement from time to time. No one other than the -Agreement Steward has the right to modify this Agreement. The Eclipse -Foundation is the initial Agreement Steward. The Eclipse Foundation may -assign the responsibility to serve as the Agreement Steward to a -suitable separate entity. Each new version of the Agreement will be -given a distinguishing version number. The Program (including -Contributions) may always be distributed subject to the version of the -Agreement under which it was received. In addition, after a new version -of the Agreement is published, Contributor may elect to distribute the -Program (including its Contributions) under the new version. Except as -expressly stated in Sections 2(a) and 2(b) above, Recipient receives no -rights or licenses to the intellectual property of any Contributor under -this Agreement, whether expressly, by implication, estoppel or -otherwise. All rights in the Program not expressly granted under this -Agreement are reserved.</p> - -<p>This Agreement is governed by the laws of the State of New York and -the intellectual property laws of the United States of America. No party -to this Agreement will bring a legal action under this Agreement more -than one year after the cause of action arose. Each party waives its -rights to a jury trial in any resulting litigation.</p> - -</body> - -</html> diff --git a/org.eclipse.babel.tapiji.tools.feature/feature.xml b/org.eclipse.babel.tapiji.tools.feature/feature.xml deleted file mode 100644 index e8346026..00000000 --- a/org.eclipse.babel.tapiji.tools.feature/feature.xml +++ /dev/null @@ -1,173 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<feature - id="org.eclipselabs.tapiji.tools.feature" - label="Internationalization Feature" - version="0.0.2.qualifier" - provider-name="Vienna University of Technology" - plugin="org.eclipselabs.tapiji.tools.feature" - os="linux,macosx,win32"> - - <description url="http://code.google.com/a/eclipselabs.org/p/tapiji/"> - TapiJI represents a set of smart tools that integrate into the -Eclipse IDE for Java developers with the goal to reduce effort -of Internationalization. This is accomplished by creating a productive -environment for building multilingual applications. In practice, -Internationalization based on the basic Java API is a tedious -task and introduces additional complexity into development. - </description> - - <copyright url="http://code.google.com/a/eclipselabs.org/p/tapiji/"> - (c) Copyright Stefan Strobl and Martin Reiterer 2011. All rights reserved. - </copyright> - - <license url="http://www.eclipse.org/legal/epl-v10.html"> - Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT&apos;S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -&quot;Contribution&quot; 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 &apos;originates&apos; from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor&apos;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. - -&quot;Contributor&quot; means any person or entity that distributes the Program. - -&quot;Licensed Patents&quot; mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -&quot;Program&quot; means the Contributions distributed in accordance with this Agreement. - -&quot;Recipient&quot; 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&apos;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 (&quot;Commercial Contributor&quot;) hereby agrees to defend and indemnify every other Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. - -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&apos;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 &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. - -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&apos;s patent(s), then such Recipient&apos;s rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient&apos;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&apos;s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient&apos;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. - </license> - - <requires> - <import plugin="org.eclipse.ui"/> - <import plugin="org.eclipse.core.runtime"/> - <import plugin="org.eclipse.jdt.ui" version="3.5.2" match="greaterOrEqual"/> - <import plugin="org.eclipse.ui.ide"/> - <import plugin="org.eclipse.jdt.core" version="3.5.2" match="greaterOrEqual"/> - <import plugin="org.eclipse.core.resources"/> - <import plugin="org.eclipse.jface.text" version="3.5.2" match="greaterOrEqual"/> - <import plugin="org.eclipse.core.filebuffers"/> - <import plugin="org.eclipse.core.resources" version="3.6.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.jdt.core" version="3.6.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.core.runtime" version="3.6.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.jdt.ui" version="3.6.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.jface"/> - <import plugin="org.eclipse.swt"/> - <import plugin="org.eclipse.text"/> - <import plugin="org.eclipse.ui.workbench"/> - <import plugin="org.eclipse.ui.ide" version="3.6.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.ui.navigator" version="3.5.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.core.runtime" version="3.7.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.ui" version="3.7.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.ui.editors" version="3.7.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.ui.ide.application" version="1.0.300" match="greaterOrEqual"/> - <import plugin="org.eclipse.ui.views" version="3.6.0" match="greaterOrEqual"/> - </requires> - - <plugin - id="org.eclipse.babel.tapiji.tools.core" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.tapiji.tools.java" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.tapiji.translator.rbe" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.tapiji.tools.rbmanager" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="com.essiembre.eclipse.i18n.resourcebundle" - download-size="0" - install-size="0" - version="0.7.8.qualifier"/> - -</feature> diff --git a/org.eclipse.babel.tapiji.tools.java.feature/.project b/org.eclipse.babel.tapiji.tools.java.feature/.project deleted file mode 100644 index 79c04ebb..00000000 --- a/org.eclipse.babel.tapiji.tools.java.feature/.project +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.java.feature</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.wst.common.project.facet.core.builder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.FeatureBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.FeatureNature</nature> - <nature>org.eclipse.wst.common.project.facet.core.nature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.java.feature/about.html b/org.eclipse.babel.tapiji.tools.java.feature/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.tapiji.tools.java.feature/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java.feature/build.properties b/org.eclipse.babel.tapiji.tools.java.feature/build.properties deleted file mode 100644 index cc2efe00..00000000 --- a/org.eclipse.babel.tapiji.tools.java.feature/build.properties +++ /dev/null @@ -1,2 +0,0 @@ -bin.includes = feature.xml -src.includes = feature.xml diff --git a/org.eclipse.babel.tapiji.tools.java.feature/feature.xml b/org.eclipse.babel.tapiji.tools.java.feature/feature.xml deleted file mode 100644 index 3ff85c71..00000000 --- a/org.eclipse.babel.tapiji.tools.java.feature/feature.xml +++ /dev/null @@ -1,75 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<feature - id="org.eclipse.babel.tapiji.tools.java.feature" - label="Feature" - version="0.0.2.qualifier"> - - <description url="http://www.example.com/description"> - [Enter Feature Description here.] - </description> - - <copyright url="http://www.example.com/copyright"> - [Enter Copyright Description here.] - </copyright> - - <license url="http://www.example.com/license"> - [Enter License Description here.] - </license> - - <plugin - id="org.eclipse.babel.core" - download-size="0" - install-size="0" - version="0.8.0.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.editor" - download-size="0" - install-size="0" - version="0.8.0.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.editor.nls" - download-size="0" - install-size="0" - version="0.8.0.qualifier" - fragment="true"/> - - <plugin - id="org.eclipse.babel.tapiji.tools.core" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.tapiji.tools.core.ui" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.tapiji.tools.java" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.tapiji.tools.java.ui" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - - <plugin - id="org.eclipse.babel.tapiji.tools.rbmanager" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - -</feature> diff --git a/org.eclipse.babel.tapiji.tools.java.feature/pom.xml b/org.eclipse.babel.tapiji.tools.java.feature/pom.xml deleted file mode 100644 index e4a6e1de..00000000 --- a/org.eclipse.babel.tapiji.tools.java.feature/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.tapiji.tools.java.feature</artifactId> - <packaging>eclipse-feature</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java.ui/.classpath b/org.eclipse.babel.tapiji.tools.java.ui/.classpath deleted file mode 100644 index 0b1bcf94..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src/"/> - <classpathentry kind="output" path="target/classes"/> -</classpath> diff --git a/org.eclipse.babel.tapiji.tools.java.ui/.project b/org.eclipse.babel.tapiji.tools.java.ui/.project deleted file mode 100644 index 23e072de..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/.project +++ /dev/null @@ -1,34 +0,0 @@ -<?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> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> 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 deleted file mode 100644 index 466dfa53..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF +++ /dev/null @@ -1,31 +0,0 @@ -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.eclipse.babel.tapiji.tools.java.ui/OSGI-INF/l10n/bundle.properties b/org.eclipse.babel.tapiji.tools.java.ui/OSGI-INF/l10n/bundle.properties deleted file mode 100644 index 351740cc..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/OSGI-INF/l10n/bundle.properties +++ /dev/null @@ -1,3 +0,0 @@ -#Properties file for org.eclipse.babel.tapiji.tools.java.ui -hover.description = hovers constant strings -hover.label = Constant Strings \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java.ui/about.html b/org.eclipse.babel.tapiji.tools.java.ui/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java.ui/build.properties b/org.eclipse.babel.tapiji.tools.java.ui/build.properties deleted file mode 100644 index d0ceeea6..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - plugin.xml,\ - about.html,\ - OSGI-INF/l10n/bundle.properties -src.includes = about.html diff --git a/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml deleted file mode 100644 index 32cff36f..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml +++ /dev/null @@ -1,43 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?eclipse version="3.4"?> -<plugin> - <extension - point="org.eclipse.babel.tapiji.tools.core.builderExtension"> - <i18nAuditor - class="org.eclipse.babel.tapiji.tools.java.ui.JavaResourceAuditor"> - </i18nAuditor> - </extension> - <extension - point="org.eclipse.jdt.ui.javaEditorTextHovers"> - <hover - activate="true" - class="org.eclipse.babel.tapiji.tools.java.ui.ConstantStringHover" - description="%hover.description" - id="org.eclipse.babel.tapiji.tools.java.ui.ConstantStringHover" - label="%hover.label"> - </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> - <extension - point="org.eclipse.babel.core.refactoringService"> - <IRefactoringService - class="org.eclipse.babel.tapiji.tools.java.ui.refactoring.RefactoringService"> - </IRefactoringService> - </extension> -</plugin> diff --git a/org.eclipse.babel.tapiji.tools.java.ui/pom.xml b/org.eclipse.babel.tapiji.tools.java.ui/pom.xml deleted file mode 100644 index b8f5ffe0..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.tapiji.tools.java.ui</artifactId> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file 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 deleted file mode 100644 index 93d84631..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui; - -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 deleted file mode 100644 index dea2c537..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui; - -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; - protected List<SLLocation> brokenResourceReferences; - protected List<SLLocation> brokenBundleReferences; - - public JavaResourceAuditor() { - this.reset(); - } - - @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.addAll(csav.getConstantStringLiterals()); - - // Report all broken Resource-Bundle references - brokenResourceReferences.addAll(csav.getBrokenResourceReferences()); - - // Report all broken definitions to Resource-Bundle references - brokenBundleReferences.addAll(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; - } - - @Override - public void reset() { - constantLiterals = new ArrayList<SLLocation>(); - brokenResourceReferences = new ArrayList<SLLocation>(); - brokenBundleReferences = new ArrayList<SLLocation>(); - } -} 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 deleted file mode 100644 index b329f847..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java +++ /dev/null @@ -1,286 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * * * Contributors: - * Martin Reiterer - initial API and implementation - * Alexej Strelzow - integrated refactoring mechanism - ******************************************************************************/ -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.KeyRefactoringProposal; -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 (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 (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME - && (tokenEnd + 1) - tokenStart > 0) { - - // Cal10n extension - String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos( - manager.getProject().getName(), cu, tokenOffset - 1); - - if (metaData != null) { - completions.add(new KeyRefactoringProposal(tokenOffset, - metaData[1], manager.getProject().getName(), - metaData[0], metaData[2])); - } - - return completions; - } - - 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.toLowerCase())) { - if (!key.equals(fullToken)) { - completions.add(new MessageCompletionProposal( - tokenStart, tokenEnd - tokenStart, key, false)); - } else { - hit = true; - // Refactoring function - completions.add(new KeyRefactoringProposal(tokenStart, - fullToken, manager.getProject().getName(), - bundleName, null)); - } - } - } - 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 deleted file mode 100644 index c9b41629..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java +++ /dev/null @@ -1,231 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - Initial implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -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 deleted file mode 100644 index 886847a6..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -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/KeyRefactoringProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/KeyRefactoringProposal.java deleted file mode 100644 index 0549e4b9..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/KeyRefactoringProposal.java +++ /dev/null @@ -1,147 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -import org.eclipse.babel.core.message.manager.RBManager; -import org.eclipse.babel.editor.util.UIUtils; -import org.eclipse.core.runtime.IPath; -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; - -/** - * Proposal for the key refactoring. The gets triggerd if you press Ctrl + Shift - * + Space on an externalized (!) {@link String} or on an externalized (!) enum! - * The key must be registered in the system! - * - * @author Alexej Strelzow - */ -public class KeyRefactoringProposal implements IJavaCompletionProposal { - - private int startPos; - private String value; - private String projectName; - private String bundleName; - private String reference; - private String enumPath; - - /** - * Constructor for non Cal10n refactoring. - * - * @param startPos - * The starting position of the Ctrl + Shift + Space command. - * @param value - * The value of the key to refactor. - * @param projectName - * The project the resource bundle is in. - * @param bundleName - * The resource bundle, which contains the key to be refactored. - */ - public KeyRefactoringProposal(int startPos, String value, - String projectName, String bundleName) { - - this.startPos = startPos; - this.value = value; - this.projectName = projectName; - this.bundleName = bundleName; - } - - /** - * Constructor for Cal10n refactoring. - * - * @param startPos - * The starting position of the Ctrl + Shift + Space command. - * @param value - * The value of the key to refactor. - * @param projectName - * The project the resource bundle is in. - * @param bundleName - * The resource bundle, which contains the key to be refactored. - * @param enumPath - * The {@link IPath#toPortableString()} of the enum to change - */ - public KeyRefactoringProposal(int startPos, String value, - String projectName, String bundleName, String enumPath) { - this(startPos, value, projectName, bundleName); - this.enumPath = enumPath; // relative path (to the project) - } - - /** - * {@inheritDoc} - */ - @Override - public void apply(IDocument document) { - RBManager.getRefactorService().openRefactorDialog(projectName, - bundleName, value, enumPath); - } - - /** - * {@inheritDoc} - */ - @Override - public Point getSelection(IDocument document) { - int refLength = reference == null ? 0 : reference.length() - 1; - return new Point(startPos + refLength, 0); - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdditionalProposalInfo() { - - if (enumPath != null) { - return "Replace this enum key with a new one! \r\n" - + "This operation will automatically replace all references to the selected key " - + "with the new one. Also the enum value will be changed!"; - } else { - return "Replace this key with a new one! \r\n" - + "This operation will automatically replace all references to the selected key " - + "with the new one."; - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getDisplayString() { - return "Refactor this key..."; - } - - /** - * {@inheritDoc} - */ - @Override - public Image getImage() { - return UIUtils.getImageDescriptor(UIUtils.IMAGE_REFACTORING) - .createImage(); - } - - /** - * {@inheritDoc} - */ - @Override - public IContextInformation getContextInformation() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public int getRelevance() { - return 100; - } - -} 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 deleted file mode 100644 index 6d5d3939..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -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 deleted file mode 100644 index 8a68647c..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -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 deleted file mode 100644 index f6a6ec5b..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -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 deleted file mode 100644 index a49665f6..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -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 deleted file mode 100644 index 23d86fee..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.model; - -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 deleted file mode 100644 index 54f8a000..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.quickfix; - -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 deleted file mode 100644 index bcceaed9..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.quickfix; - -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.setPreselectedMessage((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 deleted file mode 100644 index 67429aa1..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.quickfix; - -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 deleted file mode 100644 index 162ad5cd..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.quickfix; - -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 deleted file mode 100644 index a959b54c..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.quickfix; - -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/refactoring/Cal10nEnumRefactoringVisitor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nEnumRefactoringVisitor.java deleted file mode 100644 index ec4a573e..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nEnumRefactoringVisitor.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.refactoring; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.babel.tapiji.tools.core.Logger; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.EnumConstantDeclaration; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; -import org.eclipse.text.edits.TextEdit; - -/** - * Changes the enum class, which is referenced by the Cal10n framework. It - * replaces the old key with the new one. - * - * @author Alexej Strelzow - */ -public class Cal10nEnumRefactoringVisitor extends ASTVisitor { - - private List<String> changeSet = new ArrayList<String>(); - - private String oldKey; - private String newKey; - private CompilationUnit enumCu; - - /** - * Constructor. - * - * @param oldKey - * The old key name - * @param newKey - * The new key name, which should overwrite the old one - * @param enumCu - * The {@link CompilationUnit} to modify - * @param changeSet - * The set of changes (protocol) - */ - public Cal10nEnumRefactoringVisitor(CompilationUnit enumCu, String oldKey, - String newKey, List<String> changeSet) { - this.oldKey = oldKey; - this.newKey = newKey; - this.enumCu = enumCu; - this.changeSet = changeSet; - } - - /** - * Modifies the enum file. It replaces the old key with the new one. - */ - public boolean visit(EnumConstantDeclaration node) { - - if (node.resolveVariable().getName().equals(oldKey)) { - - // ASTRewrite - AST ast = enumCu.getAST(); - ASTRewrite rewriter = ASTRewrite.create(ast); - - EnumConstantDeclaration newDeclaration = ast - .newEnumConstantDeclaration(); - - SimpleName newSimpleName = ast.newSimpleName(newKey); - newDeclaration.setName(newSimpleName); - - rewriter.replace(node, newDeclaration, null); - - try { - TextEdit textEdit = rewriter.rewriteAST(); - if (textEdit.hasChildren()) { // if the compilation unit has - // been - // changed - ICompilationUnit icu = (ICompilationUnit) enumCu - .getJavaElement(); - icu.applyTextEdit(textEdit, null); - icu.getBuffer().save(null, true); - - // protocol - int startPos = node.getStartPosition(); - changeSet.add(icu.getPath().toPortableString() + ": line " - + enumCu.getLineNumber(startPos)); - } - } catch (Exception e) { - Logger.logError(e); - } - } - - return false; - }; -} diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nRefactoringVisitor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nRefactoringVisitor.java deleted file mode 100644 index ec1ea6f5..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/Cal10nRefactoringVisitor.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.refactoring; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.babel.tapiji.tools.core.Logger; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.Name; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; -import org.eclipse.text.edits.TextEdit; - -/** - * Refactors java files, which are using the old enumeration key that gets - * refactored. - * - * @author Alexej Strelzow - */ -public class Cal10nRefactoringVisitor extends ASTVisitor { - - private List<String> changeSet = new ArrayList<String>(); - - private String oldKey; - private String newKey; - private String enumPath; - - private CompilationUnit cu; - private AST ast; - private ASTRewrite rewriter; - - /** - * Constructor. - * - * @param oldKey - * The old key name - * @param newKey - * The new key name, which should overwrite the old one - * @param enumPath - * The path of the enum file to change - * @param cu - * The {@link CompilationUnit} to modify - * @param changeSet - * The set of changes (protocol) - */ - public Cal10nRefactoringVisitor(CompilationUnit cu, String oldKey, - String newKey, String enumPath, List<String> changeSet) { - this.oldKey = oldKey; - this.newKey = newKey; - this.enumPath = enumPath; - this.cu = cu; - this.changeSet = changeSet; - this.ast = cu.getAST(); - this.rewriter = ASTRewrite.create(ast); - } - - /** - * Changes the argument of the IMessageConveyor#getMessage(...) call. The - * new enum key replaces the old one. - */ - @SuppressWarnings("unchecked") - public boolean visit(MethodInvocation node) { - - boolean isCal10nCall = "ch.qos.cal10n.IMessageConveyor".equals(node - .resolveMethodBinding().getDeclaringClass().getQualifiedName()); - - if (!isCal10nCall) { - if (node.arguments().size() == 0) { - return false; - } else { - return true; // because the Cal10n call may be an argument! - } - } else { - QualifiedName qName = (QualifiedName) node.arguments().get(0); - String fullPath = qName.resolveTypeBinding().getJavaElement() - .getResource().getFullPath().toPortableString(); - if (fullPath.equals(enumPath) - && qName.getName().toString().equals(oldKey)) { - - // ASTRewrite - Expression exp = (Expression) rewriter.createCopyTarget(node - .getExpression()); - - MethodInvocation newMethod = ast.newMethodInvocation(); - newMethod.setExpression(exp); - newMethod.setName(ast.newSimpleName(node.getName() - .getIdentifier())); - - SimpleName newSimpleName = ast.newSimpleName(newKey); - Name newName = ast.newName(qName.getQualifier() - .getFullyQualifiedName()); - QualifiedName newQualifiedName = ast.newQualifiedName(newName, - newSimpleName); - - newMethod.arguments().add(newQualifiedName); - rewriter.replace(node, newMethod, null); - - // protocol - int startPos = node.getStartPosition(); - ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); - changeSet.add(icu.getPath().toPortableString() + ": line " - + cu.getLineNumber(startPos)); - } - } - - return false; - } - - /** - * Saves the changes, which were made in {@link #visit(MethodInvocation)} - */ - public void saveChanges() { - try { - TextEdit textEdit = rewriter.rewriteAST(); - if (textEdit.hasChildren()) { // if the compilation unit has been - // changed - ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); - icu.applyTextEdit(textEdit, null); - icu.getBuffer().save(null, true); - } - } catch (Exception e) { - Logger.logError(e); - } - } -} diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/PrimitiveRefactoringVisitor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/PrimitiveRefactoringVisitor.java deleted file mode 100644 index e6d5762f..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/PrimitiveRefactoringVisitor.java +++ /dev/null @@ -1,255 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.refactoring; - -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; - -import org.eclipse.babel.tapiji.tools.core.Logger; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -import org.eclipse.jdt.core.dom.VariableDeclarationStatement; -import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; -import org.eclipse.text.edits.TextEdit; - -/** - * Executes the refactoring operation. That is, it changes the - * {@link CompilationUnit} and saves the changes via {@link ASTRewrite}. - * - * @author Alexej Strelzow - */ -public class PrimitiveRefactoringVisitor extends ASTVisitor { - - private String varNameOfBundle; // name of the variable, which references - // the resource bundle - private List<String> changeSet = new ArrayList<String>(); - - private String oldKey; - private String newKey; - private String resourceBundleId; - - private CompilationUnit cu; - private AST ast; - private ASTRewrite rewriter; - - /** - * Constructor. - * - * @param cu - * The {@link CompilationUnit} to modify - * @param resourceBundleId - * The Id of the resource bundle to change - * @param oldKey - * The old key name - * @param newKey - * The new key name, which should overwrite the old one - * @param changeSet - * The set of changes (protocol) - */ - public PrimitiveRefactoringVisitor(CompilationUnit cu, - String resourceBundleId, String oldKey, String newKey, - List<String> changeSet) { - this.oldKey = oldKey; - this.newKey = newKey; - this.resourceBundleId = resourceBundleId; - this.cu = cu; - this.changeSet = changeSet; - this.ast = cu.getAST(); - this.rewriter = ASTRewrite.create(ast); - } - - /** - * GLOBAL VARS:<br> - * <br> - * Find the variable name of the bundle (if exists!) E.g.: - * - * <pre> - * static ResourceBundle applicationresourcesref = ResourceBundle - * .getBundle(&quot;dev.ApplicationResources&quot;); - * </pre> - * - * {@inheritDoc} - */ - @Override - public boolean visit(FieldDeclaration node) { - for (Object obj : node.fragments()) { - String val = getVarNameOfBundle((VariableDeclarationFragment) obj, - resourceBundleId); - - if (val != null) { - varNameOfBundle = val; - } - } - return false; - } - - /** - * LOCAL VARS: <br> - * <br> - * Find the variable name of the bundle (if exists!) E.g.: - * - * <pre> - * ResourceBundle applicationresourcesref = ResourceBundle - * .getBundle(&quot;dev.ApplicationResources&quot;); - * </pre> - * - * {@inheritDoc} - */ - @SuppressWarnings("rawtypes") - @Override - public boolean visit(VariableDeclarationStatement node) { - for (Object obj : node.fragments()) { - String val = getVarNameOfBundle((VariableDeclarationFragment) obj, - resourceBundleId); - - if (val != null) { - varNameOfBundle = val; - } - - // [alst] because visit(MethodInvocation node) does not work when - // the MethodInvocation is embedded - // in an Initializer (I don't know why...) - if (!node.fragments().isEmpty()) { - List fragments = node.fragments(); - ListIterator listIterator = fragments.listIterator(); - while (listIterator.hasNext()) { - Object element = listIterator.next(); - if (element instanceof VariableDeclarationFragment) { - VariableDeclarationFragment fragment = (VariableDeclarationFragment) element; - Expression initializer = fragment.getInitializer(); - if (initializer != null - && initializer instanceof MethodInvocation) { - visit((MethodInvocation) initializer); - } - } - } - } - - } - return false; - } - - @Override - public boolean visit(StringLiteral node) { - // TODO Auto-generated method stub - return super.visit(node); - } - - /** - * Searches for the {@link MethodInvocation}, which needs to be modified. It - * gets only executed, if the variable name of the resource bundle has been - * found. E.g. applicationresourcesref: - * - * <pre> - * ResourceBundle applicationresourcesref = ResourceBundle - * .getBundle(&quot;dev.ApplicationResources&quot;); - * </pre> - */ - @SuppressWarnings("unchecked") - @Override - public boolean visit(MethodInvocation node) { - if (varNameOfBundle == null) { - return false; - } - - boolean isResourceBundle = "java.util.ResourceBundle".equals(node - .resolveMethodBinding().getDeclaringClass().getQualifiedName()); - - if (!isResourceBundle) { - if (node.arguments().size() == 0) { - return false; - } else { - return true; // because the call (we are searching for) may be - // an argument! - } - } else { - // check the name of the caller, is it our resource bundle? - if (node.getExpression() instanceof SimpleName - && varNameOfBundle.equals(node.getExpression().toString())) { - - // is the parameter the old key? - StringLiteral literal = (StringLiteral) node.arguments().get(0); - - if (oldKey.equals(literal.getLiteralValue())) { - - // ASTRewrite - Expression exp = (Expression) rewriter - .createCopyTarget(node.getExpression()); - - MethodInvocation newMethod = ast.newMethodInvocation(); - newMethod.setExpression(exp); - newMethod.setName(ast.newSimpleName(node.getName() - .getIdentifier())); - - StringLiteral newStringLiteral = ast.newStringLiteral(); - newStringLiteral.setLiteralValue(newKey); - newMethod.arguments().add(newStringLiteral); - rewriter.replace(node, newMethod, null); - - // protocol - int startPos = node.getStartPosition(); - ICompilationUnit icu = (ICompilationUnit) cu - .getJavaElement(); - changeSet.add(icu.getPath().toPortableString() + ": line " - + cu.getLineNumber(startPos)); - } - } - } - return false; - } - - /** - * Saves the changes, which were made in {@link #visit(MethodInvocation)} - */ - public void saveChanges() { - try { - TextEdit textEdit = rewriter.rewriteAST(); - if (textEdit.hasChildren()) { // if the compilation unit has been - // changed - ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); - icu.applyTextEdit(textEdit, null); - icu.getBuffer().save(null, true); - } - } catch (Exception e) { - Logger.logError(e); - } - } - - private static String getVarNameOfBundle(VariableDeclarationFragment vdf, - String resourceBundleId) { - - // Is the referenced bundle in there? - if (vdf.getInitializer() != null - && vdf.getInitializer() instanceof MethodInvocation) { - MethodInvocation method = (MethodInvocation) vdf.getInitializer(); - - // what's the name of the variable of the target res. bundle? - for (Object arg : method.arguments()) { - if (arg instanceof StringLiteral - && resourceBundleId.equals(((StringLiteral) arg) - .getLiteralValue())) { - return vdf.getName().toString(); - } - } - } - - return null; - } -} diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/RefactoringService.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/RefactoringService.java deleted file mode 100644 index 388acbee..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/refactoring/RefactoringService.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Alexej Strelzow - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.ui.refactoring; - -import org.eclipse.babel.core.message.IMessagesBundleGroup; -import org.eclipse.babel.core.refactoring.IRefactoringService; -import org.eclipse.babel.tapiji.tools.core.ui.ResourceBundleManager; -import org.eclipse.babel.tapiji.tools.core.ui.dialogs.KeyRefactoringDialog; -import org.eclipse.babel.tapiji.tools.core.ui.dialogs.KeyRefactoringDialog.DialogConfiguration; -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.IFile; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jface.dialogs.InputDialog; -import org.eclipse.jface.text.IRegion; -import org.eclipse.swt.widgets.Display; - -/** - * Service class, which can be used to execute key refactorings. - * - * @author Alexej Strelzow - */ -public class RefactoringService implements IRefactoringService { - - /** - * {@inheritDoc} - */ - @Override - public void refactorKey(String projectName, String resourceBundleId, - String selectedLocale, String oldKey, String newKey, String enumName) { - ASTutilsUI.refactorKey(projectName, resourceBundleId, selectedLocale, - oldKey, newKey, enumName); - } - - /** - * {@inheritDoc} - */ - @Override - public void openRefactorDialog(String projectName, String resourceBundleId, - String oldKey, String enumName) { - - KeyRefactoringDialog dialog = new KeyRefactoringDialog(Display - .getDefault().getActiveShell()); - - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(oldKey); - config.setPreselectedBundle(resourceBundleId); - config.setProjectName(projectName); - - dialog.setDialogConfiguration(config); - - if (dialog.open() != InputDialog.OK) { - return; - } - - refactorKey(projectName, resourceBundleId, config.getSelectedLocale(), - oldKey, config.getNewKey(), enumName); - } - - /** - * {@inheritDoc} - */ - @Override - public void openRefactorDialog(IFile file, int selectionOffset) { - - String projectName = file.getProject().getName(); - CompilationUnit cu = ASTutilsUI.getCompilationUnit(file); - - StringLiteral literal = ASTutils.getStringLiteralAtPos(cu, - selectionOffset); - - if (literal == null) { // check for Cal10n - String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos( - projectName, cu, selectionOffset); - if (metaData != null) { - openRefactorDialog(projectName, metaData[0], metaData[1], - metaData[2]); - } - } else { // it's a String (not Cal10n) - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - ResourceAuditVisitor visitor = new ResourceAuditVisitor(file, - projectName); - cu.accept(visitor); - - String oldKey = literal.getLiteralValue(); - IRegion region = visitor.getKeyAt(new Long(selectionOffset)); - String bundleName = visitor.getBundleReference(region); - if (bundleName != null) { - IMessagesBundleGroup resourceBundle = manager - .getResourceBundle(bundleName); - if (resourceBundle.containsKey(oldKey)) { - String resourceBundleId = resourceBundle - .getResourceBundleId(); - - openRefactorDialog(projectName, resourceBundleId, oldKey, - null); - } - } - } - } -} 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 deleted file mode 100644 index 07aeee57..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java +++ /dev/null @@ -1,302 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * Alexej Strelzow - seperation of ui/non-ui (methods moved from ASTUtils) - ******************************************************************************/ - -package org.eclipse.babel.tapiji.tools.java.ui.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.eclipse.babel.core.configuration.DirtyHack; -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.util.FileUtils; -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.KeyRefactoringDialog; -import org.eclipse.babel.tapiji.tools.core.ui.dialogs.KeyRefactoringDialog.DialogConfiguration; -import org.eclipse.babel.tapiji.tools.core.ui.dialogs.KeyRefactoringSummaryDialog; -import org.eclipse.babel.tapiji.tools.core.ui.utils.LocaleUtils; -import org.eclipse.babel.tapiji.tools.java.ui.refactoring.Cal10nEnumRefactoringVisitor; -import org.eclipse.babel.tapiji.tools.java.ui.refactoring.Cal10nRefactoringVisitor; -import org.eclipse.babel.tapiji.tools.java.ui.refactoring.PrimitiveRefactoringVisitor; -import org.eclipse.babel.tapiji.tools.java.util.ASTutils; -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.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.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.ui.SharedASTProvider; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.swt.widgets.Display; - -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; - } - - /** - * Performs the refactoring of messages key. The key can be a {@link String} - * or an Enumeration! If it is an enumeration, then the enumPath needs to be - * provided! - * - * @param projectName - * The name of the project, where the resource bundle file is in - * @param resourceBundleId - * The Id of the resource bundle, which contains the old key - * @param selectedLocale - * The {@link Locale} to change - * @param oldKey - * The name of the key to change - * @param newKey - * The name of the key, which replaces the old one - * @param enumPath - * The path of the enum file (needs: - * {@link IPath#toPortableString()}) - */ - public static void refactorKey(final String projectName, - final String resourceBundleId, final String selectedLocale, - final String oldKey, final String newKey, final String enumPath) { - - // contains file and line - final List<String> changeSet = new ArrayList<String>(); - - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - IProject project = manager.getProject(); - - try { - project.accept(new IResourceVisitor() { - - /** - * First step of filtering. Only classes, which import - * java.util.ResourceBundle or ch.qos.cal10n.MessageConveyor - * will be changed. An exception is the enum file, which gets - * referenced by the Cal10n framework. - * - * {@inheritDoc} - */ - @Override - public boolean visit(IResource resource) throws CoreException { - if (!(resource instanceof IFile) - || !resource.getFileExtension().equals("java")) { - return true; - } - - final CompilationUnit cu = getCompilationUnit(resource); - - // step 1: import filter - for (Object obj : cu.imports()) { - ImportDeclaration imp = (ImportDeclaration) obj; - String importName = imp.getName().toString(); - if ("java.util.ResourceBundle".equals(importName)) { - PrimitiveRefactoringVisitor prv = new PrimitiveRefactoringVisitor( - cu, resourceBundleId, oldKey, newKey, - changeSet); - cu.accept(prv); - prv.saveChanges(); - break; - } else if ("ch.qos.cal10n.MessageConveyor" - .equals(importName)) { // Cal10n - Cal10nRefactoringVisitor crv = new Cal10nRefactoringVisitor( - cu, oldKey, newKey, enumPath, changeSet); - cu.accept(crv); - crv.saveChanges(); - break; - } - } - - return false; - } - }); - } catch (CoreException e) { - Logger.logError(e); - } - - if (enumPath != null) { // Cal10n support, change the enum file - IFile file = project.getFile(enumPath.substring(project.getName() - .length() + 1)); - final CompilationUnit enumCu = getCompilationUnit(file); - - Cal10nEnumRefactoringVisitor enumVisitor = new Cal10nEnumRefactoringVisitor( - enumCu, oldKey, newKey, changeSet); - enumCu.accept(enumVisitor); - } - - // change backend - RBManager rbManager = RBManager.getInstance(projectName); - IMessagesBundleGroup messagesBundleGroup = rbManager - .getMessagesBundleGroup(resourceBundleId); - - DirtyHack.setFireEnabled(false); // now the editor won't get dirty - // but with this change, we have to write it manually down -> rbManager.writeToFile - if (KeyRefactoringDialog.ALL_LOCALES.equals(selectedLocale)) { - messagesBundleGroup.renameMessageKeys(oldKey, newKey); - - } else { - IMessagesBundle messagesBundle = messagesBundleGroup - .getMessagesBundle(LocaleUtils.getLocaleByDisplayName( - manager.getProvidedLocales(resourceBundleId), - selectedLocale)); - messagesBundle.renameMessageKey(oldKey, newKey); - // rbManager.fireResourceChanged(messagesBundle); ?? - } - DirtyHack.setFireEnabled(true); - - rbManager.fireEditorChanged(); // notify Resource Bundle View - rbManager.writeToFile(rbManager.getMessagesBundleGroup(resourceBundleId)); - - // show the summary dialog - KeyRefactoringSummaryDialog summaryDialog = new KeyRefactoringSummaryDialog( - Display.getDefault().getActiveShell()); - - DialogConfiguration config = summaryDialog.new DialogConfiguration(); - config.setPreselectedKey(oldKey); - config.setNewKey(newKey); - config.setPreselectedBundle(resourceBundleId); - config.setProjectName(projectName); - - summaryDialog.setDialogConfiguration(config); - summaryDialog.setChangeSet(changeSet); - - summaryDialog.open(); - } - -} diff --git a/org.eclipse.babel.tapiji.tools.java/.classpath b/org.eclipse.babel.tapiji.tools.java/.classpath deleted file mode 100644 index 0b1bcf94..00000000 --- a/org.eclipse.babel.tapiji.tools.java/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src/"/> - <classpathentry kind="output" path="target/classes"/> -</classpath> diff --git a/org.eclipse.babel.tapiji.tools.java/.project b/org.eclipse.babel.tapiji.tools.java/.project deleted file mode 100644 index 32af1709..00000000 --- a/org.eclipse.babel.tapiji.tools.java/.project +++ /dev/null @@ -1,34 +0,0 @@ -<?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> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF deleted file mode 100644 index 8f20432e..00000000 --- a/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF +++ /dev/null @@ -1,21 +0,0 @@ -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/about.html b/org.eclipse.babel.tapiji.tools.java/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.tapiji.tools.java/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java/build.properties b/org.eclipse.babel.tapiji.tools.java/build.properties deleted file mode 100644 index 3e7f0edc..00000000 --- a/org.eclipse.babel.tapiji.tools.java/build.properties +++ /dev/null @@ -1,5 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - about.html -src.includes = about.html diff --git a/org.eclipse.babel.tapiji.tools.java/pom.xml b/org.eclipse.babel.tapiji.tools.java/pom.xml deleted file mode 100644 index 012b48d4..00000000 --- a/org.eclipse.babel.tapiji.tools.java/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.tapiji.tools.java</artifactId> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file 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 deleted file mode 100644 index 8e64a4a3..00000000 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java +++ /dev/null @@ -1,1073 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - * 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.core.message.IMessagesBundleGroup; -import org.eclipse.babel.core.message.manager.RBManager; -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.IAnnotationBinding; -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.QualifiedName; -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; - } - } - - /** - * Decides if an enumeration can be refactored or not. In other words, gives - * the OK for the Proposal to display. - * - * @author Alexej Strelzow - */ - static class Cal10nEnumLiteralFinder extends ASTVisitor { - private int position; - private String projectName; - - private String[] metaData; - - // [0] resourceBunldeId - // [1] key value - // [2] relative path (to the project) of the enum file - - /** - * Constructor. - * - * @param position - * The position of the CTRL + Shift + Space operation - */ - public Cal10nEnumLiteralFinder(String projectName, int position) { - this.position = position; - this.projectName = projectName; - } - - /** - * Following constraints must be fulfilled to make an enum - * "refactorable":<br> - * <ol> - * <li>It must be known by the system (stored in a resource bundle file) - * </li> - * <li>It must be used by the class ch.qos.cal10n.IMessageConveyor - * (Cal10n framework)</li> - * </ol> - * - * {@inheritDoc} - */ - public boolean visit(MethodInvocation node) { - - boolean isCal10nCall = "ch.qos.cal10n.IMessageConveyor".equals(node - .resolveMethodBinding().getDeclaringClass() - .getQualifiedName()); - - if (!isCal10nCall) { - if (node.arguments().size() == 0) { - return false; - } else { - return true; // because the Cal10n call may be an argument! - } - } else { - int startPosition = node.getStartPosition(); - int length = startPosition + node.getLength(); - if (startPosition < this.position && length > position - && !node.arguments().isEmpty() - && node.arguments().get(0) instanceof QualifiedName) { - QualifiedName qName = (QualifiedName) node.arguments().get( - 0); - startPosition = qName.getStartPosition(); - length = startPosition + qName.getLength(); - - if (startPosition < this.position && length > position) { - String resourceBundleId = getResourceBundleId(qName); - String keyName = qName.getName().toString(); - - if (isKnownBySystem(resourceBundleId, keyName)) { - String path = qName.resolveTypeBinding() - .getJavaElement().getResource() - .getFullPath().toPortableString(); - this.metaData = new String[3]; - this.metaData[0] = resourceBundleId; - this.metaData[1] = keyName; - this.metaData[2] = path; - } - } - } - } - - return false; - } - - private boolean isKnownBySystem(String resourceBundleId, String keyName) { - IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( - this.projectName).getMessagesBundleGroup(resourceBundleId); - return messagesBundleGroup.containsKey(keyName); - } - - private String getResourceBundleId(QualifiedName qName) { - IAnnotationBinding[] annotations = qName.resolveTypeBinding() - .getAnnotations(); - for (IAnnotationBinding annotation : annotations) { - if ("BaseName".equals(annotation.getName())) { - return (String) annotation.getAllMemberValuePairs()[0] - .getValue(); - } - } - - return null; - } - - public String[] getMetaData() { - return metaData; - } - } - - /** - * Returns whether a refactoring proposal will be shown or not. - * - * @param projectName - * The name of the project the cu is in - * @param cu - * The {@link CompilationUnit} to analyze - * @param i - * The starting point to begin the analysis - * @return Meta data of the enum key to refactor or null - */ - public static String[] getCal10nEnumLiteralDataAtPos(String projectName, - CompilationUnit cu, int i) { - Cal10nEnumLiteralFinder enumFinder = new Cal10nEnumLiteralFinder( - projectName, i); - cu.accept(enumFinder); - return enumFinder.getMetaData(); - } -} 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 deleted file mode 100644 index 34db6026..00000000 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.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 deleted file mode 100644 index e431fc84..00000000 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java +++ /dev/null @@ -1,261 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.java.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.eclipse.babel.tapiji.tools.rbmanager/.classpath b/org.eclipse.babel.tapiji.tools.rbmanager/.classpath deleted file mode 100644 index 0b1bcf94..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src/"/> - <classpathentry kind="output" path="target/classes"/> -</classpath> diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/.project b/org.eclipse.babel.tapiji.tools.rbmanager/.project deleted file mode 100644 index bd5c2229..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/.project +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.rbmanager.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> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.rbmanager/META-INF/MANIFEST.MF deleted file mode 100644 index 1ba2b2c8..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/META-INF/MANIFEST.MF +++ /dev/null @@ -1,15 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Manager -Bundle-SymbolicName: org.eclipse.babel.tapiji.tools.rbmanager.ui;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.eclipse.babel.tapiji.tools.rbmanager/OSGI-INF/l10n/bundle.properties b/org.eclipse.babel.tapiji.tools.rbmanager/OSGI-INF/l10n/bundle.properties deleted file mode 100644 index 6e0596b7..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/OSGI-INF/l10n/bundle.properties +++ /dev/null @@ -1,7 +0,0 @@ -#Properties file for org.eclipse.babel.tapiji.tools.rbmanager.ui -view.rbe.name = Resource Bundle Explorer -action.filter.label = Filter Problematic ResourceBundles -action.filter.tooltip = Filters ResourceBundles With Warnings -action.expand.label = Expand All -navigatorContent.name = Resource Bundle Content -commonFilter.name = Problematic Resource Bundle Files \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/about.html b/org.eclipse.babel.tapiji.tools.rbmanager/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties deleted file mode 100644 index 3175f51f..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties +++ /dev/null @@ -1,10 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - icons/,\ - about.html,\ - plugin.xml,\ - OSGI-INF/l10n/bundle.properties -src.includes = icons/,\ - about.html diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/__.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/__.gif deleted file mode 100644 index 65167847..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/__.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/_f.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/_f.gif deleted file mode 100644 index a5f340d4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/_f.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ad.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ad.gif deleted file mode 100644 index 0b240549..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ad.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ae.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ae.gif deleted file mode 100644 index a4a82ff8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ae.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/af.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/af.gif deleted file mode 100644 index 70e1a15b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/af.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ag.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ag.gif deleted file mode 100644 index 2dc04e5e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ag.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/al.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/al.gif deleted file mode 100644 index 1384f59b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/al.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/am.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/am.gif deleted file mode 100644 index eda901ed..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/am.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ao.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ao.gif deleted file mode 100644 index 56f02bbc..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ao.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/aq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/aq.gif deleted file mode 100644 index d8e99da6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/aq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ar.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ar.gif deleted file mode 100644 index 0231d503..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ar.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/at.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/at.gif deleted file mode 100644 index ecf48b9b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/at.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/au.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/au.gif deleted file mode 100644 index 77761249..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/au.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/az.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/az.gif deleted file mode 100644 index bc77ff24..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/az.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ba.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ba.gif deleted file mode 100644 index 8e4e5499..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ba.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bb.gif deleted file mode 100644 index 54928a68..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bd.gif deleted file mode 100644 index 25890b90..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/be.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/be.gif deleted file mode 100644 index f917f396..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/be.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bf.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bf.gif deleted file mode 100644 index 53afd44c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bf.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bg.gif deleted file mode 100644 index 5ce1db10..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bh.gif deleted file mode 100644 index ba39230e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bi.gif deleted file mode 100644 index ee3d6a48..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bj.gif deleted file mode 100644 index 55463ef0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/blank.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/blank.gif deleted file mode 100644 index 314b8633..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/blank.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bn.gif deleted file mode 100644 index ed11638b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bo.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bo.gif deleted file mode 100644 index f1796980..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bo.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/br.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/br.gif deleted file mode 100644 index e1069e08..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/br.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bs.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bs.gif deleted file mode 100644 index 30c32c32..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bs.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bt.gif deleted file mode 100644 index b53dddfb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bw.gif deleted file mode 100644 index d73ad712..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/by.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/by.gif deleted file mode 100644 index 3335ae02..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/by.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bz.gif deleted file mode 100644 index ec056372..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/bz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ca.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ca.gif deleted file mode 100644 index 547011ac..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ca.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cd.gif deleted file mode 100644 index 44fa4411..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cf.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cf.gif deleted file mode 100644 index 41405ce0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cf.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cg.gif deleted file mode 100644 index 00fa29c0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ch.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ch.gif deleted file mode 100644 index b0dc176e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ch.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ci.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ci.gif deleted file mode 100644 index b1167c0d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ci.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cl.gif deleted file mode 100644 index 31dcb03e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cm.gif deleted file mode 100644 index f361dbd7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cn.gif deleted file mode 100644 index f12f17d1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/co.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/co.gif deleted file mode 100644 index d9f14e79..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/co.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cr.gif deleted file mode 100644 index 2a5f0b93..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cs.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cs.gif deleted file mode 100644 index 580d26f5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cs.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cu.gif deleted file mode 100644 index 823befcc..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cv.gif deleted file mode 100644 index d21a45cb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cy.gif deleted file mode 100644 index 1a332d90..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cz.gif deleted file mode 100644 index 2faee5e1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/cz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dd.gif deleted file mode 100644 index 99eda38f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/de.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/de.gif deleted file mode 100644 index c7b28406..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/de.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dj.gif deleted file mode 100644 index 94fc2eb3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dk.gif deleted file mode 100644 index 4f01ec95..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dm.gif deleted file mode 100644 index b4fed906..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/do.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/do.gif deleted file mode 100644 index 85d7be8b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/do.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dz.gif deleted file mode 100644 index 622ff6ba..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/dz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ec.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ec.gif deleted file mode 100644 index 5d1641b1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ec.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ee.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ee.gif deleted file mode 100644 index c678c73c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ee.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eg.gif deleted file mode 100644 index a740c668..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eh.gif deleted file mode 100644 index 6a75cc3c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/er.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/er.gif deleted file mode 100644 index 71297d62..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/er.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/es.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/es.gif deleted file mode 100644 index 6dee15c1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/es.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/et.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/et.gif deleted file mode 100644 index 4188e4ff..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/et.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eu.gif deleted file mode 100644 index 45caabf2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/eu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fi.gif deleted file mode 100644 index b8311cac..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fj.gif deleted file mode 100644 index f5481b79..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fm.gif deleted file mode 100644 index 050eca09..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fr.gif deleted file mode 100644 index a2a2354d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/fr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ga.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ga.gif deleted file mode 100644 index 54fb2514..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ga.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gb.gif deleted file mode 100644 index 4ae2d0f8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gd.gif deleted file mode 100644 index 0095032c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ge.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ge.gif deleted file mode 100644 index f3927c8a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ge.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gh.gif deleted file mode 100644 index 6d3b6142..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gm.gif deleted file mode 100644 index 2ecf0b0b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gn.gif deleted file mode 100644 index 83179352..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gq.gif deleted file mode 100644 index 6c2bc475..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gr.gif deleted file mode 100644 index 1599add4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gt.gif deleted file mode 100644 index c306f25d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gw.gif deleted file mode 100644 index 6cba5901..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gy.gif deleted file mode 100644 index a4b4da97..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/gy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hk.gif deleted file mode 100644 index 230723af..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hn.gif deleted file mode 100644 index 05501572..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hr.gif deleted file mode 100644 index 893778a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ht.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ht.gif deleted file mode 100644 index e5cf7803..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ht.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hu.gif deleted file mode 100644 index 07778839..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/hu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/id.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/id.gif deleted file mode 100644 index 9fed7642..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/id.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ie.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ie.gif deleted file mode 100644 index 82ec5535..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ie.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/il.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/il.gif deleted file mode 100644 index 554a7612..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/il.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/in.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/in.gif deleted file mode 100644 index 430b37b9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/in.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/iq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/iq.gif deleted file mode 100644 index dae4d593..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/iq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ir.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ir.gif deleted file mode 100644 index 50f5432a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ir.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/is.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/is.gif deleted file mode 100644 index e9580e07..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/is.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/it.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/it.gif deleted file mode 100644 index 4256b464..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/it.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jm.gif deleted file mode 100644 index f1459feb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jo.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jo.gif deleted file mode 100644 index a9d36128..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jo.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jp.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jp.gif deleted file mode 100644 index ddad6e3b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/jp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ke.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ke.gif deleted file mode 100644 index 6e06f4a7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ke.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kg.gif deleted file mode 100644 index e47fb0f2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kh.gif deleted file mode 100644 index 31f5be16..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ki.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ki.gif deleted file mode 100644 index 9f12bb0d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ki.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/km.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/km.gif deleted file mode 100644 index 027276bf..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/km.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kn.gif deleted file mode 100644 index f690875e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kp.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kp.gif deleted file mode 100644 index 42584efa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kr.gif deleted file mode 100644 index 800c6cdd..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kw.gif deleted file mode 100644 index ff083b5e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kz.gif deleted file mode 100644 index 9b13afe0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/kz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ar.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ar.gif deleted file mode 100644 index 4b7632ee..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ar.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_be.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_be.gif deleted file mode 100644 index 3335ae02..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_be.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_bg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_bg.gif deleted file mode 100644 index 5ce1db10..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_bg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_cz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_cz.gif deleted file mode 100644 index 2faee5e1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_cz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_de.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_de.gif deleted file mode 100644 index c7b28406..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_de.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_dk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_dk.gif deleted file mode 100644 index 4f01ec95..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_dk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_el.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_el.gif deleted file mode 100644 index 1599add4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_el.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_en.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_en.gif deleted file mode 100644 index 4ae2d0f8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_en.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_es.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_es.gif deleted file mode 100644 index 6dee15c1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_es.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_et.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_et.gif deleted file mode 100644 index c678c73c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_et.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fi.gif deleted file mode 100644 index b8311cac..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fr.gif deleted file mode 100644 index a2a2354d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_fr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ga.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ga.gif deleted file mode 100644 index 82ec5535..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ga.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hi.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hi.gif deleted file mode 100644 index 430b37b9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hr.gif deleted file mode 100644 index 893778a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hu.gif deleted file mode 100644 index 07778839..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_hu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_in.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_in.gif deleted file mode 100644 index 9fed7642..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_in.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_is.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_is.gif deleted file mode 100644 index e9580e07..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_is.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_it.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_it.gif deleted file mode 100644 index 4256b464..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_it.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_iw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_iw.gif deleted file mode 100644 index 554a7612..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_iw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ja.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ja.gif deleted file mode 100644 index ddad6e3b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ja.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ko.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ko.gif deleted file mode 100644 index 800c6cdd..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ko.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lt.gif deleted file mode 100644 index 78447f07..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lv.gif deleted file mode 100644 index 5f7419c6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_lv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mk.gif deleted file mode 100644 index 88c077fa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ms.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ms.gif deleted file mode 100644 index 8874751b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ms.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mt.gif deleted file mode 100644 index 677969a7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_mt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_nl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_nl.gif deleted file mode 100644 index c4258e62..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_nl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_no.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_no.gif deleted file mode 100644 index 873baca1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_no.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pl.gif deleted file mode 100644 index 6ff3ba6f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pt.gif deleted file mode 100644 index 9bfc8ca4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_pt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ro.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ro.gif deleted file mode 100644 index 6bdbad14..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ro.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ru.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ru.gif deleted file mode 100644 index cf4d30c8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_ru.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sk.gif deleted file mode 100644 index b0c4ab19..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sl.gif deleted file mode 100644 index 00d59d3b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sq.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sq.gif deleted file mode 100644 index 1384f59b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sr.gif deleted file mode 100644 index 580d26f5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sv.gif deleted file mode 100644 index 9bbcb1fa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_sv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_th.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_th.gif deleted file mode 100644 index 83318c0c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_th.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_tr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_tr.gif deleted file mode 100644 index 2eac7305..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_tr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_uk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_uk.gif deleted file mode 100644 index bebd6705..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_uk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_vn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_vn.gif deleted file mode 100644 index e7d1e5b9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_vn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_zh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_zh.gif deleted file mode 100644 index f12f17d1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/l_zh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/la.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/la.gif deleted file mode 100644 index 3c6f2f15..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/la.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lb.gif deleted file mode 100644 index f3c45527..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lc.gif deleted file mode 100644 index fdcbd97f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/li.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/li.gif deleted file mode 100644 index eb9d9384..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/li.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lk.gif deleted file mode 100644 index 3aa25aa8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lr.gif deleted file mode 100644 index f54468fc..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ls.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ls.gif deleted file mode 100644 index c1ad8d2f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ls.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lt.gif deleted file mode 100644 index 78447f07..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lu.gif deleted file mode 100644 index d74df5ab..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lv.gif deleted file mode 100644 index 5f7419c6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/lv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ly.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ly.gif deleted file mode 100644 index 8ca9e0a0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ly.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ma.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ma.gif deleted file mode 100644 index 3aab8cbb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ma.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mc.gif deleted file mode 100644 index c22c1717..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/md.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/md.gif deleted file mode 100644 index 4951b21a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/md.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mg.gif deleted file mode 100644 index 24281d87..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mh.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mh.gif deleted file mode 100644 index c472aee6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mk.gif deleted file mode 100644 index 88c077fa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ml.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ml.gif deleted file mode 100644 index 4eb75ae1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ml.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mm.gif deleted file mode 100644 index bd378555..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mn.gif deleted file mode 100644 index de3029b3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mr.gif deleted file mode 100644 index d7cbb38a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mt.gif deleted file mode 100644 index 677969a7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mu.gif deleted file mode 100644 index d102ab7e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mv.gif deleted file mode 100644 index 69ac6863..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mw.gif deleted file mode 100644 index a0f0320b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mx.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mx.gif deleted file mode 100644 index bbcb376b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mx.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/my.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/my.gif deleted file mode 100644 index 8874751b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/my.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mz.gif deleted file mode 100644 index b63af289..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/mz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/na.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/na.gif deleted file mode 100644 index bee7072e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/na.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ne.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ne.gif deleted file mode 100644 index fc1b74b8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ne.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ng.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ng.gif deleted file mode 100644 index 43af12c9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ng.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ni.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ni.gif deleted file mode 100644 index cac0042d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ni.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nl.gif deleted file mode 100644 index c4258e62..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/no.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/no.gif deleted file mode 100644 index 873baca1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/no.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/np.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/np.gif deleted file mode 100644 index f01f2f9e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/np.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nr.gif deleted file mode 100644 index d485c4b1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nu.gif deleted file mode 100644 index 73177056..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nz.gif deleted file mode 100644 index 49f8464e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/nz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/om.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/om.gif deleted file mode 100644 index d90ca333..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/om.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pa.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pa.gif deleted file mode 100644 index cae5432f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pe.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pe.gif deleted file mode 100644 index e6cc7348..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pe.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pg.gif deleted file mode 100644 index 108204f3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ph.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ph.gif deleted file mode 100644 index b141cd81..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ph.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pk.gif deleted file mode 100644 index f612b977..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pl.gif deleted file mode 100644 index 6ff3ba6f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ps.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ps.gif deleted file mode 100644 index 71717cc9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ps.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pt.gif deleted file mode 100644 index 9bfc8ca4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pw.gif deleted file mode 100644 index 0a520911..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/pw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/py.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/py.gif deleted file mode 100644 index b52de243..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/py.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/qa.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/qa.gif deleted file mode 100644 index e078e46c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/qa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ro.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ro.gif deleted file mode 100644 index 6bdbad14..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ro.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ru.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ru.gif deleted file mode 100644 index cf4d30c8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ru.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/rw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/rw.gif deleted file mode 100644 index 02cf0cb1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/rw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sa.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sa.gif deleted file mode 100644 index 4b7632ee..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sb.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sb.gif deleted file mode 100644 index eb8acc08..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sc.gif deleted file mode 100644 index 4324c21f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sd.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sd.gif deleted file mode 100644 index 2d74f622..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/se.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/se.gif deleted file mode 100644 index 9bbcb1fa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/se.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sg.gif deleted file mode 100644 index b81f461e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/si.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/si.gif deleted file mode 100644 index f6afb67d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/si.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sk.gif deleted file mode 100644 index b0c4ab19..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sl.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sl.gif deleted file mode 100644 index 00d59d3b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sm.gif deleted file mode 100644 index 8d9d76b3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sn.gif deleted file mode 100644 index 1a541741..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/so.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/so.gif deleted file mode 100644 index 7f1dba35..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/so.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sr.gif deleted file mode 100644 index de781c13..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/st.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/st.gif deleted file mode 100644 index cd9036fb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/st.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/su.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/su.gif deleted file mode 100644 index 23e162a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/su.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sv.gif deleted file mode 100644 index bef488e2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sy.gif deleted file mode 100644 index a3a53cd4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sz.gif deleted file mode 100644 index b3a20ba5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/sz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/td.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/td.gif deleted file mode 100644 index 3ccc8dff..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/td.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tg.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tg.gif deleted file mode 100644 index 674e68f0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/th.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/th.gif deleted file mode 100644 index 83318c0c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/th.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tj.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tj.gif deleted file mode 100644 index 1f44255c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tm.gif deleted file mode 100644 index a603afd2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tn.gif deleted file mode 100644 index 083238da..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/to.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/to.gif deleted file mode 100644 index 603aa8e3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/to.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tp.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tp.gif deleted file mode 100644 index 40599d56..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tr.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tr.gif deleted file mode 100644 index 2eac7305..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tt.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tt.gif deleted file mode 100644 index f7154195..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tv.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tv.gif deleted file mode 100644 index 9b018e87..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tw.gif deleted file mode 100644 index 57a04829..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tz.gif deleted file mode 100644 index 6d28d408..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/tz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ua.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ua.gif deleted file mode 100644 index bebd6705..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ua.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ug.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ug.gif deleted file mode 100644 index 151e3037..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ug.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uk.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uk.gif deleted file mode 100644 index 4ae2d0f8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/un.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/un.gif deleted file mode 100644 index 135b5281..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/un.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/us.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/us.gif deleted file mode 100644 index 850094ea..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/us.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uy.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uy.gif deleted file mode 100644 index 4d129fc5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uz.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uz.gif deleted file mode 100644 index d9cc88eb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/uz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/va.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/va.gif deleted file mode 100644 index 5db146d6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/va.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vc.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vc.gif deleted file mode 100644 index 6519018d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ve.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ve.gif deleted file mode 100644 index 4abf999b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ve.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vn.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vn.gif deleted file mode 100644 index e7d1e5b9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vu.gif deleted file mode 100644 index f8736a18..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/vu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ws.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ws.gif deleted file mode 100644 index b2bc2f76..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ws.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ya.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ya.gif deleted file mode 100644 index 91536134..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ya.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye.gif deleted file mode 100644 index f183847c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye0.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye0.gif deleted file mode 100644 index b9c28b30..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/ye0.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/yu.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/yu.gif deleted file mode 100644 index c91bf1ef..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/yu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/za.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/za.gif deleted file mode 100644 index 8579793e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/za.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zm.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zm.gif deleted file mode 100644 index fc686bb8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zw.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zw.gif deleted file mode 100644 index 9821c41c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/countries/zw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/expand.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/expand.gif deleted file mode 100644 index 3b0a619d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/expand.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/expandall.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/expandall.gif deleted file mode 100644 index 0205b291..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/expandall.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragment_flag.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragment_flag.gif deleted file mode 100644 index 1c2d14f0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragment_flag.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragmentproject.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragmentproject.gif deleted file mode 100644 index ea885ac5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/fragmentproject.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/resourcebundle.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/resourcebundle.gif deleted file mode 100644 index fe05bad9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/resourcebundle.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning.gif deleted file mode 100644 index 4f41bf02..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning_flag.gif b/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning_flag.gif deleted file mode 100644 index 801a1f81..00000000 Binary files a/org.eclipse.babel.tapiji.tools.rbmanager/icons/warning_flag.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/plugin.xml b/org.eclipse.babel.tapiji.tools.rbmanager/plugin.xml deleted file mode 100644 index 131fa3cc..00000000 --- a/org.eclipse.babel.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.eclipse.babel.tapiji" - class="org.eclipse.ui.navigator.CommonNavigator" - icon="icons/resourcebundle.gif" - id="org.eclipse.babel.tapiji.tools.rbmanager.ResourceBundleExplorer" - name="%view.rbe.name" - 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="%action.filter.label" - state="false" - style="toggle" - toolbarPath="additions" - tooltip="%action.filter.tooltip"> - </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="%action.expand.label" - 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="%navigatorContent.name" - 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="%commonFilter.name"> - </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/pom.xml b/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml deleted file mode 100644 index 083a7b1e..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.tapiji.tools.rbmanager</artifactId> - <packaging>eclipse-plugin</packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file 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 deleted file mode 100644 index 56694650..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Michael Gasser - initial 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"; //$NON-NLS-1$ - private static final String FRAGMENT_FLAG_IMAGE = "fragment_flag.gif"; //$NON-NLS-1$ - public static final String WARNING_IMAGE = "warning.gif"; //$NON-NLS-1$ - public static final String FRAGMENT_PROJECT_IMAGE = "fragmentproject.gif"; //$NON-NLS-1$ - public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif"; //$NON-NLS-1$ - public static final String EXPAND = "expand.gif"; //$NON-NLS-1$ - public static final String DEFAULT_LOCALICON = File.separatorChar - + "countries" + File.separatorChar + "_f.gif"; - public static final String LOCATION_WITHOUT_ICON = File.separatorChar - + "countries" + File.separatorChar + "un.gif"; - - /** - * @return a Image from the folder 'icons' - * @throws URISyntaxException - */ - public static Image getBaseImage(String imageName) { - Image image = imageRegistry.get(imageName); - if (image == null) { - ImageDescriptor descriptor = RBManagerActivator - .getImageDescriptor(imageName); - - if (descriptor.getImageData() != null) { - image = descriptor.createImage(false); - imageRegistry.put(imageName, image); - } - } - - 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 deleted file mode 100644 index 5ff9b3eb..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 522a992a..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index c75044ef..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java +++ /dev/null @@ -1,262 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 (l1 != null && l2 != null && !l2.equals(l1)) { - 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 deleted file mode 100644 index 7671b1c9..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 2e47dac9..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index fe589e91..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 70ab5b2d..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 3cc8e55c..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 7601c78f..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 88c6cddf..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index c415e211..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 5ca05a7b..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 78e7de75..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index a33d985b..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java +++ /dev/null @@ -1,466 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index b883d060..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java +++ /dev/null @@ -1,207 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 6b224116..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 25536452..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 48a99efa..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 50a2dbcc..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 87edcf6b..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java +++ /dev/null @@ -1,232 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 8c06e72b..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java +++ /dev/null @@ -1,281 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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 deleted file mode 100644 index 0f3fc344..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Michael Gasser. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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.eclipse.babel.tapiji.tools.target/.project b/org.eclipse.babel.tapiji.tools.target/.project deleted file mode 100644 index 84c8bf8e..00000000 --- a/org.eclipse.babel.tapiji.tools.target/.project +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.target</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.m2e.core.maven2Builder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.m2e.core.maven2Nature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.target/org.eclipse.babel.tapiji.tools.target.target b/org.eclipse.babel.tapiji.tools.target/org.eclipse.babel.tapiji.tools.target.target deleted file mode 100644 index 03d9c1ef..00000000 --- a/org.eclipse.babel.tapiji.tools.target/org.eclipse.babel.tapiji.tools.target.target +++ /dev/null @@ -1,11 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<?pde version="3.6"?> - -<target name="org.eclipse.babel.tapiji.tools.target" sequenceNumber="0"> -<locations> -<location includeAllPlatforms="false" includeMode="planner" includeSource="true" type="InstallableUnit"> -<unit id="epp.package.java" version="1.4.2.20120213-0813"/> -<repository location="http://download.eclipse.org/releases/indigo"/> -</location> -</locations> -</target> diff --git a/org.eclipse.babel.tapiji.tools.target/pom.xml b/org.eclipse.babel.tapiji.tools.target/pom.xml deleted file mode 100644 index 5528afd2..00000000 --- a/org.eclipse.babel.tapiji.tools.target/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- - -Copyright (c) 2012 Martin Reiterer - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License -v1.0 which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: Martin Reiterer - setup of tycho build for babel tools - ---> - -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipse.babel.tapiji.tools.target</artifactId> - <packaging>eclipse-target-definition </packaging> - - <parent> - <groupId>org.eclipse.babel.plugins</groupId> - <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> - <version>0.0.2-SNAPSHOT</version> - <relativePath>..</relativePath> - </parent> -</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.translator.rbe/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.translator.rbe/META-INF/MANIFEST.MF deleted file mode 100644 index aa318a0c..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -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";resolution:=optional, - org.eclipse.rap.jface;bundle-version="1.5.0";resolution:=optional diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/.project b/org.eclipselabs.tapiji.tools.jsf.feature/.project deleted file mode 100644 index 2fdfb19a..00000000 --- a/org.eclipselabs.tapiji.tools.jsf.feature/.project +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipselabs.tapiji.tools.jsf.feature</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.pde.FeatureBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.FeatureNature</nature> - </natures> -</projectDescription> diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/about.html b/org.eclipselabs.tapiji.tools.jsf.feature/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipselabs.tapiji.tools.jsf.feature/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/build.properties b/org.eclipselabs.tapiji.tools.jsf.feature/build.properties deleted file mode 100644 index 1fe28114..00000000 --- a/org.eclipselabs.tapiji.tools.jsf.feature/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -bin.includes = feature.xml,\ - epl-v10.html -src.includes = epl-v10.html,\ - feature.xml diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html b/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipselabs.tapiji.tools.jsf.feature/epl-v10.html +++ /dev/null @@ -1,261 +0,0 @@ -<?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 (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR -DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS -AGREEMENT.</p> - -<p><b>1. DEFINITIONS</b></p> - -<p>&quot;Contribution&quot; means:</p> - -<p class="list">a) in the case of the initial Contributor, the initial -code and documentation distributed under this Agreement, and</p> -<p class="list">b) in the case of each subsequent Contributor:</p> -<p class="list">i) changes to the Program, and</p> -<p class="list">ii) additions to the Program;</p> -<p class="list">where such changes and/or additions to the Program -originate from and are distributed by that particular Contributor. A -Contribution 'originates' from a Contributor if it was added to the -Program by such Contributor itself or anyone acting on such -Contributor's behalf. Contributions do not include additions to the -Program which: (i) are separate modules of software distributed in -conjunction with the Program under their own license agreement, and (ii) -are not derivative works of the Program.</p> - -<p>&quot;Contributor&quot; means any person or entity that distributes -the Program.</p> - -<p>&quot;Licensed Patents&quot; mean patent claims licensable by a -Contributor which are necessarily infringed by the use or sale of its -Contribution alone or when combined with the Program.</p> - -<p>&quot;Program&quot; means the Contributions distributed in accordance -with this Agreement.</p> - -<p>&quot;Recipient&quot; means anyone who receives the Program under -this Agreement, including all Contributors.</p> - -<p><b>2. GRANT OF RIGHTS</b></p> - -<p class="list">a) Subject to the terms of this Agreement, each -Contributor hereby grants Recipient a non-exclusive, worldwide, -royalty-free copyright license to reproduce, prepare derivative works -of, publicly display, publicly perform, distribute and sublicense the -Contribution of such Contributor, if any, and such derivative works, in -source code and object code form.</p> - -<p class="list">b) Subject to the terms of this Agreement, each -Contributor hereby grants Recipient a non-exclusive, worldwide, -royalty-free patent license under Licensed Patents to make, use, sell, -offer to sell, import and otherwise transfer the Contribution of such -Contributor, if any, in source code and object code form. This patent -license shall apply to the combination of the Contribution and the -Program if, at the time the Contribution is added by the Contributor, -such addition of the Contribution causes such combination to be covered -by the Licensed Patents. The patent license shall not apply to any other -combinations which include the Contribution. No hardware per se is -licensed hereunder.</p> - -<p class="list">c) Recipient understands that although each Contributor -grants the licenses to its Contributions set forth herein, no assurances -are provided by any Contributor that the Program does not infringe the -patent or other intellectual property rights of any other entity. Each -Contributor disclaims any liability to Recipient for claims brought by -any other entity based on infringement of intellectual property rights -or otherwise. As a condition to exercising the rights and licenses -granted hereunder, each Recipient hereby assumes sole responsibility to -secure any other intellectual property rights needed, if any. For -example, if a third party patent license is required to allow Recipient -to distribute the Program, it is Recipient's responsibility to acquire -that license before distributing the Program.</p> - -<p class="list">d) Each Contributor represents that to its knowledge it -has sufficient copyright rights in its Contribution, if any, to grant -the copyright license set forth in this Agreement.</p> - -<p><b>3. REQUIREMENTS</b></p> - -<p>A Contributor may choose to distribute the Program in object code -form under its own license agreement, provided that:</p> - -<p class="list">a) it complies with the terms and conditions of this -Agreement; and</p> - -<p class="list">b) its license agreement:</p> - -<p class="list">i) effectively disclaims on behalf of all Contributors -all warranties and conditions, express and implied, including warranties -or conditions of title and non-infringement, and implied warranties or -conditions of merchantability and fitness for a particular purpose;</p> - -<p class="list">ii) effectively excludes on behalf of all Contributors -all liability for damages, including direct, indirect, special, -incidental and consequential damages, such as lost profits;</p> - -<p class="list">iii) states that any provisions which differ from this -Agreement are offered by that Contributor alone and not by any other -party; and</p> - -<p class="list">iv) states that source code for the Program is available -from such Contributor, and informs licensees how to obtain it in a -reasonable manner on or through a medium customarily used for software -exchange.</p> - -<p>When the Program is made available in source code form:</p> - -<p class="list">a) it must be made available under this Agreement; and</p> - -<p class="list">b) a copy of this Agreement must be included with each -copy of the Program.</p> - -<p>Contributors may not remove or alter any copyright notices contained -within the Program.</p> - -<p>Each Contributor must identify itself as the originator of its -Contribution, if any, in a manner that reasonably allows subsequent -Recipients to identify the originator of the Contribution.</p> - -<p><b>4. COMMERCIAL DISTRIBUTION</b></p> - -<p>Commercial distributors of software may accept certain -responsibilities with respect to end users, business partners and the -like. While this license is intended to facilitate the commercial use of -the Program, the Contributor who includes the Program in a commercial -product offering should do so in a manner which does not create -potential liability for other Contributors. Therefore, if a Contributor -includes the Program in a commercial product offering, such Contributor -(&quot;Commercial Contributor&quot;) hereby agrees to defend and -indemnify every other Contributor (&quot;Indemnified Contributor&quot;) -against any losses, damages and costs (collectively &quot;Losses&quot;) -arising from claims, lawsuits and other legal actions brought by a third -party against the Indemnified Contributor to the extent caused by the -acts or omissions of such Commercial Contributor in connection with its -distribution of the Program in a commercial product offering. The -obligations in this section do not apply to any claims or Losses -relating to any actual or alleged intellectual property infringement. In -order to qualify, an Indemnified Contributor must: a) promptly notify -the Commercial Contributor in writing of such claim, and b) allow the -Commercial Contributor to control, and cooperate with the Commercial -Contributor in, the defense and any related settlement negotiations. The -Indemnified Contributor may participate in any such claim at its own -expense.</p> - -<p>For example, a Contributor might include the Program in a commercial -product offering, Product X. That Contributor is then a Commercial -Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance -claims and warranties are such Commercial Contributor's responsibility -alone. Under this section, the Commercial Contributor would have to -defend claims against the other Contributors related to those -performance claims and warranties, and if a court requires any other -Contributor to pay any damages as a result, the Commercial Contributor -must pay those damages.</p> - -<p><b>5. NO WARRANTY</b></p> - -<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS -PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS -OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, -ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY -OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely -responsible for determining the appropriateness of using and -distributing the Program and assumes all risks associated with its -exercise of rights under this Agreement , including but not limited to -the risks and costs of program errors, compliance with applicable laws, -damage to or loss of data, programs or equipment, and unavailability or -interruption of operations.</p> - -<p><b>6. DISCLAIMER OF LIABILITY</b></p> - -<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT -NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING -WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR -DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED -HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> - -<p><b>7. GENERAL</b></p> - -<p>If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement, and without further action -by the parties hereto, such provision shall be reformed to the minimum -extent necessary to make such provision valid and enforceable.</p> - -<p>If Recipient institutes patent litigation against any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the -Program itself (excluding combinations of the Program with other -software or hardware) infringes such Recipient's patent(s), then such -Recipient's rights granted under Section 2(b) shall terminate as of the -date such litigation is filed.</p> - -<p>All Recipient's rights under this Agreement shall terminate if it -fails to comply with any of the material terms or conditions of this -Agreement and does not cure such failure in a reasonable period of time -after becoming aware of such noncompliance. If all Recipient's rights -under this Agreement terminate, Recipient agrees to cease use and -distribution of the Program as soon as reasonably practicable. However, -Recipient's obligations under this Agreement and any licenses granted by -Recipient relating to the Program shall continue and survive.</p> - -<p>Everyone is permitted to copy and distribute copies of this -Agreement, but in order to avoid inconsistency the Agreement is -copyrighted and may only be modified in the following manner. The -Agreement Steward reserves the right to publish new versions (including -revisions) of this Agreement from time to time. No one other than the -Agreement Steward has the right to modify this Agreement. The Eclipse -Foundation is the initial Agreement Steward. The Eclipse Foundation may -assign the responsibility to serve as the Agreement Steward to a -suitable separate entity. Each new version of the Agreement will be -given a distinguishing version number. The Program (including -Contributions) may always be distributed subject to the version of the -Agreement under which it was received. In addition, after a new version -of the Agreement is published, Contributor may elect to distribute the -Program (including its Contributions) under the new version. Except as -expressly stated in Sections 2(a) and 2(b) above, Recipient receives no -rights or licenses to the intellectual property of any Contributor under -this Agreement, whether expressly, by implication, estoppel or -otherwise. All rights in the Program not expressly granted under this -Agreement are reserved.</p> - -<p>This Agreement is governed by the laws of the State of New York and -the intellectual property laws of the United States of America. No party -to this Agreement will bring a legal action under this Agreement more -than one year after the cause of action arose. Each party waives its -rights to a jury trial in any resulting litigation.</p> - -</body> - -</html> diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml b/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml deleted file mode 100644 index 27b6d5b4..00000000 --- a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml +++ /dev/null @@ -1,134 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<feature - id="org.eclipselabs.tapiji.tools.jsf.feature" - label="JSF Internationalization Feature" - version="0.0.2.qualifier" - provider-name="Vienna University of Technology" - plugin="org.eclipselabs.tapiji.tools.jsf"> - - <description url="http://svn.codespot.com/a/eclipselabs.org/tapiji/update/"> - The TapiJI JSF Internationalization plug-in extends Internationalizaion -support for editing of JSF HTML templates. - </description> - - <copyright url="http://code.google.com/a/eclipselabs.org/p/tapiji/"> - (c) Copyright Stefan Strobl and Martin Reiterer 2011. All rights -reserved. - </copyright> - - <license url="http://www.eclipse.org/legal/epl-v10.html"> - Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT&apos;S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -&quot;Contribution&quot; 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 &apos;originates&apos; from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor&apos;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. - -&quot;Contributor&quot; means any person or entity that distributes the Program. - -&quot;Licensed Patents&quot; mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -&quot;Program&quot; means the Contributions distributed in accordance with this Agreement. - -&quot;Recipient&quot; 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&apos;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 (&quot;Commercial Contributor&quot;) hereby agrees to defend and indemnify every other Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. - -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&apos;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 &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. - -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&apos;s patent(s), then such Recipient&apos;s rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient&apos;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&apos;s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient&apos;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. - </license> - - <requires> - <import plugin="org.eclipse.core.resources" version="3.6.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.jface"/> - <import plugin="org.eclipse.jface.text"/> - <import plugin="org.eclipse.jdt.ui" version="3.6.0" match="greaterOrEqual"/> - <import plugin="org.eclipse.jst.jsf.common" version="1.2.0" match="greaterOrEqual"/> - <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.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"/> - <import plugin="org.eclipse.wst.validation"/> - <import plugin="org.eclipse.wst.xml.core"/> - </requires> - - <plugin - id="org.eclipselabs.tapiji.tools.jsf" - download-size="0" - install-size="0" - version="0.0.2.qualifier" - unpack="false"/> - -</feature> diff --git a/org.eclipselabs.tapiji.tools.jsf/.classpath b/org.eclipselabs.tapiji.tools.jsf/.classpath deleted file mode 100644 index 8a8f1668..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/.classpath +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> diff --git a/org.eclipselabs.tapiji.tools.jsf/.project b/org.eclipselabs.tapiji.tools.jsf/.project deleted file mode 100644 index df955d26..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/.project +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipselabs.tapiji.tools.jsf</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.jsf/.settings/org.eclipse.jdt.core.prefs b/org.eclipselabs.tapiji.tools.jsf/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 405ec907..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Sun Jan 30 11:29:14 CET 2011 -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.tools.jsf/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF deleted file mode 100644 index 0ffb2355..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF +++ /dev/null @@ -1,30 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: JsfBuilderExtension -Bundle-SymbolicName: org.eclipselabs.tapiji.tools.jsf;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.jface, - org.eclipse.jface.text, - org.eclipse.jdt.core;bundle-version="3.6.0", - org.eclipse.jdt.ui;bundle-version="3.6.0", - org.eclipse.jst.jsf.common;bundle-version="1.2.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.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, - org.eclipse.jface.dialogs, - org.eclipse.jface.text, - org.eclipse.swt.graphics, - org.eclipse.swt.widgets, - org.eclipse.ui, - org.eclipse.ui.part, - org.eclipse.ui.wizards, - org.eclipse.wst.validation.internal.core, - org.eclipse.wst.validation.internal.provisional.core, - org.eclipse.wst.xml.core.internal.regions -Bundle-Vendor: Vienna University of Technology diff --git a/org.eclipselabs.tapiji.tools.jsf/about.html b/org.eclipselabs.tapiji.tools.jsf/about.html deleted file mode 100644 index f47dbddb..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/about.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> -<title>About</title> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 5, 2006</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.jsf/build.properties b/org.eclipselabs.tapiji.tools.jsf/build.properties deleted file mode 100644 index 5435750f..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/build.properties +++ /dev/null @@ -1,8 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - epl-v10.html -src.includes = src/,\ - epl-v10.html diff --git a/org.eclipselabs.tapiji.tools.jsf/epl-v10.html b/org.eclipselabs.tapiji.tools.jsf/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/epl-v10.html +++ /dev/null @@ -1,261 +0,0 @@ -<?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 (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR -DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS -AGREEMENT.</p> - -<p><b>1. DEFINITIONS</b></p> - -<p>&quot;Contribution&quot; means:</p> - -<p class="list">a) in the case of the initial Contributor, the initial -code and documentation distributed under this Agreement, and</p> -<p class="list">b) in the case of each subsequent Contributor:</p> -<p class="list">i) changes to the Program, and</p> -<p class="list">ii) additions to the Program;</p> -<p class="list">where such changes and/or additions to the Program -originate from and are distributed by that particular Contributor. A -Contribution 'originates' from a Contributor if it was added to the -Program by such Contributor itself or anyone acting on such -Contributor's behalf. Contributions do not include additions to the -Program which: (i) are separate modules of software distributed in -conjunction with the Program under their own license agreement, and (ii) -are not derivative works of the Program.</p> - -<p>&quot;Contributor&quot; means any person or entity that distributes -the Program.</p> - -<p>&quot;Licensed Patents&quot; mean patent claims licensable by a -Contributor which are necessarily infringed by the use or sale of its -Contribution alone or when combined with the Program.</p> - -<p>&quot;Program&quot; means the Contributions distributed in accordance -with this Agreement.</p> - -<p>&quot;Recipient&quot; means anyone who receives the Program under -this Agreement, including all Contributors.</p> - -<p><b>2. GRANT OF RIGHTS</b></p> - -<p class="list">a) Subject to the terms of this Agreement, each -Contributor hereby grants Recipient a non-exclusive, worldwide, -royalty-free copyright license to reproduce, prepare derivative works -of, publicly display, publicly perform, distribute and sublicense the -Contribution of such Contributor, if any, and such derivative works, in -source code and object code form.</p> - -<p class="list">b) Subject to the terms of this Agreement, each -Contributor hereby grants Recipient a non-exclusive, worldwide, -royalty-free patent license under Licensed Patents to make, use, sell, -offer to sell, import and otherwise transfer the Contribution of such -Contributor, if any, in source code and object code form. This patent -license shall apply to the combination of the Contribution and the -Program if, at the time the Contribution is added by the Contributor, -such addition of the Contribution causes such combination to be covered -by the Licensed Patents. The patent license shall not apply to any other -combinations which include the Contribution. No hardware per se is -licensed hereunder.</p> - -<p class="list">c) Recipient understands that although each Contributor -grants the licenses to its Contributions set forth herein, no assurances -are provided by any Contributor that the Program does not infringe the -patent or other intellectual property rights of any other entity. Each -Contributor disclaims any liability to Recipient for claims brought by -any other entity based on infringement of intellectual property rights -or otherwise. As a condition to exercising the rights and licenses -granted hereunder, each Recipient hereby assumes sole responsibility to -secure any other intellectual property rights needed, if any. For -example, if a third party patent license is required to allow Recipient -to distribute the Program, it is Recipient's responsibility to acquire -that license before distributing the Program.</p> - -<p class="list">d) Each Contributor represents that to its knowledge it -has sufficient copyright rights in its Contribution, if any, to grant -the copyright license set forth in this Agreement.</p> - -<p><b>3. REQUIREMENTS</b></p> - -<p>A Contributor may choose to distribute the Program in object code -form under its own license agreement, provided that:</p> - -<p class="list">a) it complies with the terms and conditions of this -Agreement; and</p> - -<p class="list">b) its license agreement:</p> - -<p class="list">i) effectively disclaims on behalf of all Contributors -all warranties and conditions, express and implied, including warranties -or conditions of title and non-infringement, and implied warranties or -conditions of merchantability and fitness for a particular purpose;</p> - -<p class="list">ii) effectively excludes on behalf of all Contributors -all liability for damages, including direct, indirect, special, -incidental and consequential damages, such as lost profits;</p> - -<p class="list">iii) states that any provisions which differ from this -Agreement are offered by that Contributor alone and not by any other -party; and</p> - -<p class="list">iv) states that source code for the Program is available -from such Contributor, and informs licensees how to obtain it in a -reasonable manner on or through a medium customarily used for software -exchange.</p> - -<p>When the Program is made available in source code form:</p> - -<p class="list">a) it must be made available under this Agreement; and</p> - -<p class="list">b) a copy of this Agreement must be included with each -copy of the Program.</p> - -<p>Contributors may not remove or alter any copyright notices contained -within the Program.</p> - -<p>Each Contributor must identify itself as the originator of its -Contribution, if any, in a manner that reasonably allows subsequent -Recipients to identify the originator of the Contribution.</p> - -<p><b>4. COMMERCIAL DISTRIBUTION</b></p> - -<p>Commercial distributors of software may accept certain -responsibilities with respect to end users, business partners and the -like. While this license is intended to facilitate the commercial use of -the Program, the Contributor who includes the Program in a commercial -product offering should do so in a manner which does not create -potential liability for other Contributors. Therefore, if a Contributor -includes the Program in a commercial product offering, such Contributor -(&quot;Commercial Contributor&quot;) hereby agrees to defend and -indemnify every other Contributor (&quot;Indemnified Contributor&quot;) -against any losses, damages and costs (collectively &quot;Losses&quot;) -arising from claims, lawsuits and other legal actions brought by a third -party against the Indemnified Contributor to the extent caused by the -acts or omissions of such Commercial Contributor in connection with its -distribution of the Program in a commercial product offering. The -obligations in this section do not apply to any claims or Losses -relating to any actual or alleged intellectual property infringement. In -order to qualify, an Indemnified Contributor must: a) promptly notify -the Commercial Contributor in writing of such claim, and b) allow the -Commercial Contributor to control, and cooperate with the Commercial -Contributor in, the defense and any related settlement negotiations. The -Indemnified Contributor may participate in any such claim at its own -expense.</p> - -<p>For example, a Contributor might include the Program in a commercial -product offering, Product X. That Contributor is then a Commercial -Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance -claims and warranties are such Commercial Contributor's responsibility -alone. Under this section, the Commercial Contributor would have to -defend claims against the other Contributors related to those -performance claims and warranties, and if a court requires any other -Contributor to pay any damages as a result, the Commercial Contributor -must pay those damages.</p> - -<p><b>5. NO WARRANTY</b></p> - -<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS -PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS -OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, -ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY -OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely -responsible for determining the appropriateness of using and -distributing the Program and assumes all risks associated with its -exercise of rights under this Agreement , including but not limited to -the risks and costs of program errors, compliance with applicable laws, -damage to or loss of data, programs or equipment, and unavailability or -interruption of operations.</p> - -<p><b>6. DISCLAIMER OF LIABILITY</b></p> - -<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT -NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING -WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR -DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED -HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> - -<p><b>7. GENERAL</b></p> - -<p>If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement, and without further action -by the parties hereto, such provision shall be reformed to the minimum -extent necessary to make such provision valid and enforceable.</p> - -<p>If Recipient institutes patent litigation against any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the -Program itself (excluding combinations of the Program with other -software or hardware) infringes such Recipient's patent(s), then such -Recipient's rights granted under Section 2(b) shall terminate as of the -date such litigation is filed.</p> - -<p>All Recipient's rights under this Agreement shall terminate if it -fails to comply with any of the material terms or conditions of this -Agreement and does not cure such failure in a reasonable period of time -after becoming aware of such noncompliance. If all Recipient's rights -under this Agreement terminate, Recipient agrees to cease use and -distribution of the Program as soon as reasonably practicable. However, -Recipient's obligations under this Agreement and any licenses granted by -Recipient relating to the Program shall continue and survive.</p> - -<p>Everyone is permitted to copy and distribute copies of this -Agreement, but in order to avoid inconsistency the Agreement is -copyrighted and may only be modified in the following manner. The -Agreement Steward reserves the right to publish new versions (including -revisions) of this Agreement from time to time. No one other than the -Agreement Steward has the right to modify this Agreement. The Eclipse -Foundation is the initial Agreement Steward. The Eclipse Foundation may -assign the responsibility to serve as the Agreement Steward to a -suitable separate entity. Each new version of the Agreement will be -given a distinguishing version number. The Program (including -Contributions) may always be distributed subject to the version of the -Agreement under which it was received. In addition, after a new version -of the Agreement is published, Contributor may elect to distribute the -Program (including its Contributions) under the new version. Except as -expressly stated in Sections 2(a) and 2(b) above, Recipient receives no -rights or licenses to the intellectual property of any Contributor under -this Agreement, whether expressly, by implication, estoppel or -otherwise. All rights in the Program not expressly granted under this -Agreement are reserved.</p> - -<p>This Agreement is governed by the laws of the State of New York and -the intellectual property laws of the United States of America. No party -to this Agreement will bring a legal action under this Agreement more -than one year after the cause of action arose. Each party waives its -rights to a jury trial in any resulting litigation.</p> - -</body> - -</html> diff --git a/org.eclipselabs.tapiji.tools.jsf/plugin.xml b/org.eclipselabs.tapiji.tools.jsf/plugin.xml deleted file mode 100644 index 7f6bba11..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/plugin.xml +++ /dev/null @@ -1,49 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?eclipse version="3.4"?> -<plugin> - <extension - point="org.eclipse.wst.sse.ui.editorConfiguration"> - <documentationTextHover - class="ui.JSFELMessageHover" - target="org.eclipse.jst.jsp.SCRIPT.JSP_EL2"> - </documentationTextHover> - <provisionalConfiguration - class="ui.autocompletion.jsf.BundleNameProposal" - target="org.eclipse.jst.jsp.JSP_DIRECTIVE" - type="contentassistprocessor"> - </provisionalConfiguration> - <provisionalConfiguration - class="ui.autocompletion.jsf.MessageCompletionProposal" - target="org.eclipse.jst.jsp.SCRIPT.JSP_EL2" - type="contentassistprocessor"> - </provisionalConfiguration> - </extension> - <extension - point="org.eclipse.ui.ide.markerResolution"> - <markerResolutionGenerator - class="quickfix.JSFViolationResolutionGenerator" - markerType="org.eclipse.jst.jsf.ui.JSPSemanticsValidatorMarker"> - </markerResolutionGenerator> - </extension> - <extension - point="org.eclipse.wst.sse.ui.sourcevalidation"> - <validator - class="validator.JSFInternationalizationValidator" - id="validator.JSFInternationalizationValidator" - scope="total"> - <contentTypeIdentifier - id="org.eclipse.jst.jsp.core.jspsource"> - <partitionType - id="org.eclipse.jst.jsp.JSP_DIRECTIVE"> - </partitionType> - </contentTypeIdentifier> - </validator> - </extension> - <extension - point="org.eclipse.babel.tapiji.tools.core.builderExtension"> - <i18nResourceAuditor - class="auditor.JSFResourceAuditor"> - </i18nResourceAuditor> - </extension> - -</plugin> diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java deleted file mode 100644 index 30eac317..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index 1d6b513b..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java +++ /dev/null @@ -1,466 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index b6998bc9..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index 5e4772d0..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index 6c8e7288..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index 455ac9f3..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index d3204c7f..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index e492212e..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index b0c7d4f6..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java +++ /dev/null @@ -1,161 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index 2eddc8d8..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index 31abb867..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index 2bfbaf76..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index b0791474..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package 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 deleted file mode 100644 index e1a1aff8..00000000 --- a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java +++ /dev/null @@ -1,212 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Matthias Lettmayer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * 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) { - } - -}
232612c800c2583da61b95397141040d3106efda
ReactiveX-RxJava
Incoporate review suggestions.--Splits a compound unit test into to parts.-Uses mockito instead of a bespoke test object.-Removes unused import statements.-Changes the order of the Finally action w.r.t. onComplete/onError.-
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/operators/OperationFinally.java b/rxjava-core/src/main/java/rx/operators/OperationFinally.java index 4474e11936..d90b0572a6 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationFinally.java +++ b/rxjava-core/src/main/java/rx/operators/OperationFinally.java @@ -18,11 +18,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; - +import org.junit.Before; import org.junit.Test; import rx.Observable; @@ -47,9 +43,10 @@ public final class OperationFinally { * @param sequence An observable sequence of elements * @param action An action to be taken when the sequence is complete or throws an exception * @return An observable sequence with the same elements as the input. - * After the last element is consumed (just before {@link Observer#onComplete} is called), - * or when an exception is thrown (just before {@link Observer#onError}), the action will be called. - * @see http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx + * After the last element is consumed (and {@link Observer#onCompleted} has been called), + * or after an exception is thrown (and {@link Observer#onError} has been called), + * the given action will be called. + * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx">MSDN Observable.Finally method</a> */ public static <T> Func1<Observer<T>, Subscription> finally0(final Observable<T> sequence, final Action0 action) { return new Func1<Observer<T>, Subscription>() { @@ -94,14 +91,14 @@ private class FinallyObserver implements Observer<T> { @Override public void onCompleted() { - finalAction.call(); observer.onCompleted(); + finalAction.call(); } @Override public void onError(Exception e) { - finalAction.call(); observer.onError(e); + finalAction.call(); } @Override @@ -112,30 +109,24 @@ public void onNext(T args) { } public static class UnitTest { - private static class TestAction implements Action0 { - public int called = 0; - @Override public void call() { - called++; - } + private Action0 aAction0; + private Observer<String> aObserver; + @Before + public void before() { + aAction0 = mock(Action0.class); + aObserver = mock(Observer.class); + } + private void checkActionCalled(Observable<String> input) { + Observable.create(finally0(input, aAction0)).subscribe(aObserver); + verify(aAction0, times(1)).call(); + } + @Test + public void testFinallyCalledOnComplete() { + checkActionCalled(Observable.toObservable(new String[] {"1", "2", "3"})); } - @Test - public void testFinally() { - final String[] n = {"1", "2", "3"}; - final Observable<String> nums = Observable.toObservable(n); - TestAction action = new TestAction(); - action.called = 0; - Observable<String> fin = Observable.create(finally0(nums, action)); - @SuppressWarnings("unchecked") - Observer<String> aObserver = mock(Observer.class); - fin.subscribe(aObserver); - assertEquals(1, action.called); - - action.called = 0; - Observable<String> error = Observable.<String>error(new RuntimeException("expected")); - fin = Observable.create(finally0(error, action)); - fin.subscribe(aObserver); - assertEquals(1, action.called); + public void testFinallyCalledOnError() { + checkActionCalled(Observable.<String>error(new RuntimeException("expected"))); } } }
f6f9278eefa378e57bf4f2ededee32e266c8f76d
restlet-framework-java
Fixed content negotiation issue in the servlet- extension.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java b/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java index 21de031c59..2a4e443cb0 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java +++ b/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java @@ -55,6 +55,7 @@ import org.restlet.engine.security.SslUtils; import org.restlet.engine.util.Base64; import org.restlet.engine.util.StringUtils; +import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.ReadableRepresentation; import org.restlet.representation.Representation; @@ -154,19 +155,29 @@ public Representation getRequestEntity() { Representation result = null; long contentLength = getContentLength(); - // Create the result representation - InputStream requestStream = getRequestEntityStream(contentLength); - ReadableByteChannel requestChannel = getRequestEntityChannel(contentLength); + boolean chunkedEncoding = HeaderUtils.isChunkedEncoding(getRequestHeaders()); + // In some cases there is an entity without a content-length header + boolean connectionClosed = HeaderUtils.isConnectionClose(getRequestHeaders()); + + // Create the representation + if ((contentLength != Representation.UNKNOWN_SIZE && contentLength != 0) + || chunkedEncoding || connectionClosed) { + // Create the result representation + InputStream requestStream = getRequestEntityStream(contentLength); + ReadableByteChannel requestChannel = getRequestEntityChannel(contentLength); + + if (requestStream != null) { + result = new InputRepresentation(requestStream, null, contentLength); + } else if (requestChannel != null) { + result = new ReadableRepresentation(requestChannel, null, + contentLength); + } - if (requestStream != null) { - result = new InputRepresentation(requestStream, null, contentLength); - } else if (requestChannel != null) { - result = new ReadableRepresentation(requestChannel, null, - contentLength); + result.setSize(contentLength); + } else { + result = new EmptyRepresentation(); } - result.setSize(contentLength); - // Extract some interesting header values for (Parameter header : getRequestHeaders()) { if (header.getName().equalsIgnoreCase(
501a1cbb5d35609dcd97a5ce44ac60739173e479
spring-framework
Refactor from deprecated GenericTypeResolver- calls--Refactor AbstractMessageConverterMethodArgumentResolver and-BridgeMethodResolver to use ResolvableType in preference to deprecated-GenericTypeResolver calls.--Issue: SPR-10980-
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java b/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java index 1027d4dfc9dc..d0cf60aa8388 100644 --- a/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java +++ b/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java @@ -16,14 +16,11 @@ package org.springframework.core; -import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Map; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -44,6 +41,7 @@ * * @author Rob Harrop * @author Juergen Hoeller + * @author Phillip Webb * @since 2.0 */ public abstract class BridgeMethodResolver { @@ -86,6 +84,18 @@ public static Method findBridgedMethod(Method bridgeMethod) { } } + /** + * Returns {@code true} if the supplied '{@code candidateMethod}' can be + * consider a validate candidate for the {@link Method} that is {@link Method#isBridge() bridged} + * by the supplied {@link Method bridge Method}. This method performs inexpensive + * checks and can be used quickly filter for a set of possible matches. + */ + private static boolean isBridgedCandidateFor(Method candidateMethod, Method bridgeMethod) { + return (!candidateMethod.isBridge() && !candidateMethod.equals(bridgeMethod) && + candidateMethod.getName().equals(bridgeMethod.getName()) && + candidateMethod.getParameterTypes().length == bridgeMethod.getParameterTypes().length); + } + /** * Searches for the bridged method in the given candidates. * @param candidateMethods the List of candidate Methods @@ -96,11 +106,10 @@ private static Method searchCandidates(List<Method> candidateMethods, Method bri if (candidateMethods.isEmpty()) { return null; } - Map<TypeVariable, Type> typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass()); Method previousMethod = null; boolean sameSig = true; for (Method candidateMethod : candidateMethods) { - if (isBridgeMethodFor(bridgeMethod, candidateMethod, typeParameterMap)) { + if (isBridgeMethodFor(bridgeMethod, candidateMethod, bridgeMethod.getDeclaringClass())) { return candidateMethod; } else if (previousMethod != null) { @@ -112,28 +121,16 @@ else if (previousMethod != null) { return (sameSig ? candidateMethods.get(0) : null); } - /** - * Returns {@code true} if the supplied '{@code candidateMethod}' can be - * consider a validate candidate for the {@link Method} that is {@link Method#isBridge() bridged} - * by the supplied {@link Method bridge Method}. This method performs inexpensive - * checks and can be used quickly filter for a set of possible matches. - */ - private static boolean isBridgedCandidateFor(Method candidateMethod, Method bridgeMethod) { - return (!candidateMethod.isBridge() && !candidateMethod.equals(bridgeMethod) && - candidateMethod.getName().equals(bridgeMethod.getName()) && - candidateMethod.getParameterTypes().length == bridgeMethod.getParameterTypes().length); - } - /** * Determines whether or not the bridge {@link Method} is the bridge for the * supplied candidate {@link Method}. */ - static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map<TypeVariable, Type> typeVariableMap) { - if (isResolvedTypeMatch(candidateMethod, bridgeMethod, typeVariableMap)) { + static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Class<?> declaringClass) { + if (isResolvedTypeMatch(candidateMethod, bridgeMethod, declaringClass)) { return true; } Method method = findGenericDeclaration(bridgeMethod); - return (method != null && isResolvedTypeMatch(method, candidateMethod, typeVariableMap)); + return (method != null && isResolvedTypeMatch(method, candidateMethod, declaringClass)); } /** @@ -167,34 +164,27 @@ private static Method findGenericDeclaration(Method bridgeMethod) { /** * Returns {@code true} if the {@link Type} signature of both the supplied * {@link Method#getGenericParameterTypes() generic Method} and concrete {@link Method} - * are equal after resolving all {@link TypeVariable TypeVariables} using the supplied - * TypeVariable Map, otherwise returns {@code false}. + * are equal after resolving all types against the declaringType, otherwise + * returns {@code false}. */ private static boolean isResolvedTypeMatch( - Method genericMethod, Method candidateMethod, Map<TypeVariable, Type> typeVariableMap) { - + Method genericMethod, Method candidateMethod, Class<?> declaringClass) { Type[] genericParameters = genericMethod.getGenericParameterTypes(); Class[] candidateParameters = candidateMethod.getParameterTypes(); if (genericParameters.length != candidateParameters.length) { return false; } - for (int i = 0; i < genericParameters.length; i++) { - Type genericParameter = genericParameters[i]; + for (int i = 0; i < candidateParameters.length; i++) { + ResolvableType genericParameter = ResolvableType.forMethodParameter(genericMethod, i, declaringClass); Class candidateParameter = candidateParameters[i]; if (candidateParameter.isArray()) { // An array type: compare the component type. - Type rawType = GenericTypeResolver.getRawType(genericParameter, typeVariableMap); - if (rawType instanceof GenericArrayType) { - if (!candidateParameter.getComponentType().equals( - GenericTypeResolver.resolveType(((GenericArrayType) rawType).getGenericComponentType(), typeVariableMap))) { - return false; - } - break; + if (!candidateParameter.getComponentType().equals(genericParameter.getComponentType().resolve(Object.class))) { + return false; } } // A non-array type: compare the type itself. - Class resolvedParameter = GenericTypeResolver.resolveType(genericParameter, typeVariableMap); - if (!candidateParameter.equals(resolvedParameter)) { + if (!candidateParameter.equals(genericParameter.resolve(Object.class))) { return false; } } diff --git a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java index dbca8b7b5b3f..86ebb9b791e8 100644 --- a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java @@ -31,11 +31,11 @@ import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; -import static org.junit.Assert.*; import org.junit.Test; - import org.springframework.util.ReflectionUtils; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller @@ -99,16 +99,16 @@ public void testFindBridgedMethodInHierarchy() throws Exception { @Test public void testIsBridgeMethodFor() throws Exception { - Map<TypeVariable, Type> typeParameterMap = GenericTypeResolver.getTypeVariableMap(MyBar.class); Method bridged = MyBar.class.getDeclaredMethod("someMethod", String.class, Object.class); Method other = MyBar.class.getDeclaredMethod("someMethod", Integer.class, Object.class); Method bridge = MyBar.class.getDeclaredMethod("someMethod", Object.class, Object.class); - assertTrue("Should be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, bridged, typeParameterMap)); - assertFalse("Should not be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, other, typeParameterMap)); + assertTrue("Should be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, bridged, MyBar.class)); + assertFalse("Should not be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, other, MyBar.class)); } @Test + @Deprecated public void testCreateTypeVariableMap() throws Exception { Map<TypeVariable, Type> typeVariableMap = GenericTypeResolver.getTypeVariableMap(MyBar.class); TypeVariable<?> barT = findTypeVariable(InterBar.class, "T"); @@ -220,14 +220,14 @@ public void testSPR2583() throws Exception { Method otherMethod = MessageBroadcasterImpl.class.getMethod("receive", NewMessageEvent.class); assertFalse(otherMethod.isBridge()); - Map<TypeVariable, Type> typeVariableMap = GenericTypeResolver.getTypeVariableMap(MessageBroadcasterImpl.class); - assertFalse("Match identified incorrectly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, otherMethod, typeVariableMap)); - assertTrue("Match not found correctly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, bridgedMethod, typeVariableMap)); + assertFalse("Match identified incorrectly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, otherMethod, MessageBroadcasterImpl.class)); + assertTrue("Match not found correctly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, bridgedMethod, MessageBroadcasterImpl.class)); assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); } @Test + @Deprecated public void testSPR2454() throws Exception { Map<TypeVariable, Type> typeVariableMap = GenericTypeResolver.getTypeVariableMap(YourHomer.class); TypeVariable<?> variable = findTypeVariable(MyHomer.class, "L"); @@ -768,6 +768,7 @@ public class GenericBroadcasterImpl implements Broadcaster { } + @SuppressWarnings({ "unused", "unchecked" }) public abstract class GenericEventBroadcasterImpl<T extends Event> extends GenericBroadcasterImpl implements EventBroadcaster { @@ -835,6 +836,7 @@ public class ModifiedMessageEvent extends MessageEvent { } + @SuppressWarnings("unchecked") public class MessageBroadcasterImpl extends GenericEventBroadcasterImpl<MessageEvent> implements MessageBroadcaster { @@ -889,6 +891,7 @@ public interface RepositoryRegistry { } + @SuppressWarnings("unchecked") public class SettableRepositoryRegistry<R extends SimpleGenericRepository<?>> implements RepositoryRegistry { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java index 14c74c607713..9874fb38a170 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,20 +18,18 @@ import java.io.IOException; import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.core.GenericTypeResolver; import org.springframework.core.MethodParameter; +import org.springframework.core.ResolvableType; import org.springframework.http.HttpInputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.GenericHttpMessageConverter; @@ -121,8 +119,8 @@ protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, } Class<?> contextClass = methodParam.getDeclaringClass(); - Map<TypeVariable, Type> map = GenericTypeResolver.getTypeVariableMap(contextClass); - Class<T> targetClass = (Class<T>) GenericTypeResolver.resolveType(targetType, map); + Class<T> targetClass = (Class<T>) ResolvableType.forType(targetType, + ResolvableType.forMethodParameter(methodParam)).resolve(); for (HttpMessageConverter<?> converter : this.messageConverters) { if (converter instanceof GenericHttpMessageConverter) {
0b4b9f7ed12a5609c760ca93521d52879ab08413
Vala
Add more default attributes
a
https://github.com/GNOME/vala/
diff --git a/vala/valausedattr.vala b/vala/valausedattr.vala index e5e223817c..0fc5b45645 100644 --- a/vala/valausedattr.vala +++ b/vala/valausedattr.vala @@ -35,8 +35,8 @@ public class Vala.UsedAttr : CodeVisitor { "has_type_id", "instance_pos", "const_cname", "take_value_function", "copy_function", "free_function", "param_spec_function", "has_target", "type_cname", "ref_function", "ref_function_void", "unref_function", "type", "has_construct_function", "returns_floating_reference", "gir_namespace", "gir_version", "construct_function", - "lower_case_cprefix", "simple_generics", "sentinel", "scope", "has_destroy_function", - "has_copy_function", "lower_case_csuffix", "ref_sink_function", "dup_function", "finish_function", + "lower_case_cprefix", "simple_generics", "sentinel", "scope", "has_destroy_function", "ordering", "type_check_function", + "has_copy_function", "lower_case_csuffix", "ref_sink_function", "dup_function", "finish_function", "generic_type_pos", "array_length_type", "array_length", "array_length_cname", "array_length_cexpr", "array_null_terminated", "vfunc_name", "finish_name", "free_function_address_of", "pos", "delegate_target", "delegate_target_cname", "", @@ -47,6 +47,9 @@ public class Vala.UsedAttr : CodeVisitor { "NoReturn", "", "Assert", "", "ErrorBase", "", + "GenericAccessors", "", + "Diagnostics", "", + "NoAccessorMethod", "", "Deprecated", "since", "replacement", "", "IntegerType", "rank", "min", "max", "",
a62eecc95a164415d8f924e1c88e2d144282395d
hbase
HBASE-7923 force unassign can confirm region- online on any RS to get rid of double assignments--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1464232 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java index 08358c3053a1..ea71218f3209 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java @@ -2267,11 +2267,14 @@ public UnassignRegionResponse unassignRegion(RpcController controller, UnassignR return urr; } } - if (force) { - this.assignmentManager.regionOffline(hri); + LOG.debug("Close region " + hri.getRegionNameAsString() + + " on current location if it is online and reassign.force=" + force); + this.assignmentManager.unassign(hri, force); + if (!this.assignmentManager.getRegionStates().isRegionInTransition(hri) + && !this.assignmentManager.getRegionStates().isRegionAssigned(hri)) { + LOG.debug("Region " + hri.getRegionNameAsString() + + " is not online on any region server, reassigning it."); assignRegion(hri); - } else { - this.assignmentManager.unassign(hri, force); } if (cpHost != null) { cpHost.postUnassign(hri, force);
289d1dce9d15fc553188deed2b8ff052b04ac2fb
adangel$pmd
Lots of nice updates: * Colour syntax highlighting for all relevant editors & example viewers. * User-selectable marker shapes and colours, violation decorators in the navigator tree * New AST view and related XPath test editor * Rule search (page form only, non-functional) Disabled Quickfix views until its ready Zapped several nevarious bugs in previous functionality Note: for the time being, violation errors will not appear in the Problems page. There is a conflict between having unique markers and 'standard' error markers that denote inclusion in the error page. Will check out the use of annotations to deal with this... For evaluation: The size and scope of the rule editor is (I believe) outgrowing its placement within its preference page and it needs to be parked within it own view. Besides, tracking all the edits being made to the rules goes beyond what the pref pages can handle (i.e. apply/cancel... which never worked properly for the rules in any case) To that end, I've copied the rule table into its own view for now and left the one in the preference page as is so we can compare & contrast. Only one will remain by the time the best approach is chosen. git-svn-id: https://pmd.svn.sourceforge.net/svnroot/pmd/trunk@7115 51baf565-9d33-0410-a72c-fc3788e3496d
p
https://github.com/adangel/pmd
diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/.classpath b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/.classpath index d4fda0e2e81..741a2898938 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/.classpath +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/.classpath @@ -11,14 +11,7 @@ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> <classpathentry kind="src" path="src"/> <classpathentry kind="src" path="test"/> - <classpathentry kind="lib" path="/home/br/apps/eclipse/plugins/org.eclipse.core.commands_3.5.0.I20090525-2000.jar"/> - <classpathentry kind="lib" path="/home/br/apps/eclipse/plugins/org.eclipse.equinox.common_3.5.1.R35x_v20090807-1100.jar"/> - <classpathentry kind="lib" path="/home/br/apps/eclipse/plugins/org.apache.commons.logging_1.0.4.v200904062259.jar"/> <classpathentry kind="lib" path="lib/xercesImpl-2.6.2.jar"/> <classpathentry kind="con" path="org.eclipse.tptp.platform.instrumentation.ui.ContainerInitializer/Build to Manage Libraries"/> - <classpathentry kind="lib" path="/home/br/apps/eclipse/plugins/org.eclipse.swt_3.5.2.v3557f.jar" sourcepath="/home/br/apps/eclipse/plugins/swt-debug.jar"/> - <classpathentry kind="lib" path="/home/br/apps/eclipse/plugins/org.eclipse.osgi_3.5.2.R35x_v20100126.jar"/> - <classpathentry kind="lib" path="/home/br/apps/eclipse/plugins/org.eclipse.team.core_3.5.1.r35x_20100113-0800.jar"/> - <classpathentry kind="lib" path="/home/br/apps/eclipse/plugins/org.tigris.subversion.subclipse.core_1.6.10.jar"/> <classpathentry kind="output" path="bin"/> </classpath> diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF index b9c5a365153..be8eeb326e6 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %plugin.name Bundle-SymbolicName: net.sourceforge.pmd.eclipse.plugin;singleton:=true -Bundle-Version: 5.0.0.v20100726 +Bundle-Version: 5.0.0.v20100826 Bundle-Activator: net.sourceforge.pmd.eclipse.plugin.PMDPlugin Require-Bundle: org.apache.commons.logging;bundle-version="1.0.4", org.eclipse.core.resources;bundle-version="3.5.0", @@ -11,7 +11,12 @@ Require-Bundle: org.apache.commons.logging;bundle-version="1.0.4", org.eclipse.jface.text;bundle-version="3.5.0", org.eclipse.ui;bundle-version="3.5.0", org.eclipse.ui.ide;bundle-version="3.5.0", - org.eclipse.ui.editors;bundle-version="3.5.0" + org.eclipse.ui.editors;bundle-version="3.5.0", + org.eclipse.team.core;bundle-version="3.5.0", + org.eclipse.search, + org.eclipse.help;bundle-version="3.5.0", + org.eclipse.help.ui;bundle-version="3.5.0", + org.eclipse.help.appserver;bundle-version="3.1.400" Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: J2SE-1.5 Bundle-Vendor: %plugin.provider @@ -36,9 +41,10 @@ Export-Package: net.sourceforge.pmd, net.sourceforge.pmd.eclipse.runtime.properties, net.sourceforge.pmd.eclipse.runtime.writer, net.sourceforge.pmd.eclipse.ui, + net.sourceforge.pmd.eclipse.ui.actions, net.sourceforge.pmd.eclipse.ui.model, - net.sourceforge.pmd.eclipse.ui.nls, net.sourceforge.pmd.eclipse.ui.preferences.br, net.sourceforge.pmd.eclipse.ui.views.actions, net.sourceforge.pmd.util, + org.apache.log4j, rulesets diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties index 83143a2c913..87f3ea1111c 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties @@ -52,7 +52,8 @@ src.includes = icons/,\ about.ini,\ toc.xml,\ welcome.xml,\ - schema/ + schema/,\ + src/ jars.compile.order = pmd-plugin.jar source.pmd-plugin.jar = src/ output.pmd-plugin.jar = bin/ diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP1.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP1.png new file mode 100755 index 00000000000..0703aa63f7b Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP1.png differ diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP2.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP2.png new file mode 100755 index 00000000000..d98b9346871 Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP2.png differ diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP3.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP3.png new file mode 100755 index 00000000000..7452a0babd2 Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP3.png differ diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP4.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP4.png new file mode 100755 index 00000000000..f9bdb9d02df Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP4.png differ diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP5.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP5.png new file mode 100755 index 00000000000..b7a811bfb67 Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP5.png differ diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties index 1414e7475fb..ec6a6ba1823 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties @@ -19,6 +19,7 @@ preference.pmd.label.addcomment = Additional text to be appended to review comme preference.pmd.label.sample = Sample : preference.pmd.tooltip.addcomment = Use MessageFormat substitution rules. {0} is the user name, {1} is the current date. preference.pmd.message.incorrect_format = Incorrect message format +preference.pmd.group.priorities = Priority levels preference.pmd.group.review = Violations review parameters preference.pmd.group.general = General options preference.pmd.label.perspective_on_check = Show PMD perspective when checking code @@ -151,14 +152,16 @@ preference.cpd.title = CPD Configuration Options preference.cpd.tilesize = Minimum Tile Size # View labels + view.outline.default_text = A violation outline is not available view.outline.column_message = Error Message view.outline.column_line = Line view.overview.column_element = Element view.overview.column_vio_total = # Violations -view.overview.column_vio_loc = # Violations/LOC +view.overview.column_vio_loc = # Violations/KLOC view.overview.column_vio_method = # Violations/Method view.overview.column_project = Project + view.dataflow.default_text = A dataflow graph is not available view.dataflow.choose_method = Choose a method: view.dataflow.graph.column_line = Line @@ -174,6 +177,9 @@ view.dataflow.table.column_type.tooltip = Specifies the type of the anomaly, tha view.dataflow.table.column_line = Line(s) view.dataflow.table.column_variable = Variable view.dataflow.table.column_method = Method + +view.ast.default_text = An abstract syntax tree is not available + view.column.message = Message view.column.rule = Rule view.column.class = Class @@ -309,3 +315,10 @@ priority.error = Error priority.warning_high = Warning high priority.warning = Warning priority.information = Information + +priority.column.name = Name +priority.column.value = Value +priority.column.size = Size +priority.column.shape = Shape +priority.column.color = Color +priority.column.description = Description \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties index e7e8ee67b9d..9936701e989 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties @@ -101,7 +101,7 @@ view.outline.column_message = Message view.outline.column_line = Ligne view.overview.column_element = Elément view.overview.column_vio_total = # Violations -view.overview.column_vio_loc = # Violations/LDC +view.overview.column_vio_loc = # Violations/KLDC view.overview.column_vio_method = # Violations/Méthode view.overview.column_project = Projet view.dataflow.default_text = Aucun graphe de flot de données n'est disponible diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml index db789430ed6..e7da19c4309 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml @@ -12,6 +12,7 @@ </toc> </extension> +<!-- original marker <extension id="pmdMarker" name="%marker.pmd" @@ -26,6 +27,92 @@ name="rulename"> </attribute> </extension> +--> + + <extension + id="pmdMarker1" + name="%marker.pmd" + point="org.eclipse.core.resources.markers"> + <super type="org.eclipse.core.resources.textmarker"></super> + <persistent value="true"> </persistent> + <attribute name="rulename"> </attribute> + </extension> + + <extension + id="pmdMarker2" + name="%marker.pmd" + point="org.eclipse.core.resources.markers"> + <super type="org.eclipse.core.resources.textmarker"></super> + <persistent value="true"> </persistent> + <attribute name="rulename"> </attribute> + </extension> + + <extension + id="pmdMarker3" + name="%marker.pmd" + point="org.eclipse.core.resources.markers"> + <super type="org.eclipse.core.resources.textmarker"></super> + <persistent value="true"> </persistent> + <attribute name="rulename"> </attribute> + </extension> + + <extension + id="pmdMarker4" + name="%marker.pmd" + point="org.eclipse.core.resources.markers"> + <super type="org.eclipse.core.resources.textmarker"></super> + <persistent value="true"> </persistent> + <attribute name="rulename"> </attribute> + </extension> + + <extension + id="pmdMarker5" + name="%marker.pmd" + point="org.eclipse.core.resources.markers"> + <super type="org.eclipse.core.resources.textmarker"></super> + <persistent value="true"> </persistent> + <attribute name="rulename"> </attribute> + </extension> + +<extension point="org.eclipse.ui.ide.markerImageProviders"> + <imageprovider + id="PMD.imageProvider1" + icon="icons/markerP1.png" + markertype="net.sourceforge.pmd.eclipse.plugin.pmdMarker1"> + </imageprovider> +</extension> + +<extension point="org.eclipse.ui.ide.markerImageProviders"> + <imageprovider + id="PMD.imageProvider2" + icon="icons/markerP2.png" + markertype="net.sourceforge.pmd.eclipse.plugin.pmdMarker2"> + </imageprovider> +</extension> + +<extension point="org.eclipse.ui.ide.markerImageProviders"> + <imageprovider + id="PMD.imageProvider3" + icon="icons/markerP3.png" + markertype="net.sourceforge.pmd.eclipse.plugin.pmdMarker3"> + </imageprovider> +</extension> + +<extension point="org.eclipse.ui.ide.markerImageProviders"> + <imageprovider + id="PMD.imageProvider4" + icon="icons/markerP4.png" + markertype="net.sourceforge.pmd.eclipse.plugin.pmdMarker4"> + </imageprovider> +</extension> + +<extension point="org.eclipse.ui.ide.markerImageProviders"> + <imageprovider + id="PMD.imageProvider5" + icon="icons/markerP5.png" + markertype="net.sourceforge.pmd.eclipse.plugin.pmdMarker5"> + </imageprovider> +</extension> <extension id="pmdTaskMarker" @@ -402,6 +489,22 @@ icon="icons/icon_cpd.gif" id="net.sourceforge.pmd.eclipse.ui.views.CPDView" name="%view.cpd"/> + <view + allowMultiple="false" + category="net.sourceforge.pmd.eclipse.ui.views" + class="net.sourceforge.pmd.eclipse.ui.views.rules.RuleEditorView" + id="net.sourceforge.pmd.eclipse.plugin.ruleEditorView" + name="Rule Editor" + restorable="true"> + </view> + <view + allowMultiple="false" + category="net.sourceforge.pmd.eclipse.ui.views" + class="net.sourceforge.pmd.eclipse.ui.views.ast.ASTView" + id="net.sourceforge.pmd.eclipse.plugin.astView" + name="XPath Designer" + restorable="true"> + </view> </extension> <extension @@ -438,5 +541,45 @@ </menu> </menuContribution> </extension> + <extension + point="org.eclipse.ui.decorators"> + <decorator + adaptable="true" + class="net.sourceforge.pmd.eclipse.ui.RuleLabelDecorator" + icon="icons/sample_decorator.gif" + id="net.sourceforge.pmd.eclipse.plugin.RuleLabelDecorator" + label="Rule Violation Decorator" + lightweight="true" + location="TOP_LEFT" + state="true"> + <description> + The markers used by PMD to flag projects and files with violations. + </description> + <enablement> + <and> + <objectClass + name="org.eclipse.core.resources.IResource"> + </objectClass> + <or> + <objectClass + name="org.eclipse.core.resources.IProject"> + </objectClass> + <objectClass + name="org.eclipse.core.resources.IFile"> + </objectClass> + </or> + </and> + </enablement> + </decorator> + </extension> + + <extension + point="org.eclipse.search.searchPages"> + <page + class="net.sourceforge.pmd.eclipse.search.RuleSearchPage" + id="net.sourceforge.pmd.eclipse.plugin.page1" + label="Rule search"> + </page> + </extension> </plugin> diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java index 7d565a85ac0..071aa3be09b 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java @@ -1,8 +1,12 @@ package net.sourceforge.pmd.eclipse.plugin; +import java.io.File; import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import net.sourceforge.pmd.RuleSet; @@ -23,6 +27,7 @@ import net.sourceforge.pmd.eclipse.runtime.writer.IAstWriter; import net.sourceforge.pmd.eclipse.runtime.writer.IRuleSetWriter; import net.sourceforge.pmd.eclipse.runtime.writer.impl.WriterFactoryImpl; +import net.sourceforge.pmd.eclipse.ui.RuleLabelDecorator; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; import net.sourceforge.pmd.eclipse.ui.nls.StringTable; @@ -32,9 +37,14 @@ import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.RollingFileAppender; +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.FileLocator; import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; @@ -43,6 +53,7 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IDecoratorManager; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; @@ -52,6 +63,8 @@ */ public class PMDPlugin extends AbstractUIPlugin { + private static File pluginFolder; + private HashMap<RGB, Color> coloursByRGB = new HashMap<RGB, Color>(); public static final String PLUGIN_ID = "net.sourceforge.pmd.eclipse.plugin"; @@ -93,6 +106,22 @@ public static void disposeAll(Collection<Color> colors) { for (Color color : colors) color.dispose(); } + public static File getPluginFolder() { + + if (pluginFolder == null) { + URL url = Platform.getBundle(PLUGIN_ID).getEntry("/"); + try { + url = FileLocator.resolve(url); + } + catch(IOException ex) { + ex.printStackTrace(); + } + pluginFolder = new File(url.getPath()); + } + + return pluginFolder; + } + /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) @@ -369,5 +398,90 @@ private void registerAdditionalRuleSets() { log(IStatus.ERROR, "Error when processing RuleSets extensions", e); } } + + public RuleLabelDecorator ruleLabelDecorator() { + IDecoratorManager mgr = getWorkbench().getDecoratorManager(); + return (RuleLabelDecorator) mgr.getBaseLabelProvider("net.sourceforge.pmd.eclipse.plugin.RuleLabelDecorator"); + } + + public void changedFiles(Collection<IFile> changedFiles) { + + Collection<IResource> withParents = new HashSet<IResource>(changedFiles.size() * 2); + withParents.addAll(changedFiles); + for (IFile file : changedFiles) { + IResource parent = file.getParent(); + while (parent != null) { + withParents.add(parent); + parent = parent.getParent(); + } + } + + changed( withParents ); + } + + public void changed(Collection<IResource> changedResources) { + ruleLabelDecorator().changed(changedResources); + } + + private void addFilesTo(IResource resource, Collection<IResource> allKids) { + + if (resource instanceof IFile) { + allKids.add(resource); + return; + } + + if (resource instanceof IFolder) { + IFolder folder = (IFolder)resource; + IResource[] kids = null; + try { + kids = folder.members(); + } catch (CoreException e) { + e.printStackTrace(); + } + for (IResource irc : kids) { + if (irc instanceof IFile) { + allKids.add(irc); + continue; + } + if (irc instanceof IFolder) { + addFilesTo(irc, allKids); + } + } + + allKids.add(folder); + return; + } + + if (resource instanceof IProject) { + IProject project = (IProject)resource; + IResource[] kids = null; + try { + kids = project.members(); + } catch (CoreException e) { + e.printStackTrace(); + } + for (IResource irc : kids) { + if (irc instanceof IFile) { + allKids.add(irc); + continue; + } + if (irc instanceof IFolder) { + addFilesTo(irc, allKids); + } + } + allKids.add(project); + return; + } + } + + public void removedMarkersIn(IResource resource) { + + Collection<IResource> changes = new ArrayList<IResource>(); + + addFilesTo(resource, changes); + + ruleLabelDecorator().changed(changes); + } + } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java index 0628bb0920a..a84200e2a29 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java @@ -1,9 +1,13 @@ package net.sourceforge.pmd.eclipse.plugin; +import java.util.EnumSet; + import net.sourceforge.pmd.RulePriority; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ShapeDescriptor; +import net.sourceforge.pmd.eclipse.ui.Shape; +import net.sourceforge.pmd.eclipse.ui.ShapeDescriptor; +import net.sourceforge.pmd.eclipse.ui.ShapePainter; import net.sourceforge.pmd.eclipse.ui.views.actions.AbstractPMDAction; -import net.sourceforge.pmd.eclipse.util.Util; +import net.sourceforge.pmd.util.StringUtil; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; @@ -14,35 +18,138 @@ * * @author Brian Remedios */ -public class PriorityDescriptor { +public class PriorityDescriptor implements Cloneable { public final RulePriority priority; public String label; + public String description; public String filterText; public String iconId; public ShapeDescriptor shape; - private static final RGB ProtoTransparentColour = new RGB(1,1,1); // almost black + private static final RGB ProtoTransparentColour = new RGB(1,1,1); // almost full black, unlikely to be used + + private static final char DELIMITER = '_'; + + public static PriorityDescriptor from(String text) { + + String[] values = text.split(Character.toString(DELIMITER)); + if (values.length != 7) return null; + + RGB rgb = rgbFrom(values[5]); + if (rgb == null) return null; + + return new PriorityDescriptor( + RulePriority.valueOf(Integer.parseInt(values[0])), + values[1], + values[2], + values[3], + shapeFrom(values[4]), + rgb, + Integer.parseInt(values[6]) + ); + } + + private static Shape shapeFrom(String id) { + int num = Integer.parseInt(id); + for (Shape shape : EnumSet.allOf(Shape.class)) { + if (shape.id == num) return shape; + } + return null; + } + + private static RGB rgbFrom(String desc) { + String[] clrs = desc.split(","); + if (clrs.length != 3) return null; + return new RGB( + Integer.parseInt(clrs[0]), + Integer.parseInt(clrs[1]), + Integer.parseInt(clrs[2]) + ); + } + + private static void rgbOn(StringBuilder sb, RGB rgb) { + sb.append(rgb.red).append(','); + sb.append(rgb.green).append(','); + sb.append(rgb.blue); + } public PriorityDescriptor(RulePriority thePriority, String theLabelKey, String theFilterTextKey, String theIconId, ShapeDescriptor theShape) { priority = thePriority; label = AbstractPMDAction.getString(theLabelKey); + description = "--"; // TODO filterText = AbstractPMDAction.getString(theFilterTextKey); iconId = theIconId; shape = theShape; } - public PriorityDescriptor(RulePriority thePriority, String theLabelKey, String theFilterTextKey, String theIconId, Util.shape theShape, RGB theColor, int theSize) { + public PriorityDescriptor(RulePriority thePriority, String theLabelKey, String theFilterTextKey, String theIconId, Shape theShape, RGB theColor, int theSize) { this(thePriority, theLabelKey, theFilterTextKey, theIconId, new ShapeDescriptor(theShape, theColor, theSize)); } + private PriorityDescriptor(RulePriority thePriority) { + priority = thePriority; + } + + public String storeString() { + StringBuilder sb = new StringBuilder(); + storeOn(sb); + return sb.toString(); + } + + public boolean equals(Object other) { + + if (this == other) return true; + if (other.getClass() != getClass()) return false; + + PriorityDescriptor otherOne = (PriorityDescriptor)other; + + return priority.equals(otherOne.priority) && + StringUtil.isSame(label, otherOne.label, false, false, false) && + shape.equals(otherOne.shape) && + StringUtil.isSame(description, otherOne.description, false, false, false) && + StringUtil.isSame(filterText, otherOne.filterText, false, false, false) && + StringUtil.isSame(iconId, otherOne.iconId, false, false, false); + } + + public int hashCode() { + return + priority.hashCode() ^ shape.hashCode() ^ + String.valueOf(label).hashCode() ^ + String.valueOf(description).hashCode() ^ + String.valueOf(iconId).hashCode(); + } + + public void storeOn(StringBuilder sb) { + sb.append(priority.getPriority()).append(DELIMITER); + sb.append(label).append(DELIMITER); +// sb.append(description).append(DELIMITER); + sb.append(filterText).append(DELIMITER); + sb.append(iconId).append(DELIMITER); + sb.append(shape.shape.id).append(DELIMITER); + rgbOn(sb, shape.rgbColor); sb.append(DELIMITER); + sb.append(shape.size).append(DELIMITER); + } + public ImageDescriptor getImageDescriptor() { return PMDPlugin.getImageDescriptor(iconId); } + public PriorityDescriptor clone() { + + PriorityDescriptor copy = new PriorityDescriptor(priority); + copy.label = label; + copy.description = description; + copy.filterText = filterText; + copy.iconId = iconId; + copy.shape = shape.clone(); + + return copy; + } + public Image getImage(Display display) { - return Util.newDrawnImage( + return ShapePainter.newDrawnImage( display, shape.size, shape.size, @@ -51,4 +158,29 @@ public Image getImage(Display display) { shape.rgbColor //fillColour ); } + + public Image getImage(Display display, int maxDimension) { + + return ShapePainter.newDrawnImage( + display, + Math.min(shape.size, maxDimension), + Math.min(shape.size, maxDimension), + shape.shape, + ProtoTransparentColour, + shape.rgbColor //fillColour + ); + } + + public String toString() { + + StringBuilder sb = new StringBuilder(); + sb.append("RuleDescriptor: "); + sb.append(priority).append(", "); + sb.append(label).append(", "); + sb.append(description).append(", "); + sb.append(filterText).append(", "); + sb.append(iconId).append(", "); + sb.append(shape); + return sb.toString(); + } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java index 4bf1bf9c715..b50f339b03a 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java @@ -1,20 +1,31 @@ package net.sourceforge.pmd.eclipse.plugin; +import java.net.MalformedURLException; +import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; +import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import net.sourceforge.pmd.RulePriority; -import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; +import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; +import net.sourceforge.pmd.eclipse.ui.Shape; +import net.sourceforge.pmd.eclipse.ui.ShapeDescriptor; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; import net.sourceforge.pmd.eclipse.ui.nls.StringTable; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ShapeDescriptor; -import net.sourceforge.pmd.eclipse.util.Util; +import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityDescriptorCache; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; /** * @@ -27,19 +38,35 @@ public class UISettings { private static Map<Object, ShapeDescriptor> shapesByPriority; private static Map<Integer, RulePriority> prioritiesByIntValue; + private static final int MAX_MARKER_DIMENSION = 9; + private static final Map<RulePriority, PriorityDescriptor> uiDescriptorsByPriority = new HashMap<RulePriority, PriorityDescriptor>(5); + + + public static void reloadPriorities() { + uiDescriptorsByPriority.clear(); + uiDescriptorsByPriority(); // cause a reload + } - static { - uiDescriptorsByPriority.put(RulePriority.LOW, new PriorityDescriptor(RulePriority.LOW, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_1, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_1, PMDUiConstants.ICON_BUTTON_PRIO1, Util.shape.triangleSouthEast, new RGB( 0,0,255), 13) ); // blue - uiDescriptorsByPriority.put(RulePriority.MEDIUM_LOW, new PriorityDescriptor(RulePriority.MEDIUM_LOW, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_2, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_2, PMDUiConstants.ICON_BUTTON_PRIO2, Util.shape.triangleDown, new RGB( 0,255,0), 13) ); // green - uiDescriptorsByPriority.put(RulePriority.MEDIUM, new PriorityDescriptor(RulePriority.MEDIUM, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_3, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_3, PMDUiConstants.ICON_BUTTON_PRIO3, Util.shape.triangleUp, new RGB( 255,255,0), 13) ); // yellow - uiDescriptorsByPriority.put(RulePriority.MEDIUM_HIGH, new PriorityDescriptor(RulePriority.MEDIUM_HIGH,StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_4, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_4, PMDUiConstants.ICON_BUTTON_PRIO4, Util.shape.triangleNorthEast, new RGB( 255,0,255), 13) ); // purple - uiDescriptorsByPriority.put(RulePriority.HIGH, new PriorityDescriptor(RulePriority.HIGH, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_5, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_5, PMDUiConstants.ICON_BUTTON_PRIO5, Util.shape.diamond, new RGB( 255,0,0), 13) ); // red + private static Map<RulePriority, PriorityDescriptor> uiDescriptorsByPriority() { + + if (uiDescriptorsByPriority.isEmpty()) { + IPreferences preferences = PMDPlugin.getDefault().getPreferencesManager().loadPreferences(); + for (RulePriority rp : currentPriorities(true)) { + uiDescriptorsByPriority.put(rp, preferences.getPriorityDescriptor(rp)); + } + } + + return uiDescriptorsByPriority; + } + + public static Shape[] allShapes() { + return new Shape[] { Shape.circle, Shape.star, Shape.domeLeft, Shape.domeRight, Shape.diamond, Shape.square, Shape.roundedRect, Shape.minus, Shape.pipe, Shape.plus, Shape.triangleUp, Shape.triangleDown, Shape.triangleRight, Shape.triangleLeft, Shape.triangleNorthEast, Shape.triangleSouthEast, Shape.triangleSouthWest, Shape.triangleNorthWest }; } public static RulePriority[] currentPriorities(boolean sortAscending) { - RulePriority[] priorities = uiDescriptorsByPriority.keySet().toArray(new RulePriority[uiDescriptorsByPriority.size()]); + RulePriority[] priorities = RulePriority.values(); Arrays.sort(priorities, new Comparator<RulePriority>() { public int compare(RulePriority rpA, RulePriority rbB) { @@ -47,18 +74,89 @@ public int compare(RulePriority rpA, RulePriority rbB) { } }); return priorities; - } + } + + public static Map<Shape, ShapeDescriptor> shapeSet(RGB color, int size) { + + Map<Shape, ShapeDescriptor> shapes = new HashMap<Shape, ShapeDescriptor>(); + + for(Shape shape : EnumSet.allOf(Shape.class)) { + shapes.put(shape, new ShapeDescriptor(shape, color, size)); + } + + return shapes; + } + + public static String markerFilenameFor(RulePriority priority) { + String fileDir = PMDPlugin.getPluginFolder().getAbsolutePath(); + return fileDir + "/" + relativeMarkerFilenameFor(priority); + } + + public static String relativeMarkerFilenameFor(RulePriority priority) { + return "icons/markerP" + priority.getPriority() + ".png"; + } + + private static ImageDescriptor getImageDescriptor(final String fileName) { + + URL installURL = PMDPlugin.getDefault().getBundle().getEntry("/"); + try { + URL url = new URL(installURL, fileName); + return ImageDescriptor.createFromURL(url); + } + catch (MalformedURLException mue) { + mue.printStackTrace(); + return null; + } + } + + public static ImageDescriptor markerDescriptorFor(RulePriority priority) { + String path = relativeMarkerFilenameFor(priority); + return getImageDescriptor(path); + } + + public static Map<Integer, ImageDescriptor> markerImgDescriptorsByPriority() { + + RulePriority[] priorities = currentPriorities(true); + Map<Integer, ImageDescriptor> overlaysByPriority = new HashMap<Integer, ImageDescriptor>(priorities.length); + for (RulePriority priority : priorities) { + overlaysByPriority.put( + priority.getPriority(), + markerDescriptorFor(priority) + ); + } + return overlaysByPriority; + } + + public static void createRuleMarkerIcons(Display display) { + + ImageLoader loader = new ImageLoader(); + + PriorityDescriptorCache pdc = PriorityDescriptorCache.instance; + + for (RulePriority priority : currentPriorities(true)) { + Image image = pdc.descriptorFor(priority).getImage(display, MAX_MARKER_DIMENSION); + loader.data = new ImageData[] { image.getImageData() }; + String fullPath = markerFilenameFor( priority ); + loader.save(fullPath, SWT.IMAGE_PNG); + + image.dispose(); + } + } + + public static String descriptionFor(RulePriority priority) { + return descriptorFor(priority).description; + } public static PriorityDescriptor descriptorFor(RulePriority priority) { - return uiDescriptorsByPriority.get(priority); + return uiDescriptorsByPriority().get(priority); } public static Map<Object, ShapeDescriptor> shapesByPriority() { if (shapesByPriority != null) return shapesByPriority; - Map<Object, ShapeDescriptor> shapesByPriority = new HashMap<Object, ShapeDescriptor>(uiDescriptorsByPriority.size()); - for (Map.Entry<RulePriority, PriorityDescriptor> entry : uiDescriptorsByPriority.entrySet()) { + Map<Object, ShapeDescriptor> shapesByPriority = new HashMap<Object, ShapeDescriptor>(uiDescriptorsByPriority().size()); + for (Map.Entry<RulePriority, PriorityDescriptor> entry : uiDescriptorsByPriority().entrySet()) { shapesByPriority.put(entry.getKey(), entry.getValue().shape); } @@ -68,8 +166,8 @@ public static Map<Object, ShapeDescriptor> shapesByPriority() { public static RulePriority priorityFor(int value) { if (prioritiesByIntValue == null) { - prioritiesByIntValue = new HashMap<Integer, RulePriority>(uiDescriptorsByPriority.size()); - for (Map.Entry<RulePriority, PriorityDescriptor> entry : uiDescriptorsByPriority.entrySet()) { + prioritiesByIntValue = new HashMap<Integer, RulePriority>(uiDescriptorsByPriority().size()); + for (Map.Entry<RulePriority, PriorityDescriptor> entry : uiDescriptorsByPriority().entrySet()) { prioritiesByIntValue.put(entry.getKey().getPriority(), entry.getKey()); } } @@ -97,8 +195,8 @@ public static String[] getPriorityLabels() { public static List<Integer> getPriorityIntValues() { - List<Integer> values = new ArrayList<Integer>(uiDescriptorsByPriority.size()); - for (RulePriority priority : uiDescriptorsByPriority.keySet()) { + List<Integer> values = new ArrayList<Integer>(); + for (RulePriority priority : RulePriority.values()) { values.add(priority.getPriority()); } return values; diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java index ed3d21a0617..0ace889df05 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java @@ -12,10 +12,18 @@ */ public class PMDRuntimeConstants { - public static final String PMD_MARKER = PMDPlugin.PLUGIN_ID + ".pmdMarker"; + public static final String PMD_MARKER = PMDPlugin.PLUGIN_ID + ".pmdMarker"; // obsolete + + public static final String PMD_MARKER_1 = PMDPlugin.PLUGIN_ID + ".pmdMarker1"; + public static final String PMD_MARKER_2 = PMDPlugin.PLUGIN_ID + ".pmdMarker2"; + public static final String PMD_MARKER_3 = PMDPlugin.PLUGIN_ID + ".pmdMarker3"; + public static final String PMD_MARKER_4 = PMDPlugin.PLUGIN_ID + ".pmdMarker4"; + public static final String PMD_MARKER_5 = PMDPlugin.PLUGIN_ID + ".pmdMarker5"; + public static final String PMD_DFA_MARKER = PMDPlugin.PLUGIN_ID + ".pmdDFAMarker"; public static final String PMD_TASKMARKER = PMDPlugin.PLUGIN_ID + ".pmdTaskMarker"; - public static final String[] ALL_MARKER_TYPES = new String[] { PMD_MARKER, PMD_DFA_MARKER, PMD_TASKMARKER }; + public static final String[] RULE_MARKER_TYPES = new String[] { PMD_MARKER, PMD_MARKER_1, PMD_MARKER_2, PMD_MARKER_3, PMD_MARKER_4, PMD_MARKER_5 }; + public static final String[] ALL_MARKER_TYPES = new String[] { PMD_MARKER, PMD_DFA_MARKER, PMD_TASKMARKER, PMD_MARKER_1, PMD_MARKER_2, PMD_MARKER_3, PMD_MARKER_4, PMD_MARKER_5 }; public static final IntegerProperty MAX_VIOLATIONS_DESCRIPTOR = new IntegerProperty("maxviolations", "Max allowable violations", 1, Integer.MAX_VALUE-1, 1000, 0f); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java index 786d37d065e..17af8e1dc48 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java @@ -1,8 +1,10 @@ package net.sourceforge.pmd.eclipse.runtime.builder; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import net.sourceforge.pmd.Rule; @@ -10,12 +12,18 @@ import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; +import net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord; +import net.sourceforge.pmd.eclipse.ui.model.FileRecord; +import net.sourceforge.pmd.eclipse.ui.model.MarkerRecord; +import net.sourceforge.pmd.eclipse.ui.model.RootRecord; import net.sourceforge.pmd.util.StringUtil; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IMarkerDelta; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; @@ -28,6 +36,8 @@ public class MarkerUtil { public static final IMarker[] EMPTY_MARKERS = new IMarker[0]; + private static Map<String, Rule> rulesByName; + private MarkerUtil() { } public static boolean hasAnyRuleMarkers(IResource resource) throws CoreException { @@ -42,15 +52,17 @@ public boolean visit(IResource resource) { if (resource instanceof IFile) { - IMarker[] ruleMarkers = null; - try { - ruleMarkers = resource.findMarkers(PMDRuntimeConstants.PMD_MARKER, true, IResource.DEPTH_INFINITE); - } catch (CoreException ex) { - // what do to? - } - if (ruleMarkers.length > 0) { - foundOne[0] = true; - return false; + for (String markerType : PMDRuntimeConstants.RULE_MARKER_TYPES) { + IMarker[] ruleMarkers = null; + try { + ruleMarkers = resource.findMarkers(markerType, true, IResource.DEPTH_INFINITE); + } catch (CoreException ex) { + // what do to? + } + if (ruleMarkers.length > 0) { + foundOne[0] = true; + return false; + } } } @@ -92,7 +104,7 @@ public static String ruleNameFor(IMarker marker) { } public static int rulePriorityFor(IMarker marker) throws CoreException { - return ((Integer)marker.getAttribute(PMDUiConstants.KEY_MARKERATT_PRIORITY)).intValue(); + return (Integer)marker.getAttribute(PMDUiConstants.KEY_MARKERATT_PRIORITY); } public static int deleteViolationsOf(String ruleName, IResource resource) { @@ -120,6 +132,17 @@ public static int deleteViolationsOf(String ruleName, IResource resource) { } } + public static List<IMarkerDelta> markerDeltasIn(IResourceChangeEvent event) { + + List<IMarkerDelta> deltas = new ArrayList<IMarkerDelta>(); + for (String markerType : PMDRuntimeConstants.RULE_MARKER_TYPES) { + IMarkerDelta[] deltaArray = event.findMarkerDeltas(markerType, true); + for (IMarkerDelta delta : deltaArray) deltas.add(delta); + } + + return deltas; + } + public static List<Rule> rulesFor(IMarker[] markers) { List<Rule> rules = new ArrayList<Rule>(markers.length); @@ -165,6 +188,7 @@ public static void deleteMarkersIn(IResource resource, String[] markerTypes) thr for (String markerType : markerTypes) { resource.deleteMarkers(markerType, true, IResource.DEPTH_INFINITE); } + PMDPlugin.getDefault().removedMarkersIn(resource); } public static IMarker[] findAllMarkers(IResource resource) throws CoreException { @@ -189,4 +213,61 @@ public static IMarker[] findMarkers(IResource resource, String[] markerTypes) th return markerList.toArray(markerArray); } + public static Set<Integer> priorityRangeOf(IResource resource, String[] markerTypes, int sizeLimit) throws CoreException { + + Set<Integer> priorityLevels = new HashSet<Integer>(sizeLimit); + + for (String markerType : markerTypes) { + for (IMarker marker : resource.findMarkers(markerType, true, IResource.DEPTH_INFINITE)) { + priorityLevels.add( rulePriorityFor(marker) ); + if (priorityLevels.size() == sizeLimit) return priorityLevels; + } + } + + return priorityLevels; + } + + + private static void gatherRuleNames() { + + rulesByName = new HashMap<String, Rule>(); + Set<RuleSet> ruleSets = PMDPlugin.getDefault().getRuleSetManager().getRegisteredRuleSets(); + for (RuleSet rs : ruleSets) { + for (Rule rule : rs.getRules()) { + rulesByName.put(rule.getName(), rule); + } + } + } + + private static Rule ruleFrom(IMarker marker) { + String ruleName = marker.getAttribute(PMDRuntimeConstants.KEY_MARKERATT_RULENAME, ""); + if (StringUtil.isEmpty(ruleName)) return null; //printValues(marker); + return rulesByName.get(ruleName); + } + + public static Set<IFile> allMarkedFiles(RootRecord root) { + + gatherRuleNames(); + + Set<IFile> files = new HashSet<IFile>(); + + for (AbstractPMDRecord projectRecord : root.getChildren()) { + for (AbstractPMDRecord packageRecord : projectRecord.getChildren()) { + for (AbstractPMDRecord fileRecord : packageRecord.getChildren()) { + ((FileRecord)fileRecord).updateChildren(); + for (AbstractPMDRecord mRecord : fileRecord.getChildren()) { + MarkerRecord markerRecord = (MarkerRecord) mRecord; + for (IMarker marker : markerRecord.findMarkers()) { + Rule rule = ruleFrom(marker); + if (rule == null) continue; + files.add((IFile)fileRecord.getResource()); + break; + } + } + } + } + } + + return files; + } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java index b9c8f873f85..62bf20c54d8 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java @@ -230,17 +230,17 @@ public void setProjectProperties(IProjectProperties projectProperties) { * the resource to process */ protected final void reviewResource(final IResource resource) { - final IFile file = (IFile) resource.getAdapter(IFile.class); + IFile file = (IFile) resource.getAdapter(IFile.class); if (file != null && file.getFileExtension() != null) { try { - boolean included = this.projectProperties.isIncludeDerivedFiles() || !this.projectProperties.isIncludeDerivedFiles() && !file.isDerived(); - log.debug("Derived files included: " + this.projectProperties.isIncludeDerivedFiles()); + boolean included = projectProperties.isIncludeDerivedFiles() || !projectProperties.isIncludeDerivedFiles() && !file.isDerived(); + log.debug("Derived files included: " + projectProperties.isIncludeDerivedFiles()); log.debug("file " + file.getName() + " is derived: " + file.isDerived()); log.debug("file checked: " + included); final File sourceCodeFile = file.getRawLocation().toFile(); - if (getPmdEngine().applies(sourceCodeFile, getRuleSet()) && isFileInWorkingSet(file) && (this.projectProperties.isIncludeDerivedFiles() || !this.projectProperties.isIncludeDerivedFiles() && !file.isDerived())) { + if (getPmdEngine().applies(sourceCodeFile, getRuleSet()) && isFileInWorkingSet(file) && (projectProperties.isIncludeDerivedFiles() || !this.projectProperties.isIncludeDerivedFiles() && !file.isDerived())) { subTask("PMD checking: " + file.getName()); Timer timer = new Timer(); @@ -308,7 +308,7 @@ private boolean isFileInWorkingSet(final IFile file) throws PropertiesException * Update markers list for the specified file * * @param file - * the file for which markes are to be updated + * the file for which markers are to be updated * @param context * a PMD context * @param fTask @@ -324,6 +324,20 @@ private int maxAllowableViolationsFor(Rule rule) { PMDRuntimeConstants.MAX_VIOLATIONS_DESCRIPTOR.defaultValue(); } + public static String markerTypeFor(RuleViolation violation) { + + int priorityId = violation.getRule().getPriority().getPriority(); + + switch (priorityId) { + case 1: return PMDRuntimeConstants.PMD_MARKER_1; + case 2: return PMDRuntimeConstants.PMD_MARKER_2; + case 3: return PMDRuntimeConstants.PMD_MARKER_3; + case 4: return PMDRuntimeConstants.PMD_MARKER_4; + case 5: return PMDRuntimeConstants.PMD_MARKER_5; + default: return PMDRuntimeConstants.PMD_MARKER; + } + } + private void updateMarkers(final IFile file, final RuleContext context, final boolean fTask, final Map<IFile, Set<MarkerInfo>> accumulator) throws CoreException, PropertiesException { final Set<MarkerInfo> markerSet = new HashSet<MarkerInfo>(); @@ -336,7 +350,7 @@ private void updateMarkers(final IFile file, final RuleContext context, final bo Rule rule = null; while (iter.hasNext()) { - final RuleViolation violation = iter.next(); + RuleViolation violation = iter.next(); rule = violation.getRule(); review.ruleName = rule.getName(); review.lineNumber = violation.getBeginLine(); @@ -354,8 +368,8 @@ private void updateMarkers(final IFile file, final RuleContext context, final bo if (count.intValue() < maxViolations) { // Ryan Gustafson 02/16/2008 - Always use PMD_MARKER, as people get confused as to why PMD problems don't always show up on Problems view like they do when you do build. - // markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER : PMDRuntimeConstants.PMD_MARKER)); - markerSet.add(getMarkerInfo(violation, PMDRuntimeConstants.PMD_MARKER)); + // markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER : PMDRuntimeConstants.PMD_MARKER)); + markerSet.add(getMarkerInfo(violation, markerTypeFor(violation))); /* if (isDfaEnabled && violation.getRule().usesDFA()) { markerSet.add(getMarkerInfo(violation, PMDRuntimeConstants.PMD_DFA_MARKER)); @@ -518,8 +532,8 @@ private class Review { public boolean equals(final Object obj) { boolean result = false; if (obj instanceof Review) { - final Review reviewObj = (Review) obj; - result = this.ruleName.equals(reviewObj.ruleName) && this.lineNumber == reviewObj.lineNumber; + Review reviewObj = (Review) obj; + result = ruleName.equals(reviewObj.ruleName) && lineNumber == reviewObj.lineNumber; } return result; } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java index 17697b5bf88..c2bd1ee1cf6 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java @@ -36,6 +36,7 @@ package net.sourceforge.pmd.eclipse.runtime.cmd; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -47,7 +48,6 @@ import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; -import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; import net.sourceforge.pmd.eclipse.runtime.properties.IProjectProperties; import net.sourceforge.pmd.eclipse.runtime.properties.PropertiesException; @@ -64,6 +64,7 @@ import org.eclipse.core.resources.IResourceRuleFactory; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; @@ -90,8 +91,8 @@ public class ReviewCodeCmd extends AbstractDefaultCommand { final private List<ISchedulingRule> resources = new ArrayList<ISchedulingRule>(); private IResourceDelta resourceDelta; private Map<IFile, Set<MarkerInfo>> markersByFile = new HashMap<IFile, Set<MarkerInfo>>(); - private boolean taskMarker = false; - private boolean openPmdPerspective = false; + private boolean taskMarker; + private boolean openPmdPerspective; private int ruleCount; private int fileCount; private long pmdDuration; @@ -107,11 +108,15 @@ public class ReviewCodeCmd extends AbstractDefaultCommand { public ReviewCodeCmd() { super("ReviewCode", "Run PMD on a list of workbench resources"); - this.setOutputProperties(true); - this.setReadOnly(true); - this.setTerminated(false); + setOutputProperties(true); + setReadOnly(true); + setTerminated(false); } + public Set<IFile> markedFiles() { + return markersByFile.keySet(); + } + /** * @see name.herlin.command.AbstractProcessableCommand#execute() */ @@ -119,9 +124,9 @@ public ReviewCodeCmd() { public void execute() throws CommandException { log.info("ReviewCode command starting."); try { - this.fileCount = 0; - this.ruleCount = 0; - this.pmdDuration = 0; + fileCount = 0; + ruleCount = 0; + pmdDuration = 0; beginTask("PMD checking...", getStepCount()); @@ -133,7 +138,7 @@ public void execute() throws CommandException { } // Appliquer les marqueurs - final IWorkspaceRunnable action = new IWorkspaceRunnable() { + IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { applyMarkers(); } @@ -143,7 +148,7 @@ public void run(IProgressMonitor monitor) throws CoreException { workspace.run(action, getschedulingRule(), IWorkspace.AVOID_UPDATE, getMonitor()); // Switch to the PMD perspective if required - if (this.openPmdPerspective) { + if (openPmdPerspective) { Display.getDefault().asyncExec(new Runnable() { public void run() { switchToPmdPerspective(); @@ -174,13 +179,15 @@ public void run() { logInfo("Review code command terminated. " + ruleCount + " rules were executed against " + fileCount + " files. PMD was not executed."); } } + + PMDPlugin.getDefault().changedFiles( markedFiles() ); } /** * @return Returns the file markers */ public Map<IFile, Set<MarkerInfo>> getMarkers() { - return this.markersByFile; + return markersByFile; } /** @@ -301,11 +308,11 @@ private void processResource(IResource resource) throws CommandException { log.debug("Visiting resource " + resource.getName() + " : " + getStepCount()); final ResourceVisitor visitor = new ResourceVisitor(); - visitor.setMonitor(this.getMonitor()); + visitor.setMonitor(getMonitor()); visitor.setRuleSet(ruleSet); visitor.setPmdEngine(pmdEngine); - visitor.setAccumulator(this.markersByFile); - visitor.setUseTaskMarker(this.taskMarker); + visitor.setAccumulator(markersByFile); + visitor.setUseTaskMarker(taskMarker); visitor.setProjectProperties(properties); resource.accept(visitor); @@ -337,6 +344,7 @@ private void processProject(IProject project) throws CommandException { final IJavaProject javaProject = JavaCore.create(project); final IClasspathEntry[] entries = javaProject.getRawClasspath(); + final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (IClasspathEntry entrie : entries) { if (entrie.getEntryKind() == IClasspathEntry.CPE_SOURCE) { @@ -346,9 +354,9 @@ private void processProject(IProject project) throws CommandException { // to know if the entry is a folder or a project ! IContainer sourceContainer = null; try { - sourceContainer = ResourcesPlugin.getWorkspace().getRoot().getFolder(entrie.getPath()); + sourceContainer = root.getFolder(entrie.getPath()); } catch (IllegalArgumentException e) { - sourceContainer = ResourcesPlugin.getWorkspace().getRoot().getProject(entrie.getPath().toString()); + sourceContainer = root.getProject(entrie.getPath().toString()); } if (sourceContainer == null) { log.warn("Source container " + entrie.getPath() + " for project " + project.getName() + " is not valid"); @@ -384,27 +392,27 @@ private RuleSet filteredRuleSet(IProjectProperties properties) throws CommandExc */ private void processResourceDelta() throws CommandException { try { - final IProject project = this.resourceDelta.getResource().getProject(); + final IProject project = resourceDelta.getResource().getProject(); final IProjectProperties properties = PMDPlugin.getDefault().loadProjectProperties(project); - final RuleSet ruleSet = filteredRuleSet(properties); //properties.getProjectRuleSet(); + RuleSet ruleSet = filteredRuleSet(properties); //properties.getProjectRuleSet(); - final PMDEngine pmdEngine = getPmdEngineForProject(project); - this.setStepCount(countDeltaElement(this.resourceDelta)); + PMDEngine pmdEngine = getPmdEngineForProject(project); + setStepCount(countDeltaElement(resourceDelta)); log.debug("Visit of resource delta : " + getStepCount()); - final DeltaVisitor visitor = new DeltaVisitor(); - visitor.setMonitor(this.getMonitor()); + DeltaVisitor visitor = new DeltaVisitor(); + visitor.setMonitor(getMonitor()); visitor.setRuleSet(ruleSet); visitor.setPmdEngine(pmdEngine); - visitor.setAccumulator(this.markersByFile); - visitor.setUseTaskMarker(this.taskMarker); + visitor.setAccumulator(markersByFile); + visitor.setUseTaskMarker(taskMarker); visitor.setProjectProperties(properties); - this.resourceDelta.accept(visitor); + resourceDelta.accept(visitor); - this.ruleCount = ruleSet.getRules().size(); - this.fileCount += visitor.getProcessedFilesCount(); - this.pmdDuration += visitor.getActualPmdDuration(); + ruleCount = ruleSet.getRules().size(); + fileCount += visitor.getProcessedFilesCount(); + pmdDuration += visitor.getActualPmdDuration(); } catch (PropertiesException e) { throw new CommandException(e); @@ -423,36 +431,32 @@ private void applyMarkers() { final Timer timer = new Timer(); String currentFile = ""; // for logging + + beginTask("PMD Applying markers", markersByFile.size()); + try { - final Set<IFile> fileSet = markersByFile.keySet(); - final Iterator<IFile> i = fileSet.iterator(); - - beginTask("PMD Applying markers", fileSet.size()); - - while (i.hasNext() && !isCanceled()) { - final IFile file = i.next(); + for (IFile file : markersByFile.keySet()) { + if (isCanceled()) break; currentFile = file.getName(); - final Set<MarkerInfo> markerInfoSet = markersByFile.get(file); + Set<MarkerInfo> markerInfoSet = markersByFile.get(file); // MarkerUtil.deleteAllMarkersIn(file); - final Iterator<MarkerInfo> j = markerInfoSet.iterator(); - while (j.hasNext()) { - final MarkerInfo markerInfo = j.next(); - final IMarker marker = file.createMarker(markerInfo.getType()); + for (MarkerInfo markerInfo : markerInfoSet) { + IMarker marker = file.createMarker(markerInfo.getType()); marker.setAttributes(markerInfo.getAttributeNames(), markerInfo.getAttributeValues()); violationCount++; } worked(1); - } } catch (CoreException e) { - log.warn("CoreException when setting marker info for file " + currentFile + " : " + e.getMessage()); // TODO: + log.warn("CoreException when setting marker for file " + currentFile + " : " + e.getMessage()); // TODO: // NLS } finally { timer.stop(); - logInfo("" + violationCount + " markers applied on " + markersByFile.size() + " files in " + timer.getDuration() + "ms."); - log.info("End of processing marker directives. " + violationCount + " violations for " + markersByFile.size() + " files."); + int count = markersByFile.size(); + logInfo("" + violationCount + " markers applied on " + count + " files in " + timer.getDuration() + "ms."); + log.info("End of processing marker directives. " + violationCount + " violations for " + count + " files."); } } @@ -463,7 +467,7 @@ private void applyMarkers() { * @param resource a project * @return the element count */ - private int countResourceElement(final IResource resource) { + private int countResourceElement(IResource resource) { final CountVisitor visitor = new CountVisitor(); try { @@ -481,7 +485,7 @@ private int countResourceElement(final IResource resource) { * @param delta a resource delta * @return the element count */ - private int countDeltaElement(final IResourceDelta delta) { + private int countDeltaElement(IResourceDelta delta) { final CountVisitor visitor = new CountVisitor(); try { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java index 94a0f132560..48177ea3a31 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java @@ -38,7 +38,13 @@ import java.util.Set; +import net.sourceforge.pmd.RulePriority; +import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; +import net.sourceforge.pmd.eclipse.ui.Shape; +import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; + import org.apache.log4j.Level; +import org.eclipse.swt.graphics.RGB; /** * This interface models the PMD Plugin preferences @@ -61,6 +67,12 @@ public interface IPreferences { Level LOG_LEVEL = Level.WARN; String ACTIVE_RULES = ""; + PriorityDescriptor PD_1_DEFAULT = new PriorityDescriptor(RulePriority.HIGH, StringKeys.VIEW_FILTER_PRIORITY_1, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_1, null, Shape.diamond, new RGB( 255,0,0), 13); // red + PriorityDescriptor PD_2_DEFAULT = new PriorityDescriptor(RulePriority.MEDIUM_HIGH, StringKeys.VIEW_FILTER_PRIORITY_2, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_2, null, Shape.square, new RGB( 0,255,255), 13); // yellow + PriorityDescriptor PD_3_DEFAULT = new PriorityDescriptor(RulePriority.MEDIUM, StringKeys.VIEW_FILTER_PRIORITY_3, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_3, null, Shape.circle, new RGB( 0,255,0), 13); // green + PriorityDescriptor PD_4_DEFAULT = new PriorityDescriptor(RulePriority.MEDIUM_LOW, StringKeys.VIEW_FILTER_PRIORITY_4, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_4, null, Shape.domeRight,new RGB( 255,0,255), 13); // purple + PriorityDescriptor PD_5_DEFAULT = new PriorityDescriptor(RulePriority.LOW, StringKeys.VIEW_FILTER_PRIORITY_5, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_5, null, Shape.plus, new RGB( 0,0,255), 13); // blue + boolean isActive(String rulename); void isActive(String ruleName, boolean flag); @@ -107,7 +119,7 @@ public interface IPreferences { * Get the review additional comment. This comment is a text appended to the * review comment that is inserted into the code when a violation is reviewed. * This string follows the MessageFormat syntax and could contain 2 variable fields. - * The 1st fied is replaced by the current used id and the second by the current date. + * The 1st field is replaced by the current used id and the second by the current date. */ String getReviewAdditionalComment(); @@ -119,7 +131,7 @@ public interface IPreferences { /** * Does the review comment should be the PMD style (// NOPMD comment) or the - * Plugin style (// @PMD:REVIEW...) which was implemented before. + * plugin style (// @PMD:REVIEW...) which was implemented before. */ boolean isReviewPmdStyleEnabled(); @@ -128,6 +140,9 @@ public interface IPreferences { */ void setReviewPmdStyleEnabled(boolean reviewPmdStyleEnabled); + void setPriorityDescriptor(RulePriority priority, PriorityDescriptor pd); + + PriorityDescriptor getPriorityDescriptor(RulePriority priority); // CPD Preferences diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java index b7a91c3074b..099d98e70d5 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java @@ -36,9 +36,13 @@ package net.sourceforge.pmd.eclipse.runtime.preferences.impl; +import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Set; +import net.sourceforge.pmd.RulePriority; +import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesManager; @@ -63,6 +67,9 @@ class PreferencesImpl implements IPreferences { private String logFileName; private Level logLevel; private Set<String> activeRuleNames = new HashSet<String>(); + + private Map<RulePriority, PriorityDescriptor> uiDescriptorsByPriority = new HashMap<RulePriority, PriorityDescriptor>(5); + /** * Is constructed from a preferences manager * @param preferencesManager @@ -211,4 +218,12 @@ public void setActiveRuleNames(Set<String> ruleNames) { activeRuleNames = ruleNames; } + public void setPriorityDescriptor(RulePriority priority, PriorityDescriptor pd) { + uiDescriptorsByPriority.put(priority, pd); + } + + public PriorityDescriptor getPriorityDescriptor(RulePriority priority) { + return uiDescriptorsByPriority.get(priority); + } + } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java index 11ae3ff4972..bc3ac6c7d7a 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java @@ -48,11 +48,13 @@ import java.util.Set; import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.RulePriority; import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetNotFoundException; import net.sourceforge.pmd.eclipse.core.IRuleSetManager; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesFactory; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesManager; @@ -90,7 +92,12 @@ class PreferencesManagerImpl implements IPreferencesManager { private static final String LOG_FILENAME = PMDPlugin.PLUGIN_ID + ".log_filename"; private static final String LOG_LEVEL = PMDPlugin.PLUGIN_ID + ".log_level"; private static final String DISABLED_RULES = PMDPlugin.PLUGIN_ID + ".disabled_rules"; - + private static final String PRIORITY_DESC_1 = PMDPlugin.PLUGIN_ID + ".priority_descriptor_1"; + private static final String PRIORITY_DESC_2 = PMDPlugin.PLUGIN_ID + ".priority_descriptor_2"; + private static final String PRIORITY_DESC_3 = PMDPlugin.PLUGIN_ID + ".priority_descriptor_3"; + private static final String PRIORITY_DESC_4 = PMDPlugin.PLUGIN_ID + ".priority_descriptor_4"; + private static final String PRIORITY_DESC_5 = PMDPlugin.PLUGIN_ID + ".priority_descriptor_5"; + private static final String OLD_PREFERENCE_PREFIX = "net.sourceforge.pmd.runtime"; private static final String OLD_PREFERENCE_LOCATION = "/.metadata/.plugins/org.eclipse.core.runtime/.settings/net.sourceforge.pmd.runtime.prefs"; public static final String NEW_PREFERENCE_LOCATION = "/.metadata/.plugins/org.eclipse.core.runtime/.settings/net.sourceforge.pmd.eclipse.plugin.prefs"; @@ -121,6 +128,7 @@ public IPreferences loadPreferences() { loadLogFileName(); loadLogLevel(); loadActiveRules(); + loadRulePriorityDescriptors(); } return this.preferences; @@ -179,6 +187,7 @@ public void storePreferences(IPreferences preferences) { storeLogFileName(); storeLogLevel(); storeActiveRules(); + storePriorityDescriptors(); } /** @@ -186,10 +195,10 @@ public void storePreferences(IPreferences preferences) { */ public RuleSet getRuleSet() { - if (this.ruleSet == null) { - this.ruleSet = getRuleSetFromStateLocation(); + if (ruleSet == null) { + ruleSet = getRuleSetFromStateLocation(); } - return this.ruleSet; + return ruleSet; } /** @@ -282,6 +291,29 @@ private void loadActiveRules() { this.preferences.setActiveRuleNames(asStringSet(loadPreferencesStore.getString(DISABLED_RULES), ",")); } + /** + * Read the priority descriptors + * + */ + private void loadRulePriorityDescriptors() { + // TODO - put into a loop + loadPreferencesStore.setDefault(PRIORITY_DESC_1, IPreferences.PD_1_DEFAULT.storeString()); + preferences.setPriorityDescriptor(RulePriority.HIGH, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_1) ) ); + + loadPreferencesStore.setDefault(PRIORITY_DESC_2, IPreferences.PD_2_DEFAULT.storeString()); + preferences.setPriorityDescriptor(RulePriority.MEDIUM_HIGH, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_2) ) ); + + loadPreferencesStore.setDefault(PRIORITY_DESC_3, IPreferences.PD_3_DEFAULT.storeString()); + preferences.setPriorityDescriptor(RulePriority.MEDIUM, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_3) ) ); + + loadPreferencesStore.setDefault(PRIORITY_DESC_4, IPreferences.PD_4_DEFAULT.storeString()); + preferences.setPriorityDescriptor(RulePriority.MEDIUM_LOW, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_4) ) ); + + loadPreferencesStore.setDefault(PRIORITY_DESC_5, IPreferences.PD_5_DEFAULT.storeString()); + preferences.setPriorityDescriptor(RulePriority.LOW, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_5) ) ); + } + + private static Set<String> asStringSet(String delimitedString, String delimiter) { String[] values = delimitedString.split(delimiter); @@ -374,6 +406,15 @@ private void storeLogLevel() { this.storePreferencesStore.setValue(LOG_LEVEL, this.preferences.getLogLevel().toString()); } + private void storePriorityDescriptors() { + // TODO put into a loop + storePreferencesStore.setValue(PRIORITY_DESC_1, preferences.getPriorityDescriptor(RulePriority.HIGH).storeString()); + storePreferencesStore.setValue(PRIORITY_DESC_2, preferences.getPriorityDescriptor(RulePriority.MEDIUM_HIGH).storeString()); + storePreferencesStore.setValue(PRIORITY_DESC_3, preferences.getPriorityDescriptor(RulePriority.MEDIUM).storeString()); + storePreferencesStore.setValue(PRIORITY_DESC_4, preferences.getPriorityDescriptor(RulePriority.MEDIUM_LOW).storeString()); + storePreferencesStore.setValue(PRIORITY_DESC_5, preferences.getPriorityDescriptor(RulePriority.LOW).storeString()); + } + /** * Get rule set from state location */ diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/search/RuleSearchPage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/search/RuleSearchPage.java new file mode 100755 index 00000000000..3f1488e26e8 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/search/RuleSearchPage.java @@ -0,0 +1,147 @@ +package net.sourceforge.pmd.eclipse.search; + +import java.util.List; + +import net.sourceforge.pmd.lang.Language; + +import org.eclipse.jface.dialogs.DialogPage; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.search.ui.ISearchPage; +import org.eclipse.search.ui.ISearchPageContainer; +import org.eclipse.swt.SWT; +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.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +/** + * + * @author Brian Remedios + */ +public class RuleSearchPage extends DialogPage implements ISearchPage { + + private Text idText; + private Button caseSensitive; + + private String selected; + + private Button name; + private Button description; + private Button example; + private Button xpath; + private Combo language; + + public RuleSearchPage() { + } + + public RuleSearchPage(String title) { + super(title); + } + + public RuleSearchPage(String title, ImageDescriptor image) { + super(title, image); + } + + public boolean performAction() { + // TODO Auto-generated method stub + return false; + } + + public void setContainer(ISearchPageContainer container) { + if (container.getSelection() instanceof TextSelection) { + selected = ((TextSelection) container.getSelection()).getText(); + } + } + + public void buildLanguageCombo(Composite parent) { + + final List<Language> languages = Language.findWithRuleSupport(); + + language = new Combo(parent, SWT.READ_ONLY); + + Language deflt = Language.getDefaultLanguage(); + int selectionIndex = -1; + + for (int i = 0; i < languages.size(); i++) { + if (languages.get(i) == deflt) selectionIndex = i; + language.add(languages.get(i).getName()); + } + + language.select(selectionIndex); + } + + private void addButtons(Composite parent, int horizSpan) { + + Group group = new Group(parent, SWT.BORDER); + group.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, true, true, horizSpan, 1)); + group.setLayout( new GridLayout(2, false)); + group.setText("Scope"); + + name = new Button(group, SWT.CHECK); + name.setText("Names"); + + description = new Button(group, SWT.CHECK); + description.setText("Descriptions"); + + example = new Button(group, SWT.CHECK); + example.setText("Examples"); + + xpath = new Button(group, SWT.CHECK); + xpath.setText("XPaths"); + } + + public void createControl(Composite parent) { + + Composite panel = new Composite(parent, SWT.NONE); + panel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, GridData.FILL_VERTICAL, true, true, 2, 1)); + panel.setLayout( new GridLayout(3, false)); + + Composite textPanel = new Composite(panel, SWT.None); + textPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, GridData.BEGINNING, true, true, 3, 1)); + textPanel.setLayout(new GridLayout(4, false)); + + Label label = new Label(textPanel, SWT.BORDER); + label.setText("Containing text:"); + label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 4, 1)); + + idText = new Text(textPanel, SWT.BORDER); + // idText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, GridData.BEGINNING, true, false, 3, 1)); + + GridData gridData2 = new GridData(); + gridData2.horizontalSpan=3; + // gridData2.grabExcessHorizontalSpace = true; + // gridData2.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL; + idText.setLayoutData(gridData2); + + + if (selected != null) { + idText.setText(selected); + idText.setSelection(0, selected.length()); + } + + caseSensitive = new Button(textPanel, SWT.CHECK); + caseSensitive.setText("Case sensitive"); + caseSensitive.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1)); + +// addButtons(panel, 4); +// +// Label langLabel = new Label(panel, SWT.None); +// langLabel.setText("Language"); +// buildLanguageCombo(panel); + + setControl(panel); + } + + @Override + public void setVisible(boolean visible) { + super.setVisible(visible); + idText.setFocus(); + } + + +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java index cf03b573868..56a8879bdf6 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java @@ -130,6 +130,8 @@ public class PMDUiConstants { public static final String MEMENTO_OVERVIEW_FILE = "/violationOverview_memento.xml"; public static final String MEMENTO_DATAFLOW_FILE = "/dataflowView_memento.xml"; + public static final String MEMENTO_AST_FILE = "/astView_memento.xml"; + public static final String KEY_MARKERATT_RULENAME = "rulename"; public static final String KEY_MARKERATT_PRIORITY = "pmd_priority"; public static final String KEY_MARKERATT_LINE2 = "line2"; diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/RuleLabelDecorator.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/RuleLabelDecorator.java new file mode 100755 index 00000000000..810a1aff4dc --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/RuleLabelDecorator.java @@ -0,0 +1,91 @@ +package net.sourceforge.pmd.eclipse.ui; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import net.sourceforge.pmd.eclipse.plugin.UISettings; +import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; +import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IDecoration; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ILightweightLabelDecorator; +import org.eclipse.jface.viewers.LabelProviderChangedEvent; + +public class RuleLabelDecorator implements ILightweightLabelDecorator { + + private Collection<ILabelProviderListener> listeners; + + private Map<Integer, ImageDescriptor> overlaysByPriority; + + public RuleLabelDecorator() { + reloadDecorators(); + } + + public void addListener(ILabelProviderListener listener) { + if (listeners == null) listeners = new HashSet<ILabelProviderListener>(); + listeners.add(listener); + } + + public void dispose() { + + } + + public void changed(Collection<IResource> resources) { + + if (listeners == null) return; + + LabelProviderChangedEvent lpce = new LabelProviderChangedEvent(this, resources.toArray()); + + for (ILabelProviderListener listener : listeners) { + listener.labelProviderChanged(lpce); + } + + } + + public void reloadDecorators() { + overlaysByPriority = UISettings.markerImgDescriptorsByPriority(); + } + + public boolean isLabelProperty(Object element, String property) { return false; } + + public void removeListener(ILabelProviderListener listener) { + if (listeners == null) return; + listeners.remove(listener); + } + + public void decorate(Object element, IDecoration decoration) { + + if ( !(element instanceof IResource) ) return; + + IResource resource = (IResource)element; + + Set<Integer> range = null; + try { + range = MarkerUtil.priorityRangeOf(resource, PMDRuntimeConstants.RULE_MARKER_TYPES, 5); + } catch (CoreException e1) { + return; + } + + if (range.isEmpty()) return; + + Integer first = range.iterator().next(); + ImageDescriptor overlay = overlaysByPriority.get(first); + + try { + boolean hasMarkers = MarkerUtil.hasAnyRuleMarkers(resource); + if (hasMarkers) decoration.addOverlay(overlay); + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/Shape.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/Shape.java new file mode 100755 index 00000000000..dc5af5c897c --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/Shape.java @@ -0,0 +1,78 @@ +package net.sourceforge.pmd.eclipse.ui; + +/** + * + * @author Brian Remedios + */ +public enum Shape { + + square(1, "Square"), circle(2, "Circle"), roundedRect(3, "Rounded rectangle"), diamond(4, "Diamond"), + + minus(5, "Dash"), pipe(6, "Pipe"), + + domeRight(7, "Dome right"), domeLeft(8, "Dome left"), domeUp(9,"Dome up"), domeDown(10, "Dome down"), + + triangleUp(11,"Triangle up"), triangleDown(12,"Triangle down"), triangleRight(13,"Triangle right"), triangleLeft(14,"Triangle left"), + triangleNorthEast(15,"Triangle NE"), triangleSouthEast(16,"Triangle SE"), + triangleSouthWest(17,"Triangle SW"), triangleNorthWest(18,"Triangle NW"), + + plus(20,"Plus", new float[] { + 0.333f, 0, + 0.666f, 0, + 0.666f, 0.333f, + 1, 0.333f, + 1, 0.666f, + 0.666f, 0.666f, + 0.666f, 1, + 0.333f, 1, + 0.333f, 0.666f, + 0, 0.666f, + 0, 0.333f, + 0.333f, 0.333f + }), + star(21, "Star", new float[] { + 0.500f, 1.000f, + 0.378f, 0.619f, + 0, 0.619f, + 0.303f, 0.381f, + 0.193f, 0, + 0.500f, 0.226f, + 0.807f, 0, + 0.697f, 0.381f, + 1.000f, 0.619f, + 0.622f, 0.619f + }); + + public final int id; + public final String label; + private final float[] polyPoints; + + private Shape(int theId, String theLabel) { + this(theId, theLabel, null); + } + + private Shape(int theId, String theLabel, float[] optionalPolygonPoints) { + id = theId; + label = theLabel; + polyPoints = optionalPolygonPoints; + } + + @Override + public String toString() { + return label; + } + + public int[] scaledPointsTo(int xMax, int yMax, int xOffset, int yOffset, boolean flipX, boolean flipY) { + + if (polyPoints == null) return new int[0]; + + int[] points = new int[polyPoints.length]; + + for (int i=0; i<points.length; i+=2) { + points[i] = (int)(xMax * (flipX ? 1-polyPoints[i] : polyPoints[i])) + xOffset; + points[i+1] = (int)(yMax * (flipY ? 1-polyPoints[i+1] : polyPoints[i])) + yOffset; + } + + return points; + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapeDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapeDescriptor.java new file mode 100755 index 00000000000..115d0f8e8c5 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapeDescriptor.java @@ -0,0 +1,55 @@ +package net.sourceforge.pmd.eclipse.ui; + + +import org.eclipse.swt.graphics.RGB; + +/** + * + * @author Brian Remedios + */ +public class ShapeDescriptor implements Cloneable { + + public Shape shape; + public RGB rgbColor; + public int size; + + public ShapeDescriptor(Shape theShape, RGB theColor, int theSize) { + shape = theShape; + rgbColor = theColor; + size = theSize; + } + + private ShapeDescriptor() { + + } + + public boolean equals(Object other) { + + if (this == other) return true; + if (other.getClass() != getClass()) return false; + + ShapeDescriptor otherOne = (ShapeDescriptor)other; + + return shape.equals(otherOne.shape) && + rgbColor.equals(otherOne.rgbColor) && + size == otherOne.size; + } + + public int hashCode() { + return rgbColor.hashCode() ^ shape.hashCode() ^ size; + } + + public ShapeDescriptor clone() { + + ShapeDescriptor copy = new ShapeDescriptor(); + copy.shape = shape; + copy.rgbColor = new RGB(rgbColor.red, rgbColor.green, rgbColor.blue); + copy.size = size; + return copy; + } + + public String toString() { + + return shape.name() + ", " + rgbColor + ", " + size; + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePainter.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePainter.java new file mode 100755 index 00000000000..6947f755eda --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePainter.java @@ -0,0 +1,157 @@ +package net.sourceforge.pmd.eclipse.ui; + +import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; + +/** + * + * @author br + * + */ +public class ShapePainter { + + private ShapePainter() {} + + /** + * Creates an image initialized with the transparent colour with the shape drawn within. + * + * + */ + public static Image newDrawnImage(Display display, int width, int height, Shape shape, RGB transparentColour, RGB fillColour) { + + Image image = new Image(display, width, height); + GC gc = new GC(image); + + gc.setBackground(PMDPlugin.getDefault().colorFor(transparentColour)); + gc.fillRectangle(0, 0, width, height); + + gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); + gc.setBackground(PMDPlugin.getDefault().colorFor(fillColour)); + + drawShape(width-1, height-1, shape, gc, 0, 0, null); + + ImageData data = image.getImageData(); + int clrIndex = data.palette.getPixel(transparentColour); + data.transparentPixel = clrIndex; + + image = new Image(display, data); + + gc.dispose(); + return image; + } + + public static void drawShape(int width, int height, Shape shapeId, GC gc, int x, int y, String optionalText) { + + // TODO implement the following shapes: star, pentagon, hexagon, octagon, doughnut + + switch (shapeId) { + case square: { + gc.fillRectangle(x, y, width, height); // fill it + gc.drawRectangle(x, y, width, height); // then the border on top + break; + } + case circle: { + gc.fillArc(x, y, width, height, 0, 360*64); + gc.drawArc(x, y, width, height, 0, 360*64); + break; + } + case domeLeft: { + gc.fillArc(x+width/4, y, width, height, 90, 180); + gc.drawArc(x+width/4, y, width, height, 90, 180); + int threeQuarters = width/2 + width/4; + gc.drawLine(x + threeQuarters, y, x+threeQuarters, y+height); + break; + } + case domeRight: { + gc.fillArc(x-width/4, y, width, height, 270, 180); + gc.drawArc(x-width/4, y, width, height, 270, 180); + gc.drawLine(x + width/4, y, x+width/4, y+height); + break; + } + case pipe: { + gc.fillRectangle(x + (width/4), y, width - (width/2), height); + gc.drawRectangle(x + (width/4), y, width - (width/2), height); + break; + } +// case plus: { +// int xA = x + width/3; +// int xB = x + ((width/3) * 2); +// int yA = y + height/3; +// int yB = y+ ((height/3) * 2); +// int[] points = new int[] { xA,y, xB,y, xB,yA, x+width,yA, x+width,yB, xB,yB, xB,y+height, xA,y+height, xA,yB, x,yB, x,yA, xA,yA }; +// gc.fillPolygon(points); +// gc.drawPolygon(points); +// break; +// } + case minus: { + gc.fillRectangle(x, y + (height/4), width, height - (height/2)); + gc.drawRectangle(x, y + (height/4), width, height - (height/2)); + break; + } + case triangleDown: { + gc.fillPolygon(new int[] {x, y, x+width, y, x+(width/2), y+height}); + gc.drawPolygon(new int[] {x, y, x+width, y, x+(width/2), y+height}); + break; + } + case triangleUp: { + gc.fillPolygon(new int[] {x, y+height, x+width, y+height, x+(width/2), y}); + gc.drawPolygon(new int[] {x, y+height, x+width, y+height, x+(width/2), y}); + break; + } + case triangleRight: { + gc.fillPolygon(new int[] {x, y+height, x+width, y+(height/2), x, y}); + gc.drawPolygon(new int[] {x, y+height, x+width, y+(height/2), x, y}); + break; + } + case triangleLeft: { + gc.fillPolygon(new int[] {x, y+(height/2), x+width, y, x+width, y+height}); + gc.drawPolygon(new int[] {x, y+(height/2), x+width, y, x+width, y+height}); + break; + } + case triangleNorthEast: { + gc.fillPolygon(new int[] {x, y, x+width, y, x+width, y+height}); + gc.drawPolygon(new int[] {x, y, x+width, y, x+width, y+height}); + break; + } + case triangleNorthWest: { + gc.fillPolygon(new int[] {x, y, x+width, y, x, y+height}); + gc.drawPolygon(new int[] {x, y, x+width, y, x, y+height}); + break; + } + case triangleSouthEast: { + gc.fillPolygon(new int[] {x, y, x+width, y+height, x, y+height}); + gc.drawPolygon(new int[] {x, y, x+width, y+height, x, y+height}); + break; + } + case triangleSouthWest: { + gc.fillPolygon(new int[] {x, y+height, x+width, y+height, x+width, y}); + gc.drawPolygon(new int[] {x, y+height, x+width, y+height, x+width, y}); + break; + } + case roundedRect: { + gc.fillRoundRectangle(x, y, width, height, width / 2, height / 2); + gc.drawRoundRectangle(x, y, width, height, width / 2, height / 2); + break; + } + case diamond: { + gc.fillPolygon(new int[] {x+(width/2), y, x+width, y+(height/2), x+(width/2), y+height, x, y+(height/2)}); + gc.drawPolygon(new int[] {x+(width/2), y, x+width, y+(height/2), x+(width/2), y+height, x, y+(height/2)}); + break; + } + default: { + int[] points = shapeId.scaledPointsTo(width, height, x, y, false, true); + if (points.length > 1) { + gc.fillPolygon(points); + gc.drawPolygon(points); + } + } + } + if (optionalText != null) gc.drawString(optionalText, x, y); + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePicker.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePicker.java new file mode 100755 index 00000000000..af220cbc1f0 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePicker.java @@ -0,0 +1,255 @@ +package net.sourceforge.pmd.eclipse.ui; + +import java.util.HashMap; +import java.util.Map; +import java.util.Vector; + +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.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.FocusEvent; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.MouseMoveListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.ISelectionListener; + +/** + * Renders a set of coloured shapes mapped to known set of incoming items + * + * @author Brian Remedios + */ +public class ShapePicker<T extends Object> extends Canvas implements ISelectionProvider { + + private T[] items; + private int itemWidth; + private int gap = 6; + private T selectedItem; + private T highlightItem; + private Color selectedItemFillColor; + + private Map<T, ShapeDescriptor> shapeDescriptorsByItem; +// private Map<T, String> tooltipsByItem; + + private Vector<ISelectionChangedListener> listeners; + + private static Map<RGB, Color> coloursByRGB = new HashMap<RGB, Color>(); + + public ShapePicker(Composite parent, int style, int theItemWidth) { + super(parent, style); + + itemWidth = theItemWidth; + + ShapePicker.this.addPaintListener( new PaintListener() { + public void paintControl(PaintEvent pe) { + doPaint(pe); + } + } ); + + ShapePicker.this.addMouseMoveListener( new MouseMoveListener() { + public void mouseMove(MouseEvent e) { + if (!getEnabled()) return; + T newItem = itemAt(e.x, e.y); + if (newItem != highlightItem) { + highlightItem = newItem; + setToolTipText(newItem == null ? "" : newItem.toString()); + redraw(); + } + } + } ); + + ShapePicker.this.addMouseListener( new MouseListener() { + public void mouseDoubleClick(MouseEvent e) { } + public void mouseDown(MouseEvent e) { forceFocus(); } + public void mouseUp(MouseEvent e) { + if (!getEnabled()) return; + T newItem = itemAt(e.x, e.y); + if (newItem != selectedItem) { + selectedItem = newItem; + redraw(); + selectionChanged(); + } + } + } ); + + ShapePicker.this.addFocusListener( new FocusListener() { + public void focusGained(FocusEvent e) { redraw(); } + public void focusLost(FocusEvent e) { redraw(); } + } ); + + selectedItemFillColor = colorFor(new RGB(200,200,200)); + } + + private Color colourFor(int itemIndex) { + + ShapeDescriptor desc = shapeDescriptorsByItem.get(items[itemIndex]); + if (desc == null) return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); + + RGB rgb = desc.rgbColor; + + return colorFor(rgb); + } + + private Color colorFor(RGB rgb) { + + Color color = coloursByRGB.get(rgb); + if (color != null) return color; + + color = new Color(null, rgb.red, rgb.green, rgb.blue); + coloursByRGB.put( rgb, color ); + + return color; + } + + private void selectionChanged() { + if (listeners == null) return; + IStructuredSelection selection = new StructuredSelection( new Object[] { selectedItem } ); + SelectionChangedEvent event = new SelectionChangedEvent(this, selection); + for (ISelectionChangedListener listener : listeners) { + listener.selectionChanged(event); + } + } + + public boolean forceFocus() { + boolean state = super.forceFocus(); + redraw(); + return state; + } + + private Shape shapeFor(int itemIndex) { + ShapeDescriptor desc = shapeDescriptorsByItem.get(items[itemIndex]); + return desc == null ? Shape.circle : desc.shape; + } + + private T itemAt(int xIn, int yIn) { + + if (items == null) return null; + + int width = getSize().x; + int xBoundary = 3; + + for (int i=0; i<items.length; i++) { + + int xOffset = 0; + int step = (itemWidth + gap) * i; + + switch (SWT.LEFT) { // TODO take from style bits + case SWT.CENTER: xOffset = (width / 2) - (itemWidth / 2) - xBoundary + step; break; + case SWT.RIGHT: xOffset = width - width - xBoundary; break; + case SWT.LEFT: xOffset = xBoundary + step; + } + + if (xIn < xOffset ) { + return items[ i == 0 ? 0 : i-1 ]; + } + if (xIn < xOffset + itemWidth) return items[i]; + } + + return null; + } + + private void doPaint(PaintEvent pe) { + + if (items == null) return; + + GC gc = pe.gc; + int width = getSize().x; + int xBoundary = 3; + + if (isFocusControl()) { + gc.drawFocus(0,0, getSize().x, getSize().y); + } + + for (int i=0; i<items.length; i++) { + gc.setBackground( selectedItem == items[i] ? selectedItemFillColor : colourFor(i)); + + int xOffset = 0; + int step = (itemWidth + gap) * i; + + switch (SWT.LEFT) { // TODO take from style bits + case SWT.CENTER: xOffset = (width / 2) - (itemWidth / 2) - xBoundary + step; break; + case SWT.RIGHT: xOffset = width - width - xBoundary; break; + case SWT.LEFT: xOffset = xBoundary + step; + } + + gc.setLineWidth( showHighlightOn(items[i]) ? 3 : 1); + + ShapePainter.drawShape(itemWidth, itemWidth, shapeFor(i), gc, pe.x + xOffset, pe.y + gap, null); + } + } + + private boolean showHighlightOn(T item) { + return isFocusControl() && highlightItem == item; + } + + public Point computeSize(int wHint, int hHint, boolean changed) { + + Point pt = getSize(); + // TODO adapt by shape count + return new Point(pt.x, pt.y); + } + + public void setSelection(T item) { + selectedItem = item; + redraw(); + selectionChanged(); + } + + public ISelection getSelection() { + return new StructuredSelection(selectedItem); + } + + public void setGap(int inPixels) { + gap = inPixels; + redraw(); + } + + public void setItems(T[] theItems) { + items = theItems; + redraw(); + } + + public void setItemWidth(int width) { + itemWidth = width; + redraw(); + } + + public void setShapeMap(Map<T, ShapeDescriptor> theShapeMap) { + + shapeDescriptorsByItem = theShapeMap; + redraw(); + } + + public void addSelectionChangedListener(ISelectionChangedListener listener) { + if (listeners == null) listeners = new Vector<ISelectionChangedListener>(); + listeners.add(listener); + } + + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + if (listeners == null) return; + listeners.remove(listener); + } + + public void setSelection(ISelection selection) { + + setSelection( (T)((StructuredSelection)selection).getFirstElement() ); + + } + +// public void setTooltipMap(Map<T, String> theTooltips) { +// tooltipsByItem = theTooltips; +// } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java index 27882a9a65e..c97c99b242f 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java @@ -164,7 +164,7 @@ protected void clearReviews() { if (selection != null && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (getMonitor() != null) { - getMonitor().beginTask(getString(StringKeys.MSGKEY_MONITOR_REMOVE_REVIEWS), IProgressMonitor.UNKNOWN); + getMonitor().beginTask(getString(StringKeys.MONITOR_REMOVE_REVIEWS), IProgressMonitor.UNKNOWN); Iterator<?> i = structuredSelection.iterator(); while (i.hasNext()) { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java index da6291fd056..691755a384f 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java @@ -35,7 +35,6 @@ import java.util.Iterator; -import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; import net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; @@ -128,7 +127,7 @@ else if (isEditorPart()) { final IEditorInput editorInput = ((IEditorPart) targetPart()).getEditorInput(); if (editorInput instanceof IFileEditorInput) { MarkerUtil.deleteAllMarkersIn(((IFileEditorInput) editorInput).getFile()); - log.debug("Remove markers " + PMDRuntimeConstants.PMD_MARKER + " on currently edited file " + ((IFileEditorInput) editorInput).getFile().getName()); + log.debug("Remove markers on currently edited file " + ((IFileEditorInput) editorInput).getFile().getName()); } else { log.debug("The kind of editor input is not supported. The editor input type: " + editorInput.getClass().getName()); } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/BasicLineStyleListener.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/BasicLineStyleListener.java new file mode 100644 index 00000000000..c7a22cd7488 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/BasicLineStyleListener.java @@ -0,0 +1,251 @@ +package net.sourceforge.pmd.eclipse.ui.editors; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import net.sourceforge.pmd.util.StringUtil; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.LineStyleEvent; +import org.eclipse.swt.custom.LineStyleListener; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.widgets.Display; + +/** + * This class performs the syntax highlighting and styling for Pmpe + */ +public class BasicLineStyleListener implements LineStyleListener { + +// FIXME take these from the Eclipse preferences instead + private static final Color COMMENT_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN); + private static final Color REFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN); + private static final Color UNREFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); + private static final Color COMMENT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + private static final Color PUNCTUATION_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); + private static final Color KEYWORD_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA); + private static final Color STRING_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); + + // Holds the syntax data + private SyntaxData syntaxData; + + // Holds the offsets for all multiline comments + private List<int[]> commentOffsets; + + /** + * PmpeLineStyleListener constructor + * + * @param syntaxData + * the syntax data to use + */ + public BasicLineStyleListener(SyntaxData theSyntaxData) { + syntaxData = theSyntaxData; + commentOffsets = new LinkedList<int[]>(); + } + + /** + * Refreshes the offsets for all multiline comments in the parent StyledText. + * The parent StyledText should call this whenever its text is modified. Note + * that this code doesn't ignore comment markers inside strings. + * + * @param text + * the text from the StyledText + */ + public void refreshMultilineComments(String text) { + // Clear any stored offsets + commentOffsets.clear(); + + if (syntaxData != null) { + // Go through all the instances of COMMENT_START + for (int pos = text.indexOf(syntaxData.getMultiLineCommentStart()); pos > -1; pos = text.indexOf(syntaxData.getMultiLineCommentStart(), pos)) { + // offsets[0] holds the COMMENT_START offset + // and COMMENT_END holds the ending offset + int[] offsets = new int[2]; + offsets[0] = pos; + + // Find the corresponding end comment. + pos = text.indexOf(syntaxData.getMultiLineCommentEnd(), pos); + + // If no corresponding end comment, use the end of the text + offsets[1] = pos == -1 ? + text.length() - 1 : + pos + syntaxData.getMultiLineCommentEnd().length() - 1; + pos = offsets[1]; + // Add the offsets to the collection + commentOffsets.add(offsets); + } + } + } + + /** + * Checks to see if the specified section of text begins inside a multiline + * comment. Returns the index of the closing comment, or the end of the line + * if the whole line is inside the comment. Returns -1 if the line doesn't + * begin inside a comment. + * + * @param start + * the starting offset of the text + * @param length + * the length of the text + * @return int + */ + private int getBeginsInsideComment(int start, int length) { + // Assume section doesn't being inside a comment + int index = -1; + + // Go through the multiline comment ranges + for (int i = 0, n = commentOffsets.size(); i < n; i++) { + int[] offsets = (int[]) commentOffsets.get(i); + + // If starting offset is past range, quit + if (offsets[0] > start + length) + break; + // Check to see if section begins inside a comment + if (offsets[0] <= start && offsets[1] >= start) { + // It does; determine if the closing comment marker is inside this section + index = offsets[1] > start + length ? + start + length : + offsets[1] + syntaxData.getMultiLineCommentEnd().length() - 1; + } + } + return index; + } + + private boolean isDefinedVariable(String text) { + return !StringUtil.isEmpty(text); + } + + private boolean atMultiLineCommentStart(String text, int position) { + return text.indexOf(syntaxData.getMultiLineCommentStart(), position) == position; + } + + private boolean atStringStart(String text, int position) { + return text.indexOf(syntaxData.stringStart, position) == position; + } + + private boolean atVarnameReference(String text, int position) { + if (syntaxData.varnameReference == null) return false; + return text.indexOf(syntaxData.varnameReference, position) == position; + } + + private boolean atSingleLineComment(String text, int position) { + if (syntaxData.getComment() == null) return false; + return text.indexOf(syntaxData.getComment(), position) == position; + } + + /** + * Called by StyledText to get styles for a line + */ + public void lineGetStyle(LineStyleEvent event) { + + String lineText = event.lineText; + int lineOffset = event.lineOffset; + + List<StyleRange> styles = new ArrayList<StyleRange>(); + + int start = 0; + int length = lineText.length(); + + // Check if line begins inside a multiline comment + int mlIndex = getBeginsInsideComment(lineOffset, lineText.length()); + if (mlIndex > -1) { + // Line begins inside multiline comment; create the range + styles.add(new StyleRange(lineOffset, mlIndex - lineOffset, COMMENT_COLOR, COMMENT_BACKGROUND)); + start = mlIndex; + } + // Do punctuation, single-line comments, and keywords + while (start < length) { + // Check for multiline comments that begin inside this line + if (atMultiLineCommentStart(lineText, start)) { + // Determine where comment ends + int endComment = lineText.indexOf(syntaxData.getMultiLineCommentEnd(), start); + + // If comment doesn't end on this line, extend range to end of line + if (endComment == -1) + endComment = length; + else + endComment += syntaxData.getMultiLineCommentEnd().length(); + styles.add(new StyleRange(lineOffset + start, endComment - start, COMMENT_COLOR, COMMENT_BACKGROUND)); + + start = endComment; + } + + else if (atStringStart(lineText, start)) { + // Determine where comment ends + int endString = lineText.indexOf(syntaxData.stringEnd, start+1); + + // If string doesn't end on this line, extend range to end of line + if (endString == -1) + endString = length; + else + endString += syntaxData.stringEnd.length(); + styles.add(new StyleRange(lineOffset + start, endString - start, STRING_COLOR, COMMENT_BACKGROUND)); + + start = endString; + } + + else if (atSingleLineComment(lineText, start)) { // Check for single line comments + + styles.add(new StyleRange(lineOffset + start, length - start, COMMENT_COLOR, COMMENT_BACKGROUND)); + start = length; + } + + else if (atVarnameReference(lineText, start)) { // Check for variable references + + StringBuilder buf = new StringBuilder(); + int i = start + syntaxData.getVarnameReference().length(); + // Call any consecutive letters a word + for (; i < length && Character.isLetter(lineText.charAt(i)); i++) { + buf.append(lineText.charAt(i)); + } + + // See if the word is a variable + if (isDefinedVariable(buf.toString())) { + // It's a keyword; create the StyleRange + styles.add(new StyleRange(lineOffset + start, i - start, REFERENCED_VAR_COLOR, null, SWT.BOLD)); + } + // Move the marker to the last char (the one that wasn't a letter) + // so it can be retested in the next iteration through the loop + start = i; + } + + // Check for punctuation + else if (syntaxData.isPunctuation(lineText.charAt(start))) { + // Add range for punctuation + styles.add(new StyleRange(lineOffset + start, 1, PUNCTUATION_COLOR, null)); + ++start; + } else if (Character.isLetter(lineText.charAt(start))) { + + int kwEnd = getKeywordEnd(lineText, start); // See if the word is a keyword + + if (kwEnd > start) { // Its a keyword; create the StyleRange + styles.add(new StyleRange(lineOffset + start, kwEnd - start, KEYWORD_COLOR, null)); + } + + // Move the marker to the last char (the one that wasn't a letter) + // so it can be retested in the next iteration through the loop + start = Math.abs(kwEnd); + } else + ++start; // It's nothing we're interested in; advance the marker + } + + // Copy the StyleRanges back into the event + event.styles = (StyleRange[]) styles.toArray(new StyleRange[styles.size()]); + } + + private int getKeywordEnd(String lineText, int start) { + + int length = lineText.length(); + + StringBuilder buf = new StringBuilder(length); + int i = start; + + // Call any consecutive letters a word + for (; i < length && Character.isLetter(lineText.charAt(i)); i++) { + buf.append(lineText.charAt(i)); + } + + return syntaxData.isKeyword(buf.toString()) ? i : 0-i; + } +} \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxData.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxData.java new file mode 100644 index 00000000000..5359d21a731 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxData.java @@ -0,0 +1,86 @@ +package net.sourceforge.pmd.eclipse.ui.editors; + +import java.util.Collection; + +/** + * This class contains information for syntax coloring and styling for an + * extension + */ +public class SyntaxData { + + private String extension; + private Collection<String> keywords; + private String punctuation; + private String comment; + private String multiLineCommentStart; + private String multiLineCommentEnd; + public String varnameReference; + public String stringStart; + public String stringEnd; + + /** + * Constructs a SyntaxData + * + * @param extension + * the extension + */ + public SyntaxData(String extension) { + this.extension = extension; + } + + public boolean matches(String otherExtension) { + return extension.equals(otherExtension); + } + + public String getExtension() { + return extension; + } + + public void setVarnameReference(String refId) { + varnameReference = refId; + } + + public String getVarnameReference() { + return varnameReference; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public boolean isKeyword(String word) { + return keywords != null && keywords.contains(word); + } + + public boolean isPunctuation(char ch) { + return punctuation != null && punctuation.indexOf(ch) >= 0; + } + + public void setKeywords(Collection<String> keywords) { + this.keywords = keywords; + } + + public String getMultiLineCommentEnd() { + return multiLineCommentEnd; + } + + public void setMultiLineCommentEnd(String multiLineCommentEnd) { + this.multiLineCommentEnd = multiLineCommentEnd; + } + + public String getMultiLineCommentStart() { + return multiLineCommentStart; + } + + public void setMultiLineCommentStart(String multiLineCommentStart) { + this.multiLineCommentStart = multiLineCommentStart; + } + + public void setPunctuation(String thePunctuationChars) { + punctuation = thePunctuationChars; + } +} \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxManager.java new file mode 100644 index 00000000000..1b9130f3737 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxManager.java @@ -0,0 +1,104 @@ +package net.sourceforge.pmd.eclipse.ui.editors; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.StringTokenizer; + +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; + +/** + * This class manages the syntax coloring and styling data + */ +public class SyntaxManager { + + private static Map<String, SyntaxData> syntaxByExtension = new Hashtable<String, SyntaxData>(); + + public static ModifyListener adapt(final StyledText codeField, String languageCode, ModifyListener oldListener) { + + if (oldListener != null) { + codeField.removeModifyListener(oldListener); + } + + SyntaxData sd = SyntaxManager.getSyntaxData(languageCode); + if (sd == null) { + //codeField.set clear the existing style ranges TODO + return null; + } + + final BasicLineStyleListener blsl = new BasicLineStyleListener(sd); + codeField.addLineStyleListener(blsl); + + ModifyListener ml = new ModifyListener() { + public void modifyText(ModifyEvent event) { + blsl.refreshMultilineComments(codeField.getText()); + codeField.redraw(); + } + }; + codeField.addModifyListener(ml); + + return ml; + } + + /** + * Gets the syntax data for an extension + */ + public static synchronized SyntaxData getSyntaxData(String extension) { + // Check in cache + SyntaxData sd = syntaxByExtension.get(extension); + if (sd == null) { + // Not in cache; load it and put in cache + sd = loadSyntaxData(extension); + if (sd != null) + syntaxByExtension.put(sd.getExtension(), sd); + } + return sd; + } + + /** + * Loads the syntax data for an extension + * + * @param extension + * the extension to load + * @return SyntaxData + */ + private static SyntaxData loadSyntaxData(String filename) { + SyntaxData sd = null; + try { + ResourceBundle rb = ResourceBundle.getBundle("net.sourceforge.pmd.eclipse.ui.editors." + filename); + sd = new SyntaxData(filename); + + sd.stringStart = rb.getString("stringstart"); + sd.stringEnd = rb.getString("stringend"); + sd.setMultiLineCommentStart(rb.getString("multilinecommentstart")); + sd.setMultiLineCommentEnd(rb.getString("multilinecommentend")); + + // Load the keywords + Collection<String> keywords = new HashSet<String>(); + for (StringTokenizer st = new StringTokenizer(rb.getString("keywords"), " "); st.hasMoreTokens();) { + keywords.add(st.nextToken()); + } + sd.setKeywords(keywords); + + // Load the punctuation + sd.setPunctuation(rb.getString("punctuation")); + + if (rb.containsKey("comment")) { + sd.setComment( rb.getString("comment") ); + } + + if (rb.containsKey("varnamedelimiter")) { + sd.varnameReference = rb.getString("varnamedelimiter"); + } + + } catch (MissingResourceException e) { + // Ignore + } + return sd; + } +} \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/TextChange.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/TextChange.java new file mode 100644 index 00000000000..fbfc96bfd2f --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/TextChange.java @@ -0,0 +1,55 @@ +package net.sourceforge.pmd.eclipse.ui.editors; + +class TextChange { + // The starting offset of the change + private int start; + + // The length of the change + private int length; + + // The replaced text + String replacedText; + + /** + * Constructs a TextChange + * + * @param start + * the starting offset of the change + * @param length + * the length of the change + * @param replacedText + * the text that was replaced + */ + public TextChange(int start, int length, String replacedText) { + this.start = start; + this.length = length; + this.replacedText = replacedText; + } + + /** + * Returns the start + * + * @return int + */ + public int getStart() { + return start; + } + + /** + * Returns the length + * + * @return int + */ + public int getLength() { + return length; + } + + /** + * Returns the replacedText + * + * @return String + */ + public String getReplacedText() { + return replacedText; + } +} \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/c.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/c.properties new file mode 100644 index 00000000000..f57c859d5b5 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/c.properties @@ -0,0 +1,8 @@ +# This file contains the syntax data for .c files +comment=// +stringstart=" +stringend=" +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=auto const double float int short struct unsigned break continue else for long signed switch void case default enum goto register sizeof typedef volatile char do extern if return static union while \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/cpp.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/cpp.properties new file mode 100644 index 00000000000..ab31424e402 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/cpp.properties @@ -0,0 +1,8 @@ +# This file contains the syntax data for .cpp files +comment=// +stringstart=" +stringend=" +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private public protected reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ecmascript.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ecmascript.properties new file mode 100644 index 00000000000..ebc3c995e36 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ecmascript.properties @@ -0,0 +1,10 @@ +# This file contains the syntax data for .xpath files +comment=// +stringstart=' +stringend=' +varnamedelimiter=$ +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=break case catch continue default delete do else finally for function if in instanceof new return switch this throw try typeof var void undefined while with this + diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/fortran77.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/fortran77.properties new file mode 100644 index 00000000000..dd6ba2f146b --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/fortran77.properties @@ -0,0 +1,8 @@ +# This file contains the syntax data for .for files +comment=// +stringstart=" +stringend=" +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=access assign backspace blank block call close common continue data dimension direct do else endif enddo end entry eof equivalence err exist external file fmt form format formatted function goto if implicit include inquire intrinsic iostat logical named namelist nextrec number open opened parameter pause print program read rec recl return rewind sequential status stop subroutine then type unformatted unit write save \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/java.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/java.properties new file mode 100644 index 00000000000..0a842d56039 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/java.properties @@ -0,0 +1,8 @@ +# This file contains the syntax data for .java files +comment=// +stringstart=" +stringend=" +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=abstract assert boolean break byte case catch char class const continue do double else enum extends false final finally for if implements import int interface native new null package protected public private return static strictfp super switch synchronized this throws true try void volatile while diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ruby.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ruby.properties new file mode 100644 index 00000000000..01600b684ed --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ruby.properties @@ -0,0 +1,8 @@ +# This file contains the syntax data for .ruby files +comment=// +stringstart=" +stringend=" +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=alias and BEGIN begin break case class def defined? do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/scala.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/scala.properties new file mode 100644 index 00000000000..931f2e6d5aa --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/scala.properties @@ -0,0 +1,8 @@ +# This file contains the syntax data for .scala files +comment=// +stringstart=" +stringend=" +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=abstract case catch class def do else extends false final finally for forSome if implicit import lazy match new null object override package private protected requires return sealed super this throw trait try true type val var while with yield \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/xpath.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/xpath.properties new file mode 100644 index 00000000000..9fa3c609577 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/xpath.properties @@ -0,0 +1,8 @@ +# This file contains the syntax data for .xpath files +stringstart=' +stringend=' +varnamedelimiter=$ +multilinecommentstart=/* +multilinecommentend=*/ +punctuation=(){};:?<>=+-*/&|~!%.[] +keywords=AdditiveExpression AllocationExpression Annotation ArgumentList Arguments ArrayDimsAndInits ArrayInitializer Assignment AssignmentOperator Block BlockStatement BreakStatement BooleanLiteral CastExpression CatchStatement ClassOrInterfaceBody ClassOrInterfaceDeclaration ClassOrInterfaceBodyDeclaration ClassOrInterfaceType ConditionalExpression ConditionalAndExpression ConditionalOrExpression ConstructorDeclaration ContinueStatement DoLoop Element EmptyStatement EqualityExpression ExplicitConstructorInvocation Expression ExtendsList FieldDeclaration FinallyStatement ForLoop ForInLoop ForStatement FormalParameter FormalParameters IfStatement ImplementsList ImportDeclaration Initializer InstanceOfExpression LabeledStatement Literal LocalVariableDeclaration MarkerAnnotation MethodDeclaration MethodDeclarator Name NameList NullLiteral NumberLiteral PackageDeclaration PrimaryExpression PrimaryPrefix PrimarySuffix PrimitiveType ReferenceType RelationalExpression ResultType ReturnStatement Statement StatementExpression SwitchLabel SwitchStatement SynchronizedStatement ThrowStatement TryStatement Type TypeArgument TypeArguments TypeDeclaration TypeParameter TypeParameters VariableDeclaration VariableDeclarator VariableDeclaratorId VariableInitializer UnaryExpression UnaryExpressionNotPlusMinus WhileLoop WhileStatement \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java index 4887b4953a8..eeaff63176a 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java @@ -204,7 +204,7 @@ public final IMarker[] findMarkers() { // this is the overwritten Function from AbstractPMDRecord // we simply call the IResource-function to find Markers if (this.resource.isAccessible()) { - return MarkerUtil.findMarkers(resource, PMDRuntimeConstants.PMD_MARKER); + return MarkerUtil.findMarkers(resource, PMDRuntimeConstants.RULE_MARKER_TYPES); } } catch (CoreException ce) { PMDPlugin.getDefault().logError(StringKeys.MSGKEY_ERROR_FIND_MARKER + this.toString(), ce); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java index 5429acbeb00..ec5ca57d19d 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java @@ -36,6 +36,11 @@ package net.sourceforge.pmd.eclipse.ui.nls; +import net.sourceforge.pmd.eclipse.ui.preferences.PriorityColumnDescriptor; +import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityFieldAccessor; + +import org.eclipse.swt.SWT; + /** * Convenient class to hold PMD Constants * @author phherlin @@ -60,6 +65,7 @@ public class StringKeys { public static final String MSGKEY_PREF_GENERAL_TOOLTIP_ADDCOMMENT = "preference.pmd.tooltip.addcomment"; public static final String MSGKEY_PREF_GENERAL_MESSAGE_INCORRECT_FORMAT ="preference.pmd.message.incorrect_format"; public static final String MSGKEY_PREF_GENERAL_GROUP_REVIEW = "preference.pmd.group.review"; + public static final String MSGKEY_PREF_GENERAL_GROUP_PRIORITIES = "preference.pmd.group.priorities"; public static final String MSGKEY_PREF_GENERAL_GROUP_GENERAL = "preference.pmd.group.general"; public static final String MSGKEY_PREF_GENERAL_LABEL_SHOW_PERSPECTIVE = "preference.pmd.label.perspective_on_check"; public static final String MSGKEY_PREF_GENERAL_LABEL_USE_DFA = "preference.pmd.label.use_dfa"; @@ -177,7 +183,7 @@ public class StringKeys { public static final String MSGKEY_VIEW_OUTLINE_COLUMN_LINE = "view.outline.column_line"; public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_ELEMENT = "view.overview.column_element"; public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_TOTAL = "view.overview.column_vio_total"; - public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_LOC = "view.overview.column_vio_loc"; + public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_KLOC = "view.overview.column_vio_loc"; public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_METHOD = "view.overview.column_vio_method"; public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_PROJECT = "view.overview.column_project"; public static final String MSGKEY_VIEW_DATAFLOW_DEFAULT_TEXT = "view.dataflow.default_text"; @@ -196,22 +202,24 @@ public class StringKeys { public static final String MSGKEY_VIEW_DATAFLOW_TABLE_COLUMN_METHOD = "view.dataflow.table.column_method"; public static final String MSGKEY_VIEW_DATAFLOW_TABLE_COLUMN_TYPE_TOOLTIP = "view.dataflow.table.column_type.tooltip"; - public static final String MSGKEY_VIEW_FILTER_PRIORITY_1 = "view.filter.priority.1"; - public static final String MSGKEY_VIEW_FILTER_PRIORITY_2 = "view.filter.priority.2"; - public static final String MSGKEY_VIEW_FILTER_PRIORITY_3 = "view.filter.priority.3"; - public static final String MSGKEY_VIEW_FILTER_PRIORITY_4 = "view.filter.priority.4"; - public static final String MSGKEY_VIEW_FILTER_PRIORITY_5 = "view.filter.priority.5"; - public static final String MSGKEY_VIEW_FILTER_PROJECT_PREFIX = "view.filter.project_prefix"; + public static final String VIEW_AST_DEFAULT_TEXT = "view.ast.default_text"; + + public static final String VIEW_FILTER_PRIORITY_1 = "view.filter.priority.1"; + public static final String VIEW_FILTER_PRIORITY_2 = "view.filter.priority.2"; + public static final String VIEW_FILTER_PRIORITY_3 = "view.filter.priority.3"; + public static final String VIEW_FILTER_PRIORITY_4 = "view.filter.priority.4"; + public static final String VIEW_FILTER_PRIORITY_5 = "view.filter.priority.5"; + public static final String VIEW_FILTER_PROJECT_PREFIX = "view.filter.project_prefix"; public static final String MSGKEY_VIEW_ACTION_CURRENT_PROJECT = "view.action.current_project"; - public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_1 = "view.tooltip.filter.priority.1"; - public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_2 = "view.tooltip.filter.priority.2"; - public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_3 = "view.tooltip.filter.priority.3"; - public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_4 = "view.tooltip.filter.priority.4"; - public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_5 = "view.tooltip.filter.priority.5"; - public static final String MSGKEY_VIEW_TOOLTIP_PACKAGES_FILES = "view.tooltip.packages_files"; - public static final String MSGKEY_VIEW_TOOLTIP_COLLAPSE_ALL = "view.tooltip.collapse_all"; + public static final String VIEW_TOOLTIP_FILTER_PRIORITY_1 = "view.tooltip.filter.priority.1"; + public static final String VIEW_TOOLTIP_FILTER_PRIORITY_2 = "view.tooltip.filter.priority.2"; + public static final String VIEW_TOOLTIP_FILTER_PRIORITY_3 = "view.tooltip.filter.priority.3"; + public static final String VIEW_TOOLTIP_FILTER_PRIORITY_4 = "view.tooltip.filter.priority.4"; + public static final String VIEW_TOOLTIP_FILTER_PRIORITY_5 = "view.tooltip.filter.priority.5"; + public static final String VIEW_TOOLTIP_PACKAGES_FILES = "view.tooltip.packages_files"; + public static final String VIEW_TOOLTIP_COLLAPSE_ALL = "view.tooltip.collapse_all"; public static final String MSGKEY_VIEW_COLUMN_MESSAGE = "view.column.message"; public static final String MSGKEY_VIEW_COLUMN_RULE = "view.column.rule"; @@ -320,16 +328,23 @@ public class StringKeys { public static final String MSGKEY_PRIORITY_WARNING = "priority.warning"; public static final String MSGKEY_PRIORITY_INFORMATION = "priority.information"; - public static final String MSGKEY_MONITOR_JOB_TITLE = "monitor.job_title"; - public static final String MSGKEY_MONITOR_CHECKING_FILE = "monitor.checking_file"; - public static final String MSGKEY_PMD_PROCESSING = "monitor.begintask"; - public static final String MSGKEY_MONITOR_UPDATING_PROJECTS = "monitor.updating_projects"; - public static final String MSGKEY_MONITOR_REVIEW = "monitor.review"; - public static final String MSGKEY_MONITOR_REMOVE_REVIEWS = "monitor.remove_reviews"; - public static final String MSGKEY_MONITOR_CALC_STATS_TASK = "monitor.calc_stats"; - public static final String MSGKEY_MONITOR_CALC_STATS_OF_PACKAGE = "monitor.calc_stats.package"; + public static final String MONITOR_JOB_TITLE = "monitor.job_title"; + public static final String MONITOR_CHECKING_FILE = "monitor.checking_file"; + public static final String PMD_PROCESSING = "monitor.begintask"; + public static final String MONITOR_UPDATING_PROJECTS = "monitor.updating_projects"; + public static final String MONITOR_REVIEW = "monitor.review"; + public static final String MONITOR_REMOVE_REVIEWS = "monitor.remove_reviews"; + public static final String MONITOR_CALC_STATS_TASK = "monitor.calc_stats"; + public static final String MONITOR_CALC_STATS_OF_PACKAGE = "monitor.calc_stats.package"; public static final String MSGKEY_MONITOR_COLLECTING_MARKERS = "monitor.collect_markers"; + public static final String PRIORITY_COLUMN_NAME = "priority.column.name"; + public static final String PRIORITY_COLUMN_VALUE = "priority.column.value"; + public static final String PRIORITY_COLUMN_SIZE = "priority.column.size"; + public static final String PRIORITY_COLUMN_SHAPE = "priority.column.shape"; + public static final String PRIORITY_COLUMN_COLOR = "priority.column.color"; + public static final String PRIORITY_COLUMN_DESC = "priority.column.description"; + /** * This class is not meant to be instanciated * diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java index 557d48df8f6..7dcd46f0f67 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java @@ -2,18 +2,40 @@ import java.text.MessageFormat; import java.util.Date; +import java.util.List; +import java.util.Set; +import net.sourceforge.pmd.RulePriority; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; +import net.sourceforge.pmd.eclipse.plugin.UISettings; +import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; +import net.sourceforge.pmd.eclipse.ui.Shape; +import net.sourceforge.pmd.eclipse.ui.ShapePicker; +import net.sourceforge.pmd.eclipse.ui.model.RootRecord; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityDescriptorCache; import org.apache.log4j.Level; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.jface.preference.ColorSelector; import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -24,6 +46,8 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Spinner; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; @@ -41,7 +65,8 @@ public class GeneralPreferencesPage extends PreferencePage implements IWorkbenchPreferencePage { private static final String[] LOG_LEVELS = { "OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "ALL" }; - + private static final RGB SHAPE_COLOR = new RGB(255,255,255); + private Text additionalCommentText; private Label sampleLabel; private Button showPerspectiveBox; @@ -53,7 +78,8 @@ public class GeneralPreferencesPage extends PreferencePage implements IWorkbench private Scale logLevelScale; private Label logLevelValueLabel; private Button browseButton; - + private TableViewer tableViewer; + /** * Initialize the page * @@ -61,7 +87,7 @@ public class GeneralPreferencesPage extends PreferencePage implements IWorkbench */ public void init(IWorkbench arg0) { setDescription(getMessage(StringKeys.MSGKEY_PREF_GENERAL_TITLE)); - this.preferences = PMDPlugin.getDefault().loadPreferences(); + preferences = PMDPlugin.getDefault().loadPreferences(); } /** @@ -77,13 +103,15 @@ protected Control createContents(Composite parent) { layout.verticalSpacing = 10; composite.setLayout(layout); - // Create chidls + // Create groups Group generalGroup = buildGeneralGroup(composite); + Group priorityGroup = buildPriorityGroup(composite); Group reviewGroup = buildReviewGroup(composite); Group logGroup = buildLoggingGroup(composite); // Layout children generalGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + priorityGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); logGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData data = new GridData(); @@ -96,7 +124,7 @@ protected Control createContents(Composite parent) { /** * Build the group of general preferences - * @param parent the parent composte + * @param parent the parent composite * @return the group widget */ private Group buildGeneralGroup(final Composite parent) { @@ -131,11 +159,154 @@ private Group buildGeneralGroup(final Composite parent) { data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; - this.maxViolationsPerFilePerRule.setLayoutData(data); + maxViolationsPerFilePerRule.setLayoutData(data); return group; } + + /** + * Build the group of priority preferences + * @param parent the parent composite + * @return the group widget + */ + private Group buildPriorityGroup(final Composite parent) { + Group group = new Group(parent, SWT.SHADOW_IN); + group.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_GROUP_PRIORITIES)); + group.setLayout(new GridLayout(1, false)); + + IStructuredContentProvider contentProvider = new IStructuredContentProvider() { + public void dispose() { } + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } + public Object[] getElements(Object inputElement) { return (RulePriority[])inputElement; } + }; + PriorityTableLabelProvider labelProvider = new PriorityTableLabelProvider(PriorityColumnDescriptor.VisibleColumns); + + tableViewer = new TableViewer(group, SWT.BORDER | SWT.MULTI); + Table table = tableViewer.getTable(); + table.setLayoutData( new GridData(GridData.BEGINNING, GridData.CENTER, true, true) ); + + tableViewer.setLabelProvider(labelProvider); + tableViewer.setContentProvider(contentProvider); + table.setHeaderVisible(true); + labelProvider.addColumnsTo(table); + tableViewer.setInput( UISettings.currentPriorities(true) ); + + TableColumn[] columns = table.getColumns(); + for (TableColumn column : columns) column.pack(); + + GridData data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; + table.setLayoutData(data); + + Composite editorPanel = new Composite(group, SWT.None); + editorPanel.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, true, true) ); + editorPanel.setLayout(new GridLayout(6, false)); + + Label shapeLabel = new Label(editorPanel, SWT.None); + shapeLabel.setLayoutData( new GridData()); + shapeLabel.setText("Shape:"); + + final ShapePicker<Shape> ssc = new ShapePicker<Shape>(editorPanel, SWT.None, 14); + ssc.setLayoutData( new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); + ssc.setSize(280, 30); + ssc.setShapeMap(UISettings.shapeSet(SHAPE_COLOR, 10)); + ssc.setItems( UISettings.allShapes() ); + + Label colourLabel = new Label(editorPanel, SWT.None); + colourLabel.setLayoutData( new GridData()); + colourLabel.setText("Color:"); + + final ColorSelector colorPicker = new ColorSelector(editorPanel); + + Label nameLabel = new Label(editorPanel, SWT.None); + nameLabel.setLayoutData( new GridData()); + nameLabel.setText("Name:"); + + final Text priorityName = new Text(editorPanel, SWT.BORDER); + priorityName.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, true, true) ); + + final Label descLabel = new Label(editorPanel, SWT.None); + descLabel.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, false, true, 1, 1)); + descLabel.setText("Description:"); + + final Text priorityDesc = new Text(editorPanel, SWT.BORDER); + priorityDesc.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, true, true, 5, 1) ); + + tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + IStructuredSelection selection = (IStructuredSelection)event.getSelection(); + selectedPriorities(selection.toList(), ssc, colorPicker, priorityName); + }} ); + + ssc.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + IStructuredSelection selection = (IStructuredSelection)event.getSelection(); + setShape((Shape)selection.getFirstElement()); + }} ); + + colorPicker.addListener(new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + setColor((RGB)event.getNewValue()); + }} ); + + priorityName.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent me) { + setName( priorityName.getText() ); + }} ); + + return group; + } + + private void setShape(Shape shape) { + + if (shape == null) return; // renderers can't handle this + + for (PriorityDescriptor pd : selectedDescriptors()) { + pd.shape.shape = shape; + } + tableViewer.refresh(); + } + + private void setColor(RGB clr) { + for (PriorityDescriptor pd : selectedDescriptors()) { + pd.shape.rgbColor = clr; + } + tableViewer.refresh(); + } + + private void setName(String newName) { + for (PriorityDescriptor pd : selectedDescriptors()) { + pd.label = newName; + } + tableViewer.refresh(); + } + + private PriorityDescriptor[] selectedDescriptors() { + + Object[] items = ((IStructuredSelection)tableViewer.getSelection()).toArray(); + PriorityDescriptor[] descs = new PriorityDescriptor[items.length]; + for (int i=0; i<descs.length; i++) descs[i] = PriorityDescriptorCache.instance.descriptorFor((RulePriority)items[i]); + return descs; + } + + private static void selectedPriorities(List<RulePriority> items, ShapePicker<Shape> ssc, ColorSelector colorPicker, Text nameField) { + + if (items.size() != 1 ) { + ssc.setSelection((Shape)null); + nameField.setText(""); + return; + } + + RulePriority priority = items.get(0); + PriorityDescriptor desc = PriorityDescriptorCache.instance.descriptorFor(priority); + + ssc.setSelection( desc.shape.shape ); + nameField.setText(priority.getName()); + colorPicker.setColorValue( desc.shape.rgbColor ); + } + /** * Build the group of review preferences * @param parent the parent composite @@ -212,14 +383,14 @@ private Group buildLoggingGroup(Composite parent) { logFileNameLabel.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_LABEL_LOG_FILE_NAME)); logFileNameLabel.setLayoutData(gridData); - this.logFileNameText = new Text(loggingGroup, SWT.BORDER); - this.logFileNameText.setText(this.preferences.getLogFileName()); - this.logFileNameText.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_TOOLTIP_LOG_FILE_NAME)); - this.logFileNameText.setLayoutData(gridData1); + logFileNameText = new Text(loggingGroup, SWT.BORDER); + logFileNameText.setText(this.preferences.getLogFileName()); + logFileNameText.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_TOOLTIP_LOG_FILE_NAME)); + logFileNameText.setLayoutData(gridData1); - this.browseButton = new Button(loggingGroup, SWT.NONE); - this.browseButton.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_BUTTON_BROWSE)); - this.browseButton.addSelectionListener(new SelectionListener() { + browseButton = new Button(loggingGroup, SWT.NONE); + browseButton.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_BUTTON_BROWSE)); + browseButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { browseLogFile(); } @@ -234,15 +405,15 @@ public void widgetDefaultSelected(SelectionEvent event) { Label logLevelLabel = new Label(loggingGroup, SWT.NONE); logLevelLabel.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_LABEL_LOG_LEVEL)); - this.logLevelValueLabel = new Label(loggingGroup, SWT.NONE); - this.logLevelValueLabel.setText(""); - this.logLevelValueLabel.setLayoutData(gridData2); + logLevelValueLabel = new Label(loggingGroup, SWT.NONE); + logLevelValueLabel.setText(""); + logLevelValueLabel.setLayoutData(gridData2); - this.logLevelScale = new Scale(loggingGroup, SWT.NONE); - this.logLevelScale.setMaximum(6); - this.logLevelScale.setPageIncrement(1); - this.logLevelScale.setLayoutData(gridData3); - this.logLevelScale.addSelectionListener(new SelectionListener() { + logLevelScale = new Scale(loggingGroup, SWT.NONE); + logLevelScale.setMaximum(6); + logLevelScale.setPageIncrement(1); + logLevelScale.setLayoutData(gridData3); + logLevelScale.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { updateLogLevelValueLabel(); } @@ -251,7 +422,7 @@ public void widgetDefaultSelected(SelectionEvent event) { } }); - this.logLevelScale.setSelection(intLogLevel(this.preferences.getLogLevel())); + logLevelScale.setSelection(intLogLevel(this.preferences.getLogLevel())); updateLogLevelValueLabel(); return loggingGroup; @@ -357,32 +528,32 @@ private Button buildReviewPmdStyleBoxButton(final Composite parent) { * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ protected void performDefaults() { - if (this.additionalCommentText != null) { - this.additionalCommentText.setText(IPreferences.REVIEW_ADDITIONAL_COMMENT_DEFAULT); + if (additionalCommentText != null) { + additionalCommentText.setText(IPreferences.REVIEW_ADDITIONAL_COMMENT_DEFAULT); } - if (this.showPerspectiveBox != null) { - this.showPerspectiveBox.setSelection(IPreferences.PMD_PERSPECTIVE_ENABLED_DEFAULT); + if (showPerspectiveBox != null) { + showPerspectiveBox.setSelection(IPreferences.PMD_PERSPECTIVE_ENABLED_DEFAULT); } - if (this.useProjectBuildPath != null) { - this.useProjectBuildPath.setSelection(IPreferences.PROJECT_BUILD_PATH_ENABLED_DEFAULT); + if (useProjectBuildPath != null) { + useProjectBuildPath.setSelection(IPreferences.PROJECT_BUILD_PATH_ENABLED_DEFAULT); } - if (this.maxViolationsPerFilePerRule != null) { - this.maxViolationsPerFilePerRule.setMinimum(IPreferences.MAX_VIOLATIONS_PFPR_DEFAULT); + if (maxViolationsPerFilePerRule != null) { + maxViolationsPerFilePerRule.setMinimum(IPreferences.MAX_VIOLATIONS_PFPR_DEFAULT); } - if (this.reviewPmdStyleBox !=null) { - this.reviewPmdStyleBox.setSelection(IPreferences.REVIEW_PMD_STYLE_ENABLED_DEFAULT); + if (reviewPmdStyleBox !=null) { + reviewPmdStyleBox.setSelection(IPreferences.REVIEW_PMD_STYLE_ENABLED_DEFAULT); } - if (this.logFileNameText != null) { - this.logFileNameText.setText(IPreferences.LOG_FILENAME_DEFAULT); + if (logFileNameText != null) { + logFileNameText.setText(IPreferences.LOG_FILENAME_DEFAULT); } - if (this.logLevelScale != null) { - this.logLevelScale.setSelection(intLogLevel(IPreferences.LOG_LEVEL)); + if (logLevelScale != null) { + logLevelScale.setSelection(intLogLevel(IPreferences.LOG_LEVEL)); updateLogLevelValueLabel(); } } @@ -422,44 +593,67 @@ protected void browseLogFile() { dialog.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_DIALOG_BROWSE)); String fileName = dialog.open(); if (fileName != null) { - this.logFileNameText.setText(fileName); + logFileNameText.setText(fileName); } } + private void updateMarkerIcons() { + + if (!PriorityDescriptorCache.instance.hasChanges()) { + return; + } + + // TODO show in UI...could take a while to update + + PriorityDescriptorCache.instance.storeInPreferences(); + UISettings.createRuleMarkerIcons(getShell().getDisplay()); + UISettings.reloadPriorities(); + + // ensure that the decorator gets these new images... + PMDPlugin.getDefault().ruleLabelDecorator().reloadDecorators(); + + RootRecord root = new RootRecord(ResourcesPlugin.getWorkspace().getRoot()); + Set<IFile> files = MarkerUtil.allMarkedFiles(root); + PMDPlugin.getDefault().changedFiles(files); + } + /** * @see org.eclipse.jface.preference.IPreferencePage#performOk() */ public boolean performOk() { - if (this.additionalCommentText != null) { - this.preferences.setReviewAdditionalComment(this.additionalCommentText.getText()); + + updateMarkerIcons(); + + if (additionalCommentText != null) { + preferences.setReviewAdditionalComment(additionalCommentText.getText()); } - if (this.showPerspectiveBox != null) { - this.preferences.setPmdPerspectiveEnabled(this.showPerspectiveBox.getSelection()); + if (showPerspectiveBox != null) { + preferences.setPmdPerspectiveEnabled(showPerspectiveBox.getSelection()); } - if (this.useProjectBuildPath != null) { - this.preferences.setProjectBuildPathEnabled(this.useProjectBuildPath.getSelection()); + if (useProjectBuildPath != null) { + preferences.setProjectBuildPathEnabled(useProjectBuildPath.getSelection()); } - if (this.maxViolationsPerFilePerRule != null) { - this.preferences.setMaxViolationsPerFilePerRule(Integer.valueOf(this.maxViolationsPerFilePerRule.getText()).intValue()); + if (maxViolationsPerFilePerRule != null) { + preferences.setMaxViolationsPerFilePerRule(Integer.valueOf(maxViolationsPerFilePerRule.getText()).intValue()); } - if (this.reviewPmdStyleBox != null) { - this.preferences.setReviewPmdStyleEnabled(this.reviewPmdStyleBox.getSelection()); + if (reviewPmdStyleBox != null) { + preferences.setReviewPmdStyleEnabled(reviewPmdStyleBox.getSelection()); } - if (this.logFileNameText != null) { - this.preferences.setLogFileName(this.logFileNameText.getText()); + if (logFileNameText != null) { + preferences.setLogFileName(logFileNameText.getText()); } - if (this.logLevelScale != null) { - this.preferences.setLogLevel(Level.toLevel(LOG_LEVELS[this.logLevelScale.getSelection()])); + if (logLevelScale != null) { + preferences.setLogLevel(Level.toLevel(LOG_LEVELS[logLevelScale.getSelection()])); } - this.preferences.sync(); - PMDPlugin.getDefault().applyLogPreferences(this.preferences); + preferences.sync(); + PMDPlugin.getDefault().applyLogPreferences(preferences); return true; } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityColumnDescriptor.java new file mode 100755 index 00000000000..c015b52718b --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityColumnDescriptor.java @@ -0,0 +1,41 @@ +package net.sourceforge.pmd.eclipse.ui.preferences; + +import net.sourceforge.pmd.RulePriority; +import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +import net.sourceforge.pmd.eclipse.ui.preferences.br.AbstractColumnDescriptor; +import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityFieldAccessor; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; + +/** + * + * @author Brian Remedios + */ +public class PriorityColumnDescriptor extends AbstractColumnDescriptor { + + private PriorityFieldAccessor<?> accessor; + + public PriorityColumnDescriptor(String labelKey, int theAlignment, int theWidth, boolean resizableFlag, PriorityFieldAccessor<?> theAccessor) { + super(labelKey, theAlignment, theWidth, resizableFlag, null); + + accessor = theAccessor; + } + + protected Object valueFor(RulePriority priority) { + return accessor.valueFor(priority); + } + + protected Image imageFor(RulePriority priority) { + return accessor.imageFor(priority); + } + + public static final PriorityColumnDescriptor name = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_NAME, SWT.LEFT, 25, true, PriorityFieldAccessor.name); + public static final PriorityColumnDescriptor value = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_VALUE, SWT.RIGHT, 25, true, PriorityFieldAccessor.value); +// public static final PriorityColumnDescriptor size = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_SIZE, SWT.RIGHT, 25, true, PriorityFieldAccessor.size); + public static final PriorityColumnDescriptor image = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_SHAPE, SWT.CENTER, 25, true, PriorityFieldAccessor.image); +// public static final PriorityColumnDescriptor color = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_COLOR, SWT.RIGHT, 25, true, PriorityFieldAccessor.color); + public static final PriorityColumnDescriptor description = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_DESC, SWT.LEFT, 25, true, PriorityFieldAccessor.description); + + public static final PriorityColumnDescriptor[] VisibleColumns = new PriorityColumnDescriptor[] { image, name, value, description }; +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityTableLabelProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityTableLabelProvider.java new file mode 100755 index 00000000000..aae651f48f0 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityTableLabelProvider.java @@ -0,0 +1,42 @@ +package net.sourceforge.pmd.eclipse.ui.preferences; + +import net.sourceforge.pmd.RulePriority; + +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Table; + +/** + * + * @author Brian Remedios + */ +public class PriorityTableLabelProvider extends AbstractTableLabelProvider { + + private final PriorityColumnDescriptor[] columns; + + public PriorityTableLabelProvider(PriorityColumnDescriptor[] theColumns) { + columns = theColumns; + } + + + public boolean isLabelProperty(Object element, String property) { + return false; + } + + public Image getColumnImage(Object element, int columnIndex) { + + return columns[columnIndex].imageFor((RulePriority)element); + } + + public String getColumnText(Object element, int columnIndex) { + + Object value = columns[columnIndex].valueFor((RulePriority)element); + return value == null ? null : value.toString(); + } + + public void addColumnsTo(Table table) { + + for (PriorityColumnDescriptor desc : columns) { + desc.buildTableColumn(table); + } + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java index 44c32082021..1cf26a16bb1 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java @@ -9,6 +9,7 @@ import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; import net.sourceforge.pmd.eclipse.plugin.UISettings; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleUtil; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.lang.rule.XPathRule; import net.sourceforge.pmd.util.StringUtil; @@ -635,16 +636,18 @@ private Text buildXPathText(Composite parent) { } if (mode == MODE_EDIT) { - if (this.editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { - text.setText(this.editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); + //if (editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { + if (RuleUtil.isXPathRule(editedRule)) { + text.setText(editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); text.setEditable(true); } } if (mode == MODE_VIEW) { text.setEditable(false); - if (this.editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { - text.setText(this.editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); + //if (editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { + if (RuleUtil.isXPathRule(editedRule)) { + text.setText(editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java index e4e5c5d8805..6e16c210083 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java @@ -3,6 +3,8 @@ import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; import net.sourceforge.pmd.eclipse.util.ResourceManager; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; @@ -41,7 +43,7 @@ public AbstractColumnDescriptor(String labelKey, int theAlignment, int theWidth, */ public String tooltip() { return tooltip; } - protected TreeColumn buildTreeColumn(Tree parent, final RuleSortListener sortListener) { + protected TreeColumn buildTreeColumn(Tree parent) { final TreeColumn tc = new TreeColumn(parent, alignment); tc.setWidth(width); @@ -51,4 +53,16 @@ protected TreeColumn buildTreeColumn(Tree parent, final RuleSortListener sortLis return tc; } + + public TableColumn buildTableColumn(Table parent) { + + final TableColumn tc = new TableColumn(parent, alignment); + tc.setText(label); + tc.setWidth(width); + tc.setResizable(isResizable); + tc.setToolTipText(tooltip); + if (imagePath != null) tc.setImage(ResourceManager.imageFor(imagePath)); + + return tc; + } } \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java index 1e174f42bbe..bb2b4c7e51d 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java @@ -27,7 +27,7 @@ protected AbstractRuleColumnDescriptor(String labelKey, int theAlignment, int th protected TreeColumn buildTreeColumn(Tree parent, final RuleSortListener sortListener) { - TreeColumn tc = super.buildTreeColumn(parent, sortListener); + TreeColumn tc = super.buildTreeColumn(parent); tc.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java index c3c2269dbfe..87978a166a8 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java @@ -50,7 +50,6 @@ public abstract class AbstractTreeTableManager { private final Set<String> hiddenColumnNames; -// private Button sortByCheckedButton; private Button selectAllButton; private Button unSelectAllButton; private IPreferences preferences; @@ -307,7 +306,6 @@ protected void isActive(String item, boolean flag) { protected void buildCheckButtons(Composite parent) { - // sortByCheckedButton = buildSortByCheckedItemsButton(parent); selectAllButton = buildSelectAllButton(parent); unSelectAllButton = buildUnselectAllButton(parent); } @@ -434,7 +432,6 @@ protected void updateButtonsFor(int[] selectionRatio) { selectAllButton.setEnabled( selectionRatio[0] < selectionRatio[1]); unSelectAllButton.setEnabled( selectionRatio[0] > 0); -// sortByCheckedButton.setEnabled( (selectionRatio[0] != 0) && (selectionRatio[0] != selectionRatio[1])); } protected abstract void updateCheckControls(); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java index e3c885994e6..e505d48fe09 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java @@ -1,9 +1,12 @@ package net.sourceforge.pmd.eclipse.ui.preferences.br; +/** + * + * @author Brian Remedios + */ public interface ColumnDescriptor { - public abstract String label(); - - public abstract String tooltip(); + String label(); + String tooltip(); } \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java index c643ed556ce..3f0ef7cc9b8 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java @@ -26,5 +26,5 @@ public int compareTo(IndexedString other) { deltaLength; } - public static final IndexedString Empty = new IndexedString("", Collections.EMPTY_LIST); + public static final IndexedString Empty = new IndexedString(""); } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage.java deleted file mode 100644 index 44812b3ca50..00000000000 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage.java +++ /dev/null @@ -1,1490 +0,0 @@ -package net.sourceforge.pmd.eclipse.ui.preferences.br; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -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.Set; - -import net.sourceforge.pmd.PropertyDescriptor; -import net.sourceforge.pmd.Rule; -import net.sourceforge.pmd.RulePriority; -import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.eclipse.runtime.preferences.impl.PreferenceUIStore; -import net.sourceforge.pmd.eclipse.runtime.writer.IRuleSetWriter; -import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; -import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; -import net.sourceforge.pmd.eclipse.ui.preferences.RuleDialog; -import net.sourceforge.pmd.eclipse.ui.preferences.RuleSetSelectionDialog; -import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.AbstractRulePanelManager; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.Configuration; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.DescriptionPanelManager; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.EditorUsageMode; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ExamplePanelManager; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ExclusionPanelManager; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.PerRulePropertyPanelManager; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.QuickFixPanelManager; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.RulePropertyManager; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.XPathPanelManager; -import net.sourceforge.pmd.eclipse.util.ResourceManager; -import net.sourceforge.pmd.eclipse.util.Util; -import net.sourceforge.pmd.util.FileUtil; -import net.sourceforge.pmd.util.StringUtil; -import net.sourceforge.pmd.util.designer.Designer; - -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.jface.dialogs.InputDialog; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.dialogs.ProgressMonitorDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.CheckboxTreeViewer; -import org.eclipse.jface.viewers.ICheckStateProvider; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.layout.RowLayout; -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.Event; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.MenuItem; -import org.eclipse.swt.widgets.Sash; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeColumn; -import org.eclipse.swt.widgets.TreeItem; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer; - -/** - * This page is used to modify preferences only. They are stored in the preference store that belongs to - * the main plug-in class. That way, preferences can be accessed directly via the preference store. - * - * @author Philippe Herlin - * @author Brian Remedios - */ - -public class PMDPreferencePage extends AbstractPMDPreferencePage implements ValueChangeListener, RuleSortListener { - - public static PMDPreferencePage activeInstance = null; - - // columns shown in the rule treetable in the desired order - private static final RuleColumnDescriptor[] availableColumns = new RuleColumnDescriptor[] { - TextColumnDescriptor.name, - //TextColumnDescriptor.priorityName, - IconColumnDescriptor.priority, - TextColumnDescriptor.fixCount, - TextColumnDescriptor.since, - TextColumnDescriptor.ruleSetName, - TextColumnDescriptor.ruleType, - TextColumnDescriptor.minLangVers, - TextColumnDescriptor.maxLangVers, - TextColumnDescriptor.language, - ImageColumnDescriptor.filterViolationRegex, // regex text -> compact color squares (for comparison) - ImageColumnDescriptor.filterViolationXPath, // xpath text -> compact color circles (for comparison) - TextColumnDescriptor.properties, - }; - - // last item in this list is the grouping used at startup - private static final Object[][] groupingChoices = new Object[][] { - { TextColumnDescriptor.ruleSetName, StringKeys.MSGKEY_PREF_RULESET_COLUMN_RULESET}, - { TextColumnDescriptor.since, StringKeys.MSGKEY_PREF_RULESET_GROUPING_PMD_VERSION }, - { TextColumnDescriptor.priorityName, StringKeys.MSGKEY_PREF_RULESET_COLUMN_PRIORITY }, - { TextColumnDescriptor.ruleType, StringKeys.MSGKEY_PREF_RULESET_COLUMN_RULE_TYPE }, - { TextColumnDescriptor.language, StringKeys.MSGKEY_PREF_RULESET_COLUMN_LANGUAGE }, - { ImageColumnDescriptor.filterViolationRegex, StringKeys.MSGKEY_PREF_RULESET_GROUPING_REGEX }, - { null, StringKeys.MSGKEY_PREF_RULESET_GROUPING_NONE } - }; - -// private static final int RuleTableFraction = 55; // percent of screen height vs property tabs - - private ContainerCheckedTreeViewer ruleTreeViewer; - private Button addRuleButton; - private Button removeRuleButton; - private RuleSet ruleSet; - private TabFolder tabFolder; -// private final Set<Rule> checkedRules = new HashSet<Rule>(); - private Menu ruleListMenu; - private Set<String> hiddenColumnNames = new HashSet<String>(); - - private RulePropertyManager[] rulePropertyManagers; - - private boolean sortDescending; - private RuleFieldAccessor columnSorter = RuleFieldAccessor.name; // initial sort - private RuleColumnDescriptor groupingColumn; - - private Map<Integer, List<Listener>> paintListeners = new HashMap<Integer, List<Listener>>(); - - private RuleSelection ruleSelection; // may hold rules and/or group nodes - private Map<RulePriority, MenuItem> priorityMenusByPriority; - private Map<String, MenuItem> rulesetMenusByName; - - private RuleFieldAccessor checkedColumnAccessor; - - private Button sortByCheckedButton; - private Button selectAllButton; - private Button unSelectAllButton; - - /** - * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - super.init(workbench); - - activeInstance = this; - - hiddenColumnNames = PreferenceUIStore.instance.hiddenColumnNames(); - - checkedColumnAccessor = createCheckedItemAccessor(); - } - - private RuleFieldAccessor createCheckedItemAccessor() { - - return new BasicRuleFieldAccessor() { - public Comparable<Boolean> valueFor(Rule rule) { - return preferences.isActive(rule.getName()); - } - }; - } - - private void sortByCheckedItems() { - sortBy(checkedColumnAccessor, ruleTreeViewer.getTree().getColumn(0)); - } - - - protected String descriptionId() { - return StringKeys.MSGKEY_PREF_RULESET_TITLE; - } - /** - * @see org.eclipse.jface.preference.PreferencePage#performDefaults() - */ - @Override - protected void performDefaults() { - populateRuleTable(); - super.performDefaults(); - } - - private void storeActiveRules() { - - Object[] chosenRules = ruleTreeViewer.getCheckedElements(); - for (Object item : chosenRules) { - if (item instanceof Rule) { - preferences.isActive(((Rule)item).getName(), true); - } - } - - System.out.println("Active rules: " + preferences.getActiveRuleNames()); - } - - /** - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - @Override - public boolean performOk() { - - saveRuleSelections(); - PreferenceUIStore.instance.save(); - - if (isModified()) { - updateRuleSet(); - rebuildProjects(); - storeActiveRules(); - } - - return super.performOk(); - } - - @Override - public boolean performCancel() { - - saveRuleSelections(); - PreferenceUIStore.instance.save(); - return super.performCancel(); - } - - private void restoreSavedRuleSelections() { - - Set<String> names = PreferenceUIStore.instance.selectedRuleNames(); - List<Rule> rules = new ArrayList<Rule>(); - for (String name : names) rules.add(ruleSet.getRuleByName(name)); - - IStructuredSelection selection = new StructuredSelection(rules); - ruleTreeViewer.setSelection(selection); - } - - private void saveRuleSelections() { - - IStructuredSelection selection = (IStructuredSelection)ruleTreeViewer.getSelection(); - - List<String> ruleNames = new ArrayList<String>(); - for (Object item : selection.toList()) { - if (item instanceof Rule) - ruleNames.add(((Rule)item).getName()); - } - - PreferenceUIStore.instance.selectedRuleNames(ruleNames); - } - - /** - * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite) - */ - @Override - protected Control createContents(Composite parent) { - - populateRuleset(); - - Composite composite = new Composite(parent, SWT.NULL); - layoutControls(composite); - - restoreSavedRuleSelections(); - updateCheckButtons(); - - return composite; - } - - private Composite createRuleSection(Composite parent) { - - Composite ruleSection = new Composite(parent, SWT.NULL); - - // Create the controls (order is important !) - Composite groupCombo = buildGroupCombo(ruleSection, StringKeys.MSGKEY_PREF_RULESET_RULES_GROUPED_BY); - - Tree ruleTree = buildRuleTreeViewer(ruleSection); - groupBy(null); - - Composite ruleTableButtons = buildRuleTableButtons(ruleSection); - Composite rulePropertiesTableButtons = buildRulePropertiesTableButtons(ruleSection); - - // Place controls on the layout - GridLayout gridLayout = new GridLayout(3, false); - ruleSection.setLayout(gridLayout); - - GridData data = new GridData(); - data.horizontalSpan = 3; - groupCombo.setLayoutData(data); - - data = new GridData(); - data.heightHint = 200; data.widthHint = 350; - data.horizontalSpan = 1; - data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; - data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; - ruleTree.setLayoutData(data); - - data = new GridData(); - data.horizontalSpan = 1; - data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; - ruleTableButtons.setLayoutData(data); - - data = new GridData(); - data.horizontalSpan = 1; - data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; - rulePropertiesTableButtons.setLayoutData(data); - - return ruleSection; - } - - private int[] selectionRatioIn(Rule[] rules) { - - int selectedCount = 0; - for (Rule rule : rules) { - if (preferences.isActive(rule.getName())) selectedCount++; - } - return new int[] { selectedCount , rules.length }; - } - - private ICheckStateProvider createCheckStateProvider() { - - return new ICheckStateProvider() { - - public boolean isChecked(Object item) { - if (item instanceof Rule) { - return preferences.isActive(((Rule)item).getName()); - } else { - if (item instanceof RuleGroup) { - int[] fraction = selectionRatioIn(((RuleGroup)item).rules()); - return (fraction[0] > 0) && (fraction[0] == fraction[1]); - } - } - return false; // should never get here - } - - public boolean isGrayed(Object item) { - - if (item instanceof Rule) return false; - if (item instanceof RuleGroup) { - int[] fraction = selectionRatioIn(((RuleGroup)item).rules()); - return (fraction[0] > 0) && (fraction[0] != fraction[1]); - } - return false; - } - - }; - } - - /** - * Main layout - * @param parent Composite - */ - private void layoutControls(Composite parent) { - - parent.setLayout(new FormLayout()); - int ruleTableFraction = 55; //PreferenceUIStore.instance.tableFraction(); - - // Create the sash first, so the other controls can be attached to it. - final Sash sash = new Sash(parent, SWT.HORIZONTAL); - FormData data = new FormData(); - data.left = new FormAttachment(0, 0); // attach to left - data.right = new FormAttachment(100, 0); // attach to right - data.top = new FormAttachment(ruleTableFraction, 0); - sash.setLayoutData(data); - sash.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - // Re-attach to the top edge, and we use the y value of the event to determine the offset from the top - ((FormData)sash.getLayoutData()).top = new FormAttachment(0, event.y); -// PreferenceUIStore.instance.tableFraction(event.y); - sash.getParent().layout(); - } - }); - - // Create the first text box and attach its bottom edge to the sash - Composite ruleSection = createRuleSection(parent); - data = new FormData(); - data.top = new FormAttachment(0, 0); - data.bottom = new FormAttachment(sash, 0); - data.left = new FormAttachment(0, 0); - data.right = new FormAttachment(100, 0); - ruleSection.setLayoutData(data); - - // Create the second text box and attach its top edge to the sash - TabFolder propertySection = buildTabFolder(parent); - data = new FormData(); - data.top = new FormAttachment(sash, 0); - data.bottom = new FormAttachment(100, 0); - data.left = new FormAttachment(0, 0); - data.right = new FormAttachment(100, 0); - propertySection.setLayoutData(data); - } - - public static String ruleSetNameFrom(Rule rule) { - return ruleSetNameFrom( rule.getRuleSetName() ); - } - - public static String ruleSetNameFrom(String rulesetName) { - - int pos = rulesetName.toUpperCase().indexOf("RULES"); - return pos < 0 ? rulesetName : rulesetName.substring(0, pos-1); - } - - private TreeColumn columnFor(String tooltipText) { - for (TreeColumn column : ruleTreeViewer.getTree().getColumns()) { - if (column.getToolTipText().equals(tooltipText)) return column; - } - return null; - } - - private void redrawTable() { - redrawTable("-", -1); - } - - private void redrawTable(String sortColumnLabel, int sortDir) { - groupBy(groupingColumn); - - TreeColumn sortColumn = columnFor(sortColumnLabel); - ruleTreeViewer.getTree().setSortColumn(sortColumn); - ruleTreeViewer.getTree().setSortDirection(sortDir); - } - - private void updateCheckButtons() { - - Rule[] rules = new Rule[ruleSet.size()]; - rules = ruleSet.getRules().toArray(rules); - int[] selectionRatio = selectionRatioIn(rules); - - selectAllButton.setEnabled( selectionRatio[0] < selectionRatio[1]); - unSelectAllButton.setEnabled( selectionRatio[0] > 0); - sortByCheckedButton.setEnabled( (selectionRatio[0] != 0) && (selectionRatio[0] != selectionRatio[1])); - } - - private Composite buildGroupCombo(Composite parent, String comboLabelKey) { - - Composite panel = new Composite(parent, 0); - GridLayout layout = new GridLayout(5, false); - panel.setLayout(layout); - - sortByCheckedButton = buildSortByCheckedItemsButton(panel); - selectAllButton = buildSelectAllButton(panel); - unSelectAllButton = buildUnselectAllButton(panel); - - Label label = new Label(panel, 0); - GridData data = new GridData(); - data.horizontalAlignment = SWT.LEFT; - data.verticalAlignment = SWT.CENTER; - label.setLayoutData(data); - label.setText(SWTUtil.stringFor(comboLabelKey)); - - final Combo combo = new Combo(panel, SWT.READ_ONLY); - combo.setItems(SWTUtil.i18lLabelsIn(groupingChoices, 1)); - combo.select(groupingChoices.length - 1); // picks last one by default TODO make it a persistent preference - - combo.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - int selectionIdx = combo.getSelectionIndex(); - Object[] choice = groupingChoices[selectionIdx]; - groupingColumn = (RuleColumnDescriptor)choice[0]; - redrawTable(); - } - }); - - return panel; - } - - /** - * Method buildTabFolder. - * @param parent Composite - * @return TabFolder - */ - private TabFolder buildTabFolder(Composite parent) { - - tabFolder = new TabFolder(parent, SWT.TOP); - - rulePropertyManagers = new RulePropertyManager[] { - buildDescriptionTab(tabFolder, 0, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_DESCRIPTION)), - buildPropertyTab(tabFolder, 1, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_PROPERTIES)), - buildUsageTab(tabFolder, 2, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FILTERS)), - buildXPathTab(tabFolder, 3, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_XPATH)), - buildQuickFixTab(tabFolder, 4, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FIXES)), - buildExampleTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_EXAMPLES)), - }; - - tabFolder.pack(); - return tabFolder; - } - - /** - * @param parent TabFolder - * @param index int - */ - private RulePropertyManager buildPropertyTab(TabFolder parent, int index, String title) { - - TabItem tab = new TabItem(parent, 0, index); - tab.setText(title); - - PerRulePropertyPanelManager manager = new PerRulePropertyPanelManager(title, EditorUsageMode.Editing, this); - tab.setControl( - manager.setupOn(parent) - ); - manager.tab(tab); - return manager; - } - - /** - * @param parent TabFolder - * @param index int - */ - private RulePropertyManager buildDescriptionTab(TabFolder parent, int index, String title) { - - TabItem tab = new TabItem(parent, 0, index); - tab.setText(title); - - DescriptionPanelManager manager = new DescriptionPanelManager(title, EditorUsageMode.Editing, this); - tab.setControl( - manager.setupOn(parent) - ); - manager.tab(tab); - return manager; - } - - /** - * @param parent TabFolder - * @param index int - */ - private RulePropertyManager buildXPathTab(TabFolder parent, int index, String title) { - - TabItem tab = new TabItem(parent, 0, index); - tab.setText(title); - - XPathPanelManager manager = new XPathPanelManager(title, EditorUsageMode.Editing, this); - tab.setControl( - manager.setupOn(parent) - ); - manager.tab(tab); - return manager; - } - - /** - * @param parent TabFolder - * @param index int - */ - private RulePropertyManager buildExampleTab(TabFolder parent, int index, String title) { - - TabItem tab = new TabItem(parent, 0, index); - tab.setText(title); - - ExamplePanelManager manager = new ExamplePanelManager(title, EditorUsageMode.Editing, this); - tab.setControl( - manager.setupOn(parent) - ); - manager.tab(tab); - return manager; - } - - /** - * @param parent TabFolder - * @param index int - */ - private RulePropertyManager buildQuickFixTab(TabFolder parent, int index, String title) { - - TabItem tab = new TabItem(parent, 0, index); - tab.setText(title); - - QuickFixPanelManager manager = new QuickFixPanelManager(title, EditorUsageMode.Editing, this); - tab.setControl( - manager.setupOn(parent) - ); - manager.tab(tab); - return manager; - } - - /** - * - * @param parent TabFolder - * @param index int - * @param title String - */ - private RulePropertyManager buildUsageTab(TabFolder parent, int index, String title) { - - TabItem tab = new TabItem(parent, 0, index); - tab.setText(title); - - ExclusionPanelManager manager = new ExclusionPanelManager(title, EditorUsageMode.Editing, this, true); - tab.setControl( - manager.setupOn( - parent - ) - ); - manager.tab(tab); - return manager; - } - - /** - * Create buttons for rule table management - * @param parent Composite - * @return Composite - */ - private Composite buildRuleTableButtons(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout gridLayout = new GridLayout(); - gridLayout.numColumns = 1; - gridLayout.verticalSpacing = 3; - composite.setLayout(gridLayout); - - addRuleButton = buildAddRuleButton(composite); - removeRuleButton = buildRemoveRuleButton(composite); - Button importRuleSetButton = buildImportRuleSetButton(composite); - Button exportRuleSetButton = buildExportRuleSetButton(composite); - Button ruleDesignerButton = buildRuleDesignerButton(composite); - - GridData data = new GridData(); - addRuleButton.setLayoutData(data); - - data = new GridData(); - importRuleSetButton.setLayoutData(data); - - data = new GridData(); - exportRuleSetButton.setLayoutData(data); - - data = new GridData(); - data.horizontalAlignment = GridData.FILL; - data.grabExcessVerticalSpace = true; - data.verticalAlignment = GridData.END; - ruleDesignerButton.setLayoutData(data); - - return composite; - } - - /** - * Create buttons for rule properties table management - * @param parent Composite - * @return Composite - */ - private Composite buildRulePropertiesTableButtons(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - RowLayout rowLayout = new RowLayout(); - rowLayout.type = SWT.VERTICAL; - rowLayout.wrap = false; - rowLayout.pack = false; - composite.setLayout(rowLayout); - - return composite; - } - - /** - * Build rule table viewer - * @param parent Composite - * @return Tree - */ - private Tree buildRuleTreeViewer(Composite parent) { - - int treeStyle = SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK; - ruleTreeViewer = new ContainerCheckedTreeViewer(parent, treeStyle); - - final Tree ruleTree = ruleTreeViewer.getTree(); - ruleTree.setLinesVisible(true); - ruleTree.setHeaderVisible(true); - - ruleTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection selection = (IStructuredSelection)event.getSelection(); - selectedItems(selection.toArray()); - } - }); - - ruleListMenu = createMenuFor(ruleTree); - ruleTree.setMenu(ruleListMenu); - ruleTree.addListener(SWT.MenuDetect, new Listener () { - public void handleEvent (Event event) { - popupRuleSelectionMenu(event); - } - }); - - ruleTree.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - if (event.detail == SWT.CHECK) { - TreeItem item = (TreeItem) event.item; - boolean checked = item.getChecked(); - checkItems(item, checked); - checkPath(item.getParentItem(), checked, false); - } - // if (!checkedRules.isEmpty()) System.out.println(checkedRules.iterator().next()); - } - }); - - ruleTree.addListener(SWT.MouseMove, new Listener() { - public void handleEvent(Event event) { - Point point = new Point(event.x, event.y); - TreeItem item = ruleTree.getItem(point); - if (item != null) { - int columnIndex = columnIndexAt(item, event.x); - updateTooltipFor(item, columnIndex); - } - } - }); - - ruleTreeViewer.setCheckStateProvider(createCheckStateProvider()); - - return ruleTree; - } - - private int columnIndexAt(TreeItem item, int xPosition) { - - TreeColumn[] cols = ruleTreeViewer.getTree().getColumns(); - Rectangle bounds = null; - - for(int i = 0; i < cols.length; i++){ - bounds = item.getBounds(i); - if (bounds.x < xPosition && xPosition < (bounds.x + bounds.width)) { - return i; - } - } - return -1; - } - - private void updateTooltipFor(TreeItem item, int columnIndex) { - - RuleLabelProvider provider = (RuleLabelProvider)ruleTreeViewer.getLabelProvider(); - String txt = provider.getDetailText(item.getData(), columnIndex); - ruleTreeViewer.getTree().setToolTipText(txt); - } - - public static Image imageFor(RulePriority priority) { - String codePath = PMDUiConstants.buttonCodePathFor(priority, false); - return ResourceManager.imageFor(codePath); - } - - private boolean currentSelectionHasNonDefaultValues() { - - return ruleSelection == null ? - false : RuleUtil.allUseDefaultValues(ruleSelection); - } - - private Menu createMenuFor(Control control) { - - Menu menu = new Menu(control); - - MenuItem priorityMenu = new MenuItem (menu, SWT.CASCADE); - priorityMenu.setText(SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_COLUMN_PRIORITY)); - Menu subMenu = new Menu(menu); - priorityMenu.setMenu (subMenu); - priorityMenusByPriority = new HashMap<RulePriority, MenuItem>(RulePriority.values().length); - - for (RulePriority priority : RulePriority.values()) { - MenuItem priorityItem = new MenuItem (subMenu, SWT.RADIO); - priorityMenusByPriority.put(priority, priorityItem); - priorityItem.setText(priority.getName()); // TODO need to internationalize? - // priorityItem.setImage(imageFor(priority)); not visible with radiobuttons - final RulePriority pri = priority; - priorityItem.addSelectionListener( new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - setPriority(pri); - } - public void widgetDefaultSelected(SelectionEvent e) { }} - ); - } - - MenuItem removeItem = new MenuItem(menu, SWT.PUSH); - removeItem.setText("Remove"); - removeItem.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - removeSelectedRules(); - } - }); - - MenuItem useDefaultsItem = new MenuItem(menu, SWT.PUSH); - useDefaultsItem.setText("Use defaults"); - useDefaultsItem.setEnabled(false); - useDefaultsItem.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - // useDefaultValues(); - } - }); - - return menu; - } - - private void addColumnSelectionOptions(Menu menu) { - - MenuItem showMenu = new MenuItem(menu, SWT.CASCADE); - showMenu.setText("Show"); - Menu columnsSubMenu = new Menu(menu); - showMenu.setMenu(columnsSubMenu); - - for (String columnLabel : columnLabels()) { - MenuItem columnItem = new MenuItem(columnsSubMenu, SWT.CHECK); - columnItem.setSelection(!hiddenColumnNames.contains(columnLabel)); - columnItem.setText(columnLabel); - final String nameStr = columnLabel; - columnItem.addSelectionListener( new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - toggleColumnVisiblity(nameStr); - } - } - ); - } - } - - private static String[] columnLabels() { - String[] names = new String[availableColumns.length]; - for (int i=0; i<availableColumns.length; i++) { - names[i] = availableColumns[i].label(); - } - return names; - } - - private void toggleColumnVisiblity(String columnName) { - - if (hiddenColumnNames.contains(columnName)) { - hiddenColumnNames.remove(columnName); - } else { - hiddenColumnNames.add(columnName); - } - - PreferenceUIStore.instance.hiddenColumnNames(hiddenColumnNames); - redrawTable(); - } - - private void addRulesetMenuOptions(Menu menu) { - - MenuItem rulesetMenu = new MenuItem(menu, SWT.CASCADE); - rulesetMenu.setText("Ruleset"); - Menu rulesetSubMenu = new Menu(menu); - rulesetMenu.setMenu(rulesetSubMenu); - rulesetMenusByName = new HashMap<String, MenuItem>(); - - MenuItem demoItem = new MenuItem(rulesetSubMenu, SWT.PUSH); - demoItem.setText("---demo only---"); // NO API to re-parent rules to other rulesets (yet) - - for (String rulesetName : rulesetNames()) { - MenuItem rulesetItem = new MenuItem(rulesetSubMenu, SWT.RADIO); - rulesetMenusByName.put(rulesetName, rulesetItem); - rulesetItem.setText(rulesetName); - final String rulesetStr = rulesetName; - rulesetItem.addSelectionListener( new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setRuleset(rulesetStr); - } - } - ); - } - } - private void popupRuleSelectionMenu(Event event) { - - // have to do it here or else the ruleset var is null in the menu setup - timing issue - if (rulesetMenusByName == null) { - addRulesetMenuOptions(ruleListMenu); - new MenuItem(ruleListMenu, SWT.SEPARATOR); - addColumnSelectionOptions(ruleListMenu); - } - - adjustMenuPrioritySettings(); - adjustMenuRulesetSettings(); - adjustMenuUseDefaultsOption(); - ruleListMenu.setLocation(event.x, event.y); - ruleListMenu.setVisible(true); - } - - private void adjustMenuUseDefaultsOption() { - - } - - // if all the selected rules/ruleGroups reference a common ruleset name - // then check that item and disable it, do the reverse for all others. - private void adjustMenuRulesetSettings() { - - String rulesetName = ruleSetNameFrom(RuleUtil.commonRuleset(ruleSelection)); - Iterator<Map.Entry<String, MenuItem>> iter = rulesetMenusByName.entrySet().iterator(); - - while (iter.hasNext()) { - Map.Entry<String, MenuItem> entry = iter.next(); - MenuItem item = entry.getValue(); - if (rulesetName == null) { // allow all entries if none or conflicting - item.setSelection(false); - item.setEnabled(true); - continue; - } - if (StringUtil.areSemanticEquals(entry.getKey(), rulesetName)) { - item.setSelection(true); - item.setEnabled(false); - } else { - item.setSelection(false); - item.setEnabled(true); - } - } - } - - private void adjustMenuPrioritySettings() { - - RulePriority priority = RuleUtil.commonPriority(ruleSelection); - Iterator<Map.Entry<RulePriority, MenuItem>> iter = priorityMenusByPriority.entrySet().iterator(); - - while (iter.hasNext()) { - Map.Entry<RulePriority, MenuItem> entry = iter.next(); - MenuItem item = entry.getValue(); - if (entry.getKey() == priority) { - item.setSelection(true); - item.setEnabled(false); - } else { - item.setSelection(false); - item.setEnabled(true); - } - } - } - - private boolean hasPriorityGrouping() { - return - groupingColumn == TextColumnDescriptor.priorityName || - groupingColumn == TextColumnDescriptor.priority; - } - - private void setPriority(RulePriority priority) { - - ruleSelection.setPriority(priority); - - if (hasPriorityGrouping()) { - redrawTable(); - } else { - ruleTreeViewer.update(ruleSelection.allRules().toArray(), null); - } - } - - private String[] rulesetNames() { - - Set<String> names = new HashSet<String>(); - for (Rule rule : ruleSet.getRules()) { - names.add(ruleSetNameFrom(rule)); // if we strip out the 'Rules' portions then we don't get matches...need to rename rulesets - } - return names.toArray(new String[names.size()]); - } - - private void setRuleset(String rulesetName) { - // TODO - awaiting support in PMD itself - } - - /** - * @param item Object[] - */ - private void selectedItems(Object[] items) { - - ruleSelection = new RuleSelection(items); - for (RulePropertyManager manager : rulePropertyManagers) manager.manage(ruleSelection); - - removeRuleButton.setEnabled(items.length > 0); - } - - /** - * Method groupBy. - * @param chosenColumn RuleColumnDescriptor - */ - private void groupBy(RuleColumnDescriptor chosenColumn) { - - List<RuleColumnDescriptor> visibleColumns = new ArrayList<RuleColumnDescriptor>(availableColumns.length); - for (RuleColumnDescriptor desc : availableColumns) { - if (desc == chosenColumn) continue; // redundant, don't include it - if (hiddenColumnNames.contains(desc.label())) continue; - visibleColumns.add(desc); - } - - setupTreeColumns( - visibleColumns.toArray(new RuleColumnDescriptor[visibleColumns.size()]), - chosenColumn == null ? null : chosenColumn.accessor() - ); - } - - /** - * Remove all rows, columns, and column painters in preparation - * for new columns. - * - * @return Tree - */ - private Tree cleanupRuleTree() { - - Tree ruleTree = ruleTreeViewer.getTree(); - - ruleTree.clearAll(true); - for(;ruleTree.getColumns().length>0;) { // TODO also dispose any heading icons? - ruleTree.getColumns()[0].dispose(); - } - - // ensure we don't have any previous per-column painters left over - for (Map.Entry<Integer, List<Listener>> entry : paintListeners.entrySet()) { - int eventCode = entry.getKey().intValue(); - List<Listener> listeners = entry.getValue(); - for (Listener listener : listeners) { - ruleTree.removeListener(eventCode, listener); - } - listeners.clear(); - } - - return ruleTree; - } - - /** - * Method setupTreeColumns. - * @param columnDescs RuleColumnDescriptor[] - * @param groupingField RuleFieldAccessor - */ - private void setupTreeColumns(RuleColumnDescriptor[] columnDescs, RuleFieldAccessor groupingField) { - - Tree ruleTree = cleanupRuleTree(); - - for (int i=0; i<columnDescs.length; i++) columnDescs[i].newTreeColumnFor(ruleTree, i, this, paintListeners); - - ruleTreeViewer.setLabelProvider(new RuleLabelProvider(columnDescs)); - ruleTreeViewer.setContentProvider( - new RuleSetTreeItemProvider(groupingField, "??", Util.comparatorFrom(columnSorter, sortDescending)) - ); - - ruleTreeViewer.setInput(ruleSet); - checkSelections(); - - TreeColumn[] columns = ruleTree.getColumns(); - for (TreeColumn column : columns) column.pack(); - } - - /** - * Method checkPath. - * @param item TreeItem - * @param checked boolean - * @param grayed boolean - */ - private void checkPath(TreeItem item, boolean checked, boolean grayed) { - if (item == null) return; - if (grayed) { - checked = true; - } else { - int index = 0; - TreeItem[] items = item.getItems(); - while (index < items.length) { - TreeItem child = items[index]; - if (child.getGrayed() || checked != child.getChecked()) { - checked = grayed = true; - break; - } - index++; - } - } - check(item, checked); - item.setGrayed(grayed); - checkPath(item.getParentItem(), checked, grayed); - } - - /** - * @param item TreeItem - * @param checked boolean - */ - private void checkItems(TreeItem item, boolean checked) { - item.setGrayed(false); - check(item, checked); - TreeItem[] items = item.getItems(); - for (TreeItem item2 : items) { - checkItems(item2, checked); - } - updateCheckButtons(); - } - - /** - * @param item TreeItem - * @param checked boolean - */ - private void check(TreeItem item, boolean checked) { - - item.setChecked(checked); - if (item.getData() instanceof RuleGroup) return; - - String name = ((Rule)item.getData()).getName(); - - preferences.isActive(name, checked); - - updateCheckButtons(); - setModified(true); - } - - /** - * Build the remove rule button - * @param parent Composite - * @return Button - */ - private Button buildRemoveRuleButton(Composite parent) { - - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_DELETE)); - button.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_REMOVERULE)); - - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - removeSelectedRules(); - } - }); - return button; - } - - private void removeSelectedRules() { - - int removeCount = ruleSelection.removeAllFrom(ruleSet); - if (removeCount == 0) return; - - setModified(true); - - try { - refresh(); - } catch (Throwable t) { - ruleTreeViewer.setSelection(null); - } - } - - /** - * Build the edit rule button - * @param parent Composite - * @return Button - */ - private Button buildAddRuleButton(Composite parent) { - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_ADD)); - button.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_ADDRULE)); - button.setEnabled(true); - - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - RuleDialog dialog = new RuleDialog(getShell()); - int result = dialog.open(); - if (result == RuleDialog.OK) { - Rule addedRule = dialog.getRule(); - ruleSet.addRule(addedRule); - setModified(true); - try { - refresh(); - } catch (Throwable t) { - plugin.logError("Exception when refreshing the rule table", t); - } - - setModified(true); - try { - refresh(); - } catch (Throwable t) { - plugin.logError("Exception when refreshing the rule table", t); - } - } - } - }); - - return button; - } - - /** - * Build the import ruleset button - * @param parent Composite - * @return Button - */ - private Button buildImportRuleSetButton(Composite parent) { - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_IMPORT)); - button.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_IMPORTRULESET)); - button.setEnabled(true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - RuleSetSelectionDialog dialog = new RuleSetSelectionDialog(getShell()); - dialog.open(); - if (dialog.getReturnCode() == RuleSetSelectionDialog.OK) { - try { - RuleSet selectedRuleSet = dialog.getSelectedRuleSet(); - if (dialog.isImportByReference()) { - ruleSet.addRuleSetByReference(selectedRuleSet, false); - } else { - // Set pmd-eclipse as new RuleSet name and add the Rule - Iterator<Rule> iter = selectedRuleSet.getRules().iterator(); - while (iter.hasNext()) { - Rule rule = iter.next(); - rule.setRuleSetName("pmd-eclipse"); - ruleSet.addRule(rule); - } - } - setModified(true); - try { - refresh(); - } catch (Throwable t) { - plugin.logError("Exception when refreshing the rule table", t); - } - } catch (RuntimeException e) { - plugin.showError(getMessage(StringKeys.MSGKEY_ERROR_IMPORTING_RULESET), e); - } - } - } - }); - - return button; - } - - /** - * Build the export rule set button - * @param parent Composite - * @return Button - */ - private Button buildExportRuleSetButton(Composite parent) { - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_EXPORT)); - button.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_EXPORTRULESET)); - button.setEnabled(true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); - String fileName = dialog.open(); - if (fileName != null) { - try { - File file = new File(fileName); - boolean flContinue = true; - if (file.exists()) { - flContinue = MessageDialog.openConfirm(getShell(), - getMessage(StringKeys.MSGKEY_CONFIRM_TITLE), - getMessage(StringKeys.MSGKEY_CONFIRM_RULESET_EXISTS)); - } - - InputDialog input = null; - if (flContinue) { - input = new InputDialog(getShell(), - getMessage(StringKeys.MSGKEY_PREF_RULESET_DIALOG_TITLE), - getMessage(StringKeys.MSGKEY_PREF_RULESET_DIALOG_RULESET_DESCRIPTION), - ruleSet.getDescription() == null ? "" : ruleSet.getDescription().trim(), null); - flContinue = input.open() == InputDialog.OK; - } - - if (flContinue) { - ruleSet.setName(FileUtil.getFileNameWithoutExtension(file.getName())); - ruleSet.setDescription(input.getValue()); - OutputStream out = new FileOutputStream(fileName); - IRuleSetWriter writer = plugin.getRuleSetWriter(); - writer.write(out, ruleSet); - out.close(); - MessageDialog.openInformation(getShell(), getMessage(StringKeys.MSGKEY_INFORMATION_TITLE), - getMessage(StringKeys.MSGKEY_INFORMATION_RULESET_EXPORTED)); - } - } catch (Exception e) { - plugin.showError(getMessage(StringKeys.MSGKEY_ERROR_EXPORTING_RULESET), e); - } - } - } - }); - - return button; - } - - private CheckboxTreeViewer treeViewer() { return ruleTreeViewer; } - - private Button buildSortByCheckedItemsButton(Composite parent) { - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); - button.setToolTipText("Sort by checked items"); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_SORT_CHECKED)); - - button.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - sortByCheckedItems(); - } - }); - - return button; - } - - /** - * - * @param parent Composite - * @return Button - */ - private Button buildSelectAllButton(Composite parent) { - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); -// button.setText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_SELECT_ALL)); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_CHECK_ALL)); - - button.setEnabled(true); - button.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - setAllRulesActive(); - } - }); - - return button; - } - - private void setAllRulesActive() { - for (Rule rule : ruleSet.getRules()) { - preferences.isActive(rule.getName(), true); - } - - treeViewer().setCheckedElements(ruleSet.getRules().toArray()); - setModified(true); - updateCheckButtons(); - } - - /** - * - * @param parent Composite - * @return Button - */ - private Button buildUnselectAllButton(Composite parent) { - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); -// button.setText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_SELECT_ALL)); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_UNCHECK_ALL)); - - button.setEnabled(true); - button.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - preferences.getActiveRuleNames().clear(); - treeViewer().setCheckedElements(new Object[0]); - setModified(true); - updateCheckButtons(); - } - }); - - return button; - } - - /** - * Build the Rule Designer button - * @param parent Composite - * @return Button - */ - private Button buildRuleDesignerButton(Composite parent) { - Button button = new Button(parent, SWT.PUSH | SWT.LEFT); - button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_EDITOR)); - button.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_RULEDESIGNER)); - button.setEnabled(true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - // TODO Is this cool from Eclipse? Is there a nicer way to spawn a J2SE Application? - new Thread(new Runnable() { - public void run() { - Designer.main(new String[] { "-noexitonclose" }); - } - }).start(); - } - }); - - return button; - } - - private void populateRuleset() { - - RuleSet defaultRuleSet = plugin.getPreferencesManager().getRuleSet(); - ruleSet = new RuleSet(); - ruleSet.addRuleSet(defaultRuleSet); - ruleSet.setName(defaultRuleSet.getName()); - ruleSet.setDescription(Util.asCleanString(defaultRuleSet.getDescription())); - ruleSet.addExcludePatterns(defaultRuleSet.getExcludePatterns()); - ruleSet.addIncludePatterns(defaultRuleSet.getIncludePatterns()); - } - - /** - * Populate the rule table - */ - private void populateRuleTable() { - ruleTreeViewer.setInput(ruleSet); - checkSelections(); - } - - private void checkSelections() { - -// List<Rule> activeRules = new ArrayList<Rule>(); -// -// for (Rule rule : ruleSet.getRules()) { -// if (preferences.isActive(rule.getName())) { -// activeRules.add(rule); -// } -// } -// -// ruleTreeViewer.setCheckedElements(activeRules.toArray()); - } - - /** - * Refresh the list - */ - protected void refresh() { - try { - ruleTreeViewer.getControl().setRedraw(false); - ruleTreeViewer.refresh(); - } catch (ClassCastException e) { - plugin.logError("Ignoring exception while refreshing table", e); - } finally { - ruleTreeViewer.getControl().setRedraw(true); - } - } - - /** - * Update the configured rule set - * Update also all configured projects - */ - private void updateRuleSet() { - try { - ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(getShell()); - monitorDialog.run(true, true, new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - plugin.getPreferencesManager().setRuleSet(ruleSet); - } - }); - } catch (Exception e) { - plugin.logError("Exception updating all projects after a preference change", e); - } - } - - /** - * If user wants to, rebuild all projects - */ - private void rebuildProjects() { - if (MessageDialog.openQuestion(getShell(), getMessage(StringKeys.MSGKEY_QUESTION_TITLE), - getMessage(StringKeys.MSGKEY_QUESTION_RULES_CHANGED))) { - try { - ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(getShell()); - monitorDialog.run(true, true, new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - try { - ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor); - } catch (CoreException e) { - plugin.logError("Exception building all projects after a preference change", e); - } - } - }); - } catch (Exception e) { - plugin.logError("Exception building all projects after a preference change", e); - } - } - } - - /** - * Select and show a particular rule in the table - * @param rule Rule - */ - protected void selectAndShowRule(Rule rule) { - Tree tree = ruleTreeViewer.getTree(); - TreeItem[] items = tree.getItems(); - for (TreeItem item : items) { - Rule itemRule = (Rule)item.getData(); - if (itemRule.equals(rule)) { - // tree.setSelection(tree.indexOf(items[i])); - tree.showSelection(); - break; - } - } - } - - public void changed(Rule rule, PropertyDescriptor<?> desc, Object newValue) { - // TODO enhance to recognize default values - ruleTreeViewer.update(rule, null); - setModified(); - } - - public void changed(RuleSelection selection, PropertyDescriptor<?> desc, Object newValue) { - // TODO enhance to recognize default values - - for (Rule rule : selection.allRules()) { - if (newValue != null) { // non-reliable update behaviour, alternate trigger option - weird - ruleTreeViewer.getTree().redraw(); - // System.out.println("doing redraw"); - } else { - ruleTreeViewer.update(rule, null); - // System.out.println("viewer update"); - } - } - for (RulePropertyManager manager : rulePropertyManagers) { - manager.validate(); - } - - setModified(); - } - - public void sortBy(RuleFieldAccessor accessor, Object context) { - - TreeColumn column = (TreeColumn)context; - - if (columnSorter == accessor) { - sortDescending = !sortDescending; - } else { - columnSorter = accessor; - } - - redrawTable(column.getToolTipText(), sortDescending ? SWT.DOWN : SWT.UP); - } - - -} \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java index 7c954782571..20a0d5bcc89 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java @@ -11,6 +11,7 @@ import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; import net.sourceforge.pmd.eclipse.runtime.preferences.impl.PreferenceUIStore; +import net.sourceforge.pmd.eclipse.ui.Shape; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.Configuration; @@ -55,9 +56,9 @@ public class PMDPreferencePage2 extends AbstractPMDPreferencePage implements Rul private RulePropertyManager[] rulePropertyManagers; private RuleTableManager tableManager; - public static final Util.shape PriorityShape = Util.shape.diamond; - public static final Util.shape RegexFilterShape = Util.shape.square; - public static final Util.shape XPathFilterShape = Util.shape.circle; + public static final Shape PriorityShape = Shape.diamond; + public static final Shape RegexFilterShape = Shape.square; + public static final Shape XPathFilterShape = Shape.circle; public static final FontBuilder blueBold11 = new FontBuilder("Tahoma", 11, SWT.BOLD, SWT.COLOR_BLUE); public static final FontBuilder redBold11 = new FontBuilder("Tahoma", 11, SWT.BOLD, SWT.COLOR_RED); @@ -69,7 +70,7 @@ public class PMDPreferencePage2 extends AbstractPMDPreferencePage implements Rul //TextColumnDescriptor.priorityName, // IconColumnDescriptor.priority, ImageColumnDescriptor.priority, - TextColumnDescriptor.fixCount, + // TextColumnDescriptor.fixCount, TextColumnDescriptor.since, TextColumnDescriptor.ruleSetName, TextColumnDescriptor.ruleType, @@ -284,8 +285,8 @@ private TabFolder buildTabFolder(Composite parent) { buildPropertyTab(tabFolder, 2, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_PROPERTIES)), buildUsageTab(tabFolder, 3, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FILTERS)), buildXPathTab(tabFolder, 4, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_XPATH)), - buildQuickFixTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FIXES)), - buildExampleTab(tabFolder, 6, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_EXAMPLES)), +// buildQuickFixTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FIXES)), + buildExampleTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_EXAMPLES)), }; tabFolder.pack(); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityDescriptorCache.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityDescriptorCache.java new file mode 100644 index 00000000000..69ac06f3c45 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityDescriptorCache.java @@ -0,0 +1,65 @@ +package net.sourceforge.pmd.eclipse.ui.preferences.br; + +import java.util.HashMap; +import java.util.Map; + +import net.sourceforge.pmd.RulePriority; +import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; +import net.sourceforge.pmd.eclipse.plugin.UISettings; +import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; +import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesManager; + +/** + * + * @author Brian Remedios + */ +public class PriorityDescriptorCache { + + private Map <RulePriority, PriorityDescriptor> uiDescriptorsByPriority; + + public static final PriorityDescriptorCache instance = new PriorityDescriptorCache(); + + private PriorityDescriptorCache() { + uiDescriptorsByPriority = new HashMap<RulePriority, PriorityDescriptor>(5); + loadFromPreferences(); + } + + public void loadFromPreferences() { + + IPreferences preferences = PMDPlugin.getDefault().getPreferencesManager().loadPreferences(); + for (RulePriority rp : UISettings.currentPriorities(true)) { + uiDescriptorsByPriority.put(rp, preferences.getPriorityDescriptor(rp).clone()); + } + } + + public void storeInPreferences() { + + IPreferencesManager mgr = PMDPlugin.getDefault().getPreferencesManager(); + + IPreferences prefs = mgr.loadPreferences(); + + for (Map.Entry<RulePriority, PriorityDescriptor> entry : uiDescriptorsByPriority.entrySet()) { + prefs.setPriorityDescriptor(entry.getKey(), entry.getValue()); + } + + mgr.storePreferences(prefs); + } + + public PriorityDescriptor descriptorFor(RulePriority priority) { + return uiDescriptorsByPriority.get(priority); + } + + public boolean hasChanges() { + + IPreferences preferences = PMDPlugin.getDefault().getPreferencesManager().loadPreferences(); + + for (RulePriority rp : UISettings.currentPriorities(true)) { + PriorityDescriptor newOne = uiDescriptorsByPriority.get(rp); + PriorityDescriptor currentOne = preferences.getPriorityDescriptor(rp); + if (newOne.equals(currentOne)) continue; + return true; + } + return false; + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessor.java new file mode 100755 index 00000000000..0692ce0b1bd --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessor.java @@ -0,0 +1,49 @@ +package net.sourceforge.pmd.eclipse.ui.preferences.br; + +import net.sourceforge.pmd.RulePriority; +import net.sourceforge.pmd.eclipse.ui.Shape; + +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; + +/** + * + * @author Brian Remedios + */ +public interface PriorityFieldAccessor<T extends Object> { + + T valueFor(RulePriority priority); + + Image imageFor(RulePriority priority); + + String labelFor(RulePriority priority); + + PriorityFieldAccessor<String> name = new PriorityFieldAccessorAdapter<String>() { + public String valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).label; } + }; + + PriorityFieldAccessor<String> description = new PriorityFieldAccessorAdapter<String>() { + public String valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).description; } + }; + + PriorityFieldAccessor<Shape> shape = new PriorityFieldAccessorAdapter<Shape>() { + public Shape valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).shape.shape; } + }; + + PriorityFieldAccessor<RGB> color = new PriorityFieldAccessorAdapter<RGB>() { + public RGB valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).shape.rgbColor; } + }; + + PriorityFieldAccessor<Integer> size = new PriorityFieldAccessorAdapter<Integer>() { + public Integer valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).shape.size; } + }; + + PriorityFieldAccessor<Integer> value = new PriorityFieldAccessorAdapter<Integer>() { + public Integer valueFor(RulePriority priority) { return priority.getPriority(); } + }; + + PriorityFieldAccessor<Image> image = new PriorityFieldAccessorAdapter<Image>() { + public Image imageFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).getImage(Display.getCurrent()); } + }; +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessorAdapter.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessorAdapter.java new file mode 100644 index 00000000000..5dc26d01734 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessorAdapter.java @@ -0,0 +1,12 @@ +package net.sourceforge.pmd.eclipse.ui.preferences.br; + +import net.sourceforge.pmd.RulePriority; + +import org.eclipse.swt.graphics.Image; + +public class PriorityFieldAccessorAdapter<T extends Object> implements PriorityFieldAccessor<T> { + + public T valueFor(RulePriority priority) { return null; } + public Image imageFor(RulePriority priority) { return null; } + public String labelFor(RulePriority priority) { return null; } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java index d8bf8571aa8..eaf0d756496 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java @@ -119,6 +119,7 @@ public Comparable<String> valueFor(Rule rule) { public String labelFor(Rule rule) { List<String> types = new ArrayList<String>(3); if (rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) types.add(ruleTypeXPath[1]); + // if (if (RuleUtil.isXPathRule(rule)) TODO if (rule.usesDFA()) types.add(ruleTypeDFlow[1]); if (rule.usesTypeResolution()) types.add(ruleTypeTypeRes[1]); return Util.asString(types, ", "); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java index e32fea396b4..26a4f06ce26 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java @@ -233,6 +233,8 @@ private void createRule(Shell shell) { try { CreateRuleWizard wiz = new CreateRuleWizard(); WizardDialog dialog = new WizardDialog(shell, wiz); + wiz.dialog(dialog); + int result = dialog.open(); if (result == Window.OK) { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java index 44403d9d9f6..3bc9214a0d2 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java @@ -14,6 +14,7 @@ import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.rule.RuleReference; +import net.sourceforge.pmd.lang.rule.XPathRule; import net.sourceforge.pmd.lang.rule.properties.AbstractProperty; import net.sourceforge.pmd.util.CollectionUtil; @@ -33,6 +34,15 @@ public static boolean isDefaultValue(Map.Entry<PropertyDescriptor<?>, Object> en return areEqual(desc.defaultValue(), value); } + // TODO fix rule!! + public static boolean isXPathRule(Rule rule) { + + for (PropertyDescriptor<?> desc : rule.getPropertyDescriptors()) { + if (desc.equals(XPathRule.XPATH_DESCRIPTOR)) return true; + } + return false; + } + // TODO move elsewhere public static boolean areEqual(Object value, Object otherValue) { if (value == otherValue) { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items index 18f8a30a337..1d35cc11c1d 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items @@ -4,7 +4,6 @@ Finish remaining editors and the Add Property dialog Enable 'Use defaults' option in popup menu (need support in properties/PMD) Add selection column selected rules in per-project rule settings table Rework context menu - build on-demand, not before -Markup violations using priority icons rather than the yellow yield signs or red Xs Work on support for fixes Format example & description text Need preference widgets to allow user-specified shapes for RulePriorities diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java index 17c63399940..00bbf6da61b 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java @@ -6,6 +6,9 @@ import net.sourceforge.pmd.PropertyDescriptor; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; +import net.sourceforge.pmd.eclipse.ui.editors.BasicLineStyleListener; +import net.sourceforge.pmd.eclipse.ui.editors.SyntaxData; +import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleSelection; import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; import net.sourceforge.pmd.eclipse.ui.preferences.editors.TypeText; @@ -17,7 +20,10 @@ import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; +import org.eclipse.swt.custom.LineStyleListener; import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Button; @@ -201,7 +207,16 @@ public void handleEvent(Event event) { } }); } + + protected void addTextListeners(final StyledText control, final StringProperty desc) { + control.addListener(SWT.FocusOut, new Listener() { + public void handleEvent(Event event) { + changed(desc, control.getText()); + } + }); + } + protected void initializeOn(Composite parent) { if (errorColour != null) return; @@ -335,4 +350,10 @@ protected Text newTextField(Composite parent) { return new Text(parent, SWT.BORDER | SWT.WRAP | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); } + + protected StyledText newCodeField(Composite parent) { + + return new StyledText(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); + } + } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java index 7527a975672..c2dffaa3bea 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java @@ -9,6 +9,7 @@ import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; +import org.eclipse.jface.wizard.WizardDialog; /** * A wizard that encapsulates a succession of rule panel managers to collect the @@ -18,18 +19,24 @@ */ public class CreateRuleWizard extends Wizard implements ValueChangeListener, RuleTarget { - private Rule rule; - + private Rule rule; + private WizardDialog dialog; + public CreateRuleWizard() { super(); } + public void dialog(WizardDialog theDialog) { + dialog = theDialog; + } + public Rule rule() { return rule; } public void rule(Rule theRule) { rule = theRule; + dialog.updateButtons(); } public void addPages() { @@ -38,7 +45,7 @@ public void addPages() { addPage(new PerRulePropertyPanelManager("properties", EditorUsageMode.CreateNew, this)); addPage(new XPathPanelManager("xpath", EditorUsageMode.CreateNew, this)); addPage(new ExclusionPanelManager("exclusion", EditorUsageMode.CreateNew, this, false)); - addPage(new QuickFixPanelManager("fixes", EditorUsageMode.CreateNew, this)); +// addPage(new QuickFixPanelManager("fixes", EditorUsageMode.CreateNew, this)); addPage(new ExamplePanelManager("examples", EditorUsageMode.CreateNew, this)); } @@ -82,7 +89,8 @@ public IWizardPage getNextPage(IWizardPage currentPage) { getAndPrepare(ExclusionPanelManager.ID); } if (currentPage instanceof ExclusionPanelManager || currentPage instanceof XPathPanelManager) { - return getAndPrepare(QuickFixPanelManager.ID); +// return getAndPrepare(QuickFixPanelManager.ID); + return getAndPrepare(ExamplePanelManager.ID); } if (currentPage instanceof QuickFixPanelManager) { return getAndPrepare(ExamplePanelManager.ID); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java index 6f24e8971f7..e661cf0ef0d 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java @@ -5,18 +5,20 @@ import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.util.StringUtil; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +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.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Text; /** * @@ -24,8 +26,9 @@ */ public class ExamplePanelManager extends AbstractRulePanelManager { - private Text exampleField; - + private StyledText exampleField; + private ModifyListener modifyListener; + public static final String ID = "example"; public ExamplePanelManager(String theTitle, EditorUsageMode theMode, ValueChangeListener theListener) { @@ -61,7 +64,7 @@ public Control setupOn(Composite parent) { GridLayout layout = new GridLayout(2, false); panel.setLayout(layout); - exampleField = newTextField(panel); + exampleField = newCodeField(panel); gridData = new GridData(GridData.FILL_BOTH); gridData.grabExcessHorizontalSpace = true; gridData.horizontalSpan = 1; @@ -77,11 +80,11 @@ public void handleEvent(Event event) { if (StringUtil.areSemanticEquals(existingValue, cleanValue)) return; - soleRule.setDescription(cleanValue); + soleRule.setDescription(cleanValue); valueChanged(null, cleanValue); } }); - + return panel; } @@ -127,6 +130,11 @@ protected void adapt() { shutdown(exampleField); } else { show(exampleField, examples(soleRule)); + modifyListener = SyntaxManager.adapt( + exampleField, + soleRule.getLanguage().getTerseName(), + modifyListener + ); } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java index ffe2bbe69b4..791d79833d7 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java @@ -4,6 +4,7 @@ import java.util.List; import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; @@ -11,6 +12,7 @@ import net.sourceforge.pmd.lang.rule.properties.StringProperty; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; @@ -28,7 +30,7 @@ public class ExclusionPanelManager extends AbstractRulePanelManager { private Text excludeWidget; - private Text xpathWidget; + private StyledText xpathWidget; private Composite excludeColour; private Composite xPathColour; private ColourManager colourManager; @@ -79,6 +81,23 @@ public void modifyText(ModifyEvent e) { }); } + private void addListeners(final StyledText control, final StringProperty desc, final Control colourWindow) { + + addTextListeners(control, desc); + + control.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + String newText = control.getText(); + if (colourWindow != null) { + colourWindow.setBackground( + colourManager.colourFor(newText) + ); + } + changed(desc, newText); + } + }); + } + private Composite newColourPanel(Composite parent, String label) { Composite panel = new Composite(parent, SWT.None); @@ -158,11 +177,12 @@ public Control setupOn(Composite parent) { gridData = new GridData(GridData.FILL_BOTH); gridData.horizontalSpan = 2; gridData.grabExcessHorizontalSpace = true; - xpathWidget = newTextField(panel); + xpathWidget = newCodeField(panel); xpathWidget.setLayoutData(gridData); - + SyntaxManager.adapt(xpathWidget, "xpath", null); + addListeners(xpathWidget, Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR, xPathColour); - + panel.pack(); return panel; diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java index d404cee62bb..f689655d0c0 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java @@ -10,6 +10,7 @@ import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; import net.sourceforge.pmd.eclipse.ui.preferences.br.EditorFactory; import net.sourceforge.pmd.eclipse.ui.preferences.br.NewPropertyDialog; +import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleUtil; import net.sourceforge.pmd.eclipse.ui.preferences.br.SizeChangeListener; import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; import net.sourceforge.pmd.eclipse.util.ResourceManager; @@ -200,7 +201,7 @@ public void widgetSelected(SelectionEvent e) { */ public List<String> updateDeleteButtons() { - if (rule == null || !rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { + if (rule == null || !RuleUtil.isXPathRule(rule)) { return Collections.emptyList(); } @@ -208,7 +209,7 @@ public List<String> updateDeleteButtons() { List<int[]> refPositions = Util.referencedNamePositionsIn(source, '$'); if (refPositions.isEmpty()) return Collections.emptyList(); - List<String> unreferenced = new ArrayList<String>(refPositions.size()); + List<String> unreferencedOnes = new ArrayList<String>(refPositions.size()); List<String> varNames = Util.fragmentsWithin(source, refPositions); for (Control[] widgetRow : widgets) { @@ -221,9 +222,9 @@ public List<String> updateDeleteButtons() { "Delete variable: $" + buttonName : "Delete unreferenced variable: $" + buttonName ); - if (!isReferenced) unreferenced.add((String) butt.getData()); + if (!isReferenced) unreferencedOnes.add((String) butt.getData()); } - return unreferenced; + return unreferencedOnes; }; } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java index 8ab9fea8db9..4e00c5ff029 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; +import net.sourceforge.pmd.PropertyDescriptor; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.eclipse.ui.preferences.br.EditorFactory; import net.sourceforge.pmd.eclipse.ui.preferences.br.SizeChangeListener; @@ -78,7 +79,14 @@ public PerRulePropertyPanelManager(String theTitle, EditorUsageMode theMode, Val protected boolean canManageMultipleRules() { return false; } protected boolean canWorkWith(Rule rule) { - if (rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) return true; + + // TODO if (rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) return true; won't work, need to tweak Rule implementation as map is empty + + // alternate approach for now + for (PropertyDescriptor<?> desc : rule.getPropertyDescriptors()) { + if (desc.equals(XPathRule.XPATH_DESCRIPTOR)) return true; + } + return !Configuration.filteredPropertiesOf(rule).isEmpty(); } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java index c459ffa8088..b04e8de674f 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java @@ -12,6 +12,7 @@ import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; import net.sourceforge.pmd.eclipse.plugin.UISettings; +import net.sourceforge.pmd.eclipse.ui.ShapePicker; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; import net.sourceforge.pmd.eclipse.ui.preferences.br.ImplementationType; import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleFieldAccessor; @@ -55,7 +56,7 @@ public class RulePanelManager extends AbstractRulePanelManager { private Button ruleReferenceButton; private Combo languageCombo; private Combo priorityCombo; - private ShapeSetCanvas priorityDisplay; + private ShapePicker priorityDisplay; private Label minLanguageLabel; private Label maxLanguageLabel; @@ -68,6 +69,8 @@ public class RulePanelManager extends AbstractRulePanelManager { private Button usesDfaButton; private List<Label> labels; + private boolean inSetup; + public static final String ID = "rule"; public RulePanelManager(String theTitle, EditorUsageMode theMode, ValueChangeListener theListener, RuleTarget theRuleSource) { @@ -222,6 +225,8 @@ protected boolean canManageMultipleRules() { @Override public Control setupOn(Composite parent) { + inSetup = true; + labels = new ArrayList<Label>(); Composite dlgArea = new Composite(parent, SWT.NONE); @@ -340,7 +345,7 @@ public Control setupOn(Composite parent) { priorityCombo = buildPriorityCombo(priorityComp); priorityCombo.setLayoutData( new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); - priorityDisplay = new ShapeSetCanvas(priorityComp, SWT.NONE, 14); + priorityDisplay = new ShapePicker(priorityComp, SWT.NONE, 14); priorityDisplay.setLayoutData( new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); priorityDisplay.setShapeMap(UISettings.shapesByPriority()); priorityDisplay.setSize(90, 25); @@ -353,6 +358,8 @@ public Control setupOn(Composite parent) { validate(); + inSetup = false; + return dlgArea; } @@ -480,7 +487,7 @@ public void widgetSelected(SelectionEvent event) { return combo; } - + private Combo buildLanguageCombo(Composite parent) { final List<Language> languages = Language.findWithRuleSupport(); @@ -653,7 +660,15 @@ private void validateRuleParams() { populateRuleInstance(); } - if (target != null) target.rule(isOk ? rules.soleRule() : null); + if (inSetup) return; + + if (target != null) { + target.rule( + isOk ? + rules.soleRule() : + null + ); + } } private void copyLocalValuesTo(Rule rule) { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ShapeDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ShapeDescriptor.java deleted file mode 100755 index c98b1394440..00000000000 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ShapeDescriptor.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers; - -import net.sourceforge.pmd.eclipse.util.Util; - -import org.eclipse.swt.graphics.RGB; - -/** - * - * @author Brian Remedios - */ -public class ShapeDescriptor { - - public final Util.shape shape; - public final RGB rgbColor; - public final int size; - - public ShapeDescriptor(Util.shape theShape, RGB theColor, int theSize) { - shape = theShape; - rgbColor = theColor; - size = theSize; - } -} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ShapeSetCanvas.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ShapeSetCanvas.java deleted file mode 100755 index b7389acfbab..00000000000 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ShapeSetCanvas.java +++ /dev/null @@ -1,98 +0,0 @@ -package net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers; - -import java.util.Map; - -import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; -import net.sourceforge.pmd.eclipse.util.Util; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; - -/** - * Renders a set of coloured shapes mapped to known set of incoming items - * - * @author Brian Remedios - */ -public class ShapeSetCanvas extends Canvas { - - private Object[] items; - private int itemWidth; - private Map<Object, ShapeDescriptor> shapeDescriptorsByItem; - - public ShapeSetCanvas(Composite parent, int style, int theItemWidth) { - super(parent, style); - - itemWidth = theItemWidth; - - ShapeSetCanvas.this.addPaintListener( new PaintListener() { - public void paintControl(PaintEvent pe) { - doPaint(pe); - } - } ); - } - - private Color colourFor(int itemIndex) { - ShapeDescriptor desc = shapeDescriptorsByItem.get(items[itemIndex]); - if (desc == null) return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); - return PMDPlugin.getDefault().colorFor(desc.rgbColor); - } - - private Util.shape shapeFor(int itemIndex) { - ShapeDescriptor desc = shapeDescriptorsByItem.get(items[itemIndex]); - return desc == null ? Util.shape.circle : desc.shape; - } - - private void doPaint(PaintEvent pe) { - - GC gc = pe.gc; - int width = getSize().x; - int xBoundary = 3; - int gap = 2; - - for (int i=0; i<items.length; i++) { - gc.setBackground(colourFor(i)); - - int xOffset = 0; - int step = (itemWidth + gap) * i; - - switch (SWT.LEFT) { // TODO take from style bits - case SWT.CENTER: xOffset = (width / 2) - (itemWidth / 2) - xBoundary + step; break; - case SWT.RIGHT: xOffset = width - width - xBoundary; break; - case SWT.LEFT: xOffset = xBoundary + step; - } - - Util.drawShape(itemWidth, itemWidth, shapeFor(i), gc, pe.x + xOffset, pe.y); - } - } - - public Point computeSize(int wHint, int hHint, boolean changed) { - - Point pt = getSize(); - // TODO adapt by shape count - return new Point(pt.x, pt.y); - } - - public void setItems(Object[] theItems) { - items = theItems; - redraw(); - } - - public void setItemWidth(int width) { - itemWidth = width; - redraw(); - } - - public void setShapeMap(Map<Object, ShapeDescriptor> theShapeMap) { - - shapeDescriptorsByItem = theShapeMap; - redraw(); - } - -} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/XPathPanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/XPathPanelManager.java index f9c2252c95c..cfcf0ee836b 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/XPathPanelManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/XPathPanelManager.java @@ -3,22 +3,22 @@ import java.util.ArrayList; import java.util.List; -import net.sourceforge.pmd.PropertyDescriptor; import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.eclipse.ui.editors.BasicLineStyleListener; +import net.sourceforge.pmd.eclipse.ui.editors.SyntaxData; +import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; import net.sourceforge.pmd.eclipse.ui.preferences.br.ImplementationType; import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleSelection; import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; import net.sourceforge.pmd.eclipse.ui.preferences.editors.EnumerationEditorFactory; import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; -import net.sourceforge.pmd.eclipse.util.Util; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.lang.rule.XPathRule; import net.sourceforge.pmd.lang.rule.properties.EnumeratedProperty; import net.sourceforge.pmd.util.StringUtil; import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; @@ -41,7 +41,7 @@ public class XPathPanelManager extends AbstractRulePanelManager { private Combo xpathVersionField; private Label versionLabel; private List<String> unknownVariableNames; - + public static final String ID = "xpath"; public XPathPanelManager(String theTitle, EditorUsageMode theMode, ValueChangeListener theListener) { @@ -58,7 +58,7 @@ protected List<String> fieldErrors() { List<String> errors = new ArrayList<String>(2); - if (StringUtil.isEmpty(xpathField.getText().trim())) { + if (StringUtil.isEmpty(xpathField.getText())) { errors.add("Missing XPATH code"); } @@ -100,7 +100,8 @@ public Control setupOn(Composite parent) { GridLayout layout = new GridLayout(2, false); panel.setLayout(layout); - xpathField = new StyledText(panel, SWT.BORDER); + xpathField = newCodeField(panel); + SyntaxManager.adapt(xpathField, "xpath", null); gridData = new GridData(GridData.FILL_BOTH); gridData.grabExcessHorizontalSpace = true; gridData.horizontalSpan = 2; @@ -121,11 +122,12 @@ public void modifyText(ModifyEvent event) { validate(); soleRule.setProperty(XPathRule.XPATH_DESCRIPTOR, newValue); - updateVariablesField(); + + // updateVariablesField(); valueChanged(XPathRule.XPATH_DESCRIPTOR, newValue); } - }); - + }); + versionLabel = new Label(panel, 0); versionLabel.setText(SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULEEDIT_LABEL_XPATH_VERSION)); gridData = new GridData(); @@ -163,35 +165,35 @@ private void configureVersionFieldFor(Rule rule) { if (selectionIdx >= 0) xpathVersionField.select(selectionIdx); } - private static StyleRange styleFor(Rule rule, String source, int[] position, List<String> unknownVars) { - - String varName = source.substring(position[0], position[0] + position[1]); - PropertyDescriptor<?> desc = rule.getPropertyDescriptor(varName); - - if (desc == null) unknownVars.add(varName); - - return new StyleRange( - position[0], position[1], - desc == null ? errorColour : null, - null, - SWT.BOLD - ); - } - - private void updateVariablesField() { - - xpathField.setStyleRange(null); // clear all - - Rule rule = soleRule(); - unknownVariableNames = new ArrayList<String>(); - - String xpath = rule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim(); - List<int[]> positions = Util.referencedNamePositionsIn(xpath, '$'); - for (int[] position : positions) { - StyleRange range = styleFor(rule, xpath, position, unknownVariableNames); - xpathField.setStyleRange(range); - } - } +// private static StyleRange styleFor(Rule rule, String source, int[] position, List<String> unknownVars) { +// +// String varName = source.substring(position[0], position[0] + position[1]); +// PropertyDescriptor<?> desc = rule.getPropertyDescriptor(varName); +// +// if (desc == null) unknownVars.add(varName); +// +// return new StyleRange( +// position[0], position[1], +// desc == null ? errorColour : null, +// null, +// SWT.BOLD +// ); +// } +// +// private void updateVariablesField() { +// +// xpathField.setStyleRange(null); // clear all +// +// Rule rule = soleRule(); +// unknownVariableNames = new ArrayList<String>(); +// +// String xpath = rule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim(); +// List<int[]> positions = Util.referencedNamePositionsIn(xpath, '$'); +// for (int[] position : positions) { +// StyleRange range = styleFor(rule, xpath, position, unknownVariableNames); +// xpathField.setStyleRange(range); +// } +// } protected void adapt() { @@ -202,7 +204,7 @@ protected void adapt() { } else { show(xpathField, soleRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); configureVersionFieldFor(soleRule); - updateVariablesField(); + // updateVariablesField(); } validate(); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractPMDPagebookView.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractPMDPagebookView.java index 9ceb360cffa..f2070edf451 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractPMDPagebookView.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractPMDPagebookView.java @@ -56,6 +56,32 @@ protected IWorkbenchPage getSitePage() { return getSite().getPage(); } + /** + * Gets the fileRecord from the currently active editor. + * @param part IWorkbenchPart + * @return a new FileRecord + */ + protected FileRecord getFileRecordFromWorkbenchPart(IWorkbenchPart part) { + if (part instanceof IEditorPart) { + // If there is a file opened in the editor, we create a record for it + IEditorInput input = ((IEditorPart) part).getEditorInput(); + if (input != null && input instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) input).getFile(); + return AbstractDefaultCommand.isJavaFile(file) ? + new FileRecord(file) : + null; + } + } else { + // We also want to get the editors when it's not active + // so we pretend, that the editor has been activated + IEditorPart editorPart = getSite().getPage().getActiveEditor(); + if (editorPart != null) { + return getFileRecordFromWorkbenchPart(editorPart); + } + } + return null; + } + /* @see org.eclipse.ui.part.ViewPart#init(org.eclipse.ui.IViewSite) */ @Override public void init(IViewSite site) throws PartInitException { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractStructureInspectorPage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractStructureInspectorPage.java new file mode 100644 index 00000000000..f9e19de7b9f --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractStructureInspectorPage.java @@ -0,0 +1,294 @@ +package net.sourceforge.pmd.eclipse.ui.views; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.pmd.PMDException; +import net.sourceforge.pmd.RuleContext; +import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; +import net.sourceforge.pmd.eclipse.runtime.cmd.PMDEngine; +import net.sourceforge.pmd.eclipse.ui.model.FileRecord; +import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; +import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; +import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; +import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator; +import net.sourceforge.pmd.util.StringUtil; +import net.sourceforge.pmd.util.designer.DFAGraphRule; + +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.IPropertyListener; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.part.Page; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * + * @author Brian Remedios + */ +public abstract class AbstractStructureInspectorPage extends Page implements IPropertyListener, ISelectionChangedListener { + + protected Combo methodSelector; + protected FileRecord resourceRecord; + protected List<ASTMethodDeclaration> pmdMethodList; + + protected ITextEditor textEditor; + + public static String parameterTypes(ASTMethodDeclaration node) { + + StringBuilder sb = new StringBuilder(); + + for (int ix = 0; ix < node.jjtGetNumChildren(); ix++) { + Node sn = node.jjtGetChild(ix); + if (sn instanceof ASTMethodDeclarator) { + List<ASTFormalParameter> allParams = ((ASTMethodDeclarator) sn).findChildrenOfType(ASTFormalParameter.class); + for (ASTFormalParameter formalParam : allParams) { + ASTClassOrInterfaceType param = formalParam.getFirstDescendantOfType(ASTClassOrInterfaceType.class); + if (param != null) { + sb.append( param.getImage() ).append(", "); + } + } + } + } + + return sb.toString(); + } + + protected AbstractStructureInspectorPage(IWorkbenchPart part, FileRecord record) { + super(); + + resourceRecord = record; + if (part instanceof ITextEditor) { + textEditor = (ITextEditor) part; + } + } + + public void setFocus() { + methodSelector.setFocus(); + } + + /** + * Shows the method that belongs to a violation (to a line). + * @param violation RuleViolation + */ + protected void showMethodToViolation(RuleViolation violation) { + final int beginLine = violation.getBeginLine(); + + for (int i = 0; i < pmdMethodList.size(); i++) { + ASTMethodDeclaration pmdMethod = pmdMethodList.get(i); + if (beginLine >= pmdMethod.getBeginLine() && beginLine <= pmdMethod.getEndLine()) { + showMethod(pmdMethod); + // select the method in the combobox + methodSelector.select(i); + return; + } + } + } + + protected RuleViolation selectedViolationFrom(SelectionChangedEvent event) { + + if (event.getSelection() instanceof IStructuredSelection) { + final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); + return element instanceof RuleViolation ? + (RuleViolation) element : null; + } + + return null; // should never happen + } + + /* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ + public void selectionChanged(SelectionChangedEvent event) { + + RuleViolation violation = selectedViolationFrom(event); + if (violation == null) return; + + String varName = violation.getVariableName(); + if (StringUtil.isEmpty(varName)) return; + + int beginLine = violation.getBeginLine(); + int endLine = violation.getEndLine(); + + if (beginLine != 0 && endLine != 0) { + try { + int offset = getDocument().getLineOffset(violation.getBeginLine() - 1); + int length = getDocument().getLineOffset(violation.getEndLine()) - offset; + textEditor.selectAndReveal(offset, length); + } catch (BadLocationException ble) { + logError(StringKeys.MSGKEY_ERROR_RUNTIME_EXCEPTION + "Exception when selecting a line in the editor", ble); + } + + // showMethodToMarker(marker); + showMethodToViolation(violation); + + // then we calculate and color _a possible_ Path + // for this Error in the Dataflow + // final DataflowGraph graph = astViewer.getGraph(); + // if (!astViewer.isDisposed() && graph != null) { + // graph.markPath(beginLine, endLine, varName); + // } + } + } + + /** + * If the review is ready propertyChanged with the results will be called. + */ + public void propertyChanged(Object source, int propId) { + if (source instanceof Iterator<?> + && propId == PMDRuntimeConstants.PROPERTY_REVIEW) { + // tableViewer.setInput(source); + } + } + + /** + * Gets the label of a method for an element of the combobox. + * @param pmdMethod the method to create a label for + * @return a label for the method + */ + String getMethodLabel(ASTMethodDeclaration pmdMethod) { + return pmdMethod.getMethodName() + "(" + parameterTypes(pmdMethod) + ")"; + } + + /** + * Refreshes the list of PMD methods for the combobox. + * @see #getPMDMethods(IResource) + */ + protected void refreshPMDMethods() { + + methodSelector.removeAll(); + pmdMethodList = getPMDMethods(); + + for (ASTMethodDeclaration pmdMethod : pmdMethodList) { + methodSelector.add(getMethodLabel(pmdMethod)); + } + } + + public void showFirstMethod() { + methodSelector.select(0); + showMethod(0); + } + + /** + * @return the underlying FileRecord + */ + public FileRecord getFileRecord() { + return resourceRecord; + } + + /** + * Confort method to show a method. + * @param index index position of the combobox + */ + protected void showMethod(int index) { + if (index >= 0 && index < pmdMethodList.size() ) { + ASTMethodDeclaration method = pmdMethodList.get(index); + showMethod(method); + } + } + + protected abstract void showMethod(ASTMethodDeclaration pmdMethod); + + /** + * Helper method to return an NLS string from its key. + */ + protected static String getString(String key) { + return PMDPlugin.getDefault().getStringTable().getString(key); + } + + protected void buildMethodSelector(Composite parent) { + // the drop down box for showing all methods of the given resource + methodSelector = new Combo(parent, SWT.LEFT | SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER); + refreshPMDMethods(); + methodSelector.setText(getString(StringKeys.MSGKEY_VIEW_DATAFLOW_CHOOSE_METHOD)); + methodSelector.setLayoutData(new GridData(300, SWT.DEFAULT)); + methodSelector.addSelectionListener( new SelectionAdapter() { + + /* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) */ + public void widgetDefaultSelected(SelectionEvent e) { + if (methodSelector.equals(e.widget)) { + showMethod(methodSelector.getSelectionIndex()); + } + } + + public void widgetSelected(SelectionEvent e) { + methodPicked(); + } + }); + } + + public void methodPicked() { + int index = methodSelector.getSelectionIndex(); + methodSelector.setSelection(new Point(0,0)); + showMethod(index); + } + + /** + * Gets a List of all PMD-Methods. + * + * @return an List of ASTMethodDeclarations + */ + private List<ASTMethodDeclaration> getPMDMethods() { + + List<ASTMethodDeclaration> methodList = new ArrayList<ASTMethodDeclaration>(); + + // we need PMD to run over the given Resource + // with the DFAGraphRule to get the Methods; + // PMD needs this Resource as a String + try { + DFAGraphRule dfaGraphRule = new DFAGraphRule(); + RuleSet rs = new RuleSet(); + rs.addRule(dfaGraphRule); + + RuleContext ctx = new RuleContext(); + ctx.setSourceCodeFilename("[scratchpad]"); + + StringReader reader = new StringReader(getDocument().get()); + + // run PMD using the DFAGraphRule + // and the Text of the Resource + new PMDEngine().processFile(reader, rs, ctx); + + // the Rule then can give us the Methods + methodList.addAll(dfaGraphRule.getMethods()); + } catch (PMDException pmde) { + logError(StringKeys.MSGKEY_ERROR_PMD_EXCEPTION + this.toString(), pmde); + } + + return methodList; + } + + /** + * Gets the Document of the page. + * @return instance of IDocument of the page + */ + public IDocument getDocument() { + return textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); + } + + public static void logError(String message, Throwable error) { + PMDPlugin.getDefault().logError(message, error); + } + + public static void logErrorByKey(String messageId, Throwable error) { + PMDPlugin.getDefault().logError(getString(messageId), error); + } + +} \ No newline at end of file diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractViolationLabelProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractViolationLabelProvider.java new file mode 100755 index 00000000000..f15e318097f --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/AbstractViolationLabelProvider.java @@ -0,0 +1,46 @@ +package net.sourceforge.pmd.eclipse.ui.views; + +import java.util.HashMap; +import java.util.Map; + +import net.sourceforge.pmd.eclipse.plugin.UISettings; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.swt.graphics.Image; + +/** + * + * @author Brian Remedios + */ +public abstract class AbstractViolationLabelProvider extends LabelProvider implements ITableLabelProvider { + + private static Map<Integer, Image> imagesByPriorityIndex; + + static { + loadImageMap(); + } + + protected AbstractViolationLabelProvider() { + } + + private static void loadImageMap() { + + Map<Integer, ImageDescriptor> map = UISettings.markerImgDescriptorsByPriority(); + + imagesByPriorityIndex = new HashMap<Integer, Image>(map.size()); + + for (Map.Entry<Integer, ImageDescriptor> entry : map.entrySet()) { + imagesByPriorityIndex.put( + entry.getKey(), + entry.getValue().createImage() + ); + } + } + + protected static Image getPriorityImage(int priority) { + + return imagesByPriorityIndex.get(priority); + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ChangeEvaluator.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ChangeEvaluator.java new file mode 100755 index 00000000000..f6ffa59b405 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ChangeEvaluator.java @@ -0,0 +1,194 @@ +package net.sourceforge.pmd.eclipse.ui.views; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IMarkerDelta; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; + +import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; +import net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord; +import net.sourceforge.pmd.eclipse.ui.model.FileRecord; +import net.sourceforge.pmd.eclipse.ui.model.PackageRecord; +import net.sourceforge.pmd.eclipse.ui.model.ProjectRecord; +import net.sourceforge.pmd.eclipse.ui.model.RootRecord; + +/** + * As chunks of code originally found in the ViolationOverviewContentProvider, the ChangeEvaluator + * aggregates the same functionality while using formal ChangeRecord instances instead of List triplets. + * + * @author Brian Remedios + */ +public class ChangeEvaluator { + + private final RootRecord root; + + public ChangeEvaluator(RootRecord theRoot) { + root = theRoot; + } + + + public ChangeRecord<AbstractPMDRecord> changeRecordFor(IResourceChangeEvent event) { + + List<IMarkerDelta> markerDeltas = MarkerUtil.markerDeltasIn(event); + + // first we get a List of changes to Files and Projects so we won't be updating everything + List<IResource> changedFiles = new ArrayList<IResource>(); + List<IProject> changedProjects = new ArrayList<IProject>(); + for (IMarkerDelta markerDelta : markerDeltas) { + IResource resource = markerDelta.getResource(); + IProject project = resource.getProject(); + + // the lists should not contain Projects or Resources twice + if (!changedFiles.contains(resource)) { + changedFiles.add(resource); +// LOG.debug("Resource " + resource.getName() + " has changed"); + } + + if (!changedProjects.contains(project)) { + changedProjects.add(project); +// LOG.debug("Project " + project.getName() + " has changed"); + } + } + + // we can add, change, or remove Resources + // all the changes are given to the viewer later + + ChangeRecord<AbstractPMDRecord> changeRec = new ChangeRecord<AbstractPMDRecord>(); + + // we go through the changed Projects + for (IProject project : changedProjects) { +// LOG.debug("Processing changes for project " + project.getName()); + ProjectRecord projectRec = (ProjectRecord) root.findResource(project); + + // if the Project is closed or deleted, we also delete it from the Model and go on + if (!(project.isOpen() && project.isAccessible())) { // NOPMD by Sven on 09.11.06 22:17 +// LOG.debug("The project is not open or not accessible. Remove it"); + List<AbstractPMDRecord>[] array = updateFiles(project, changedFiles); + changeRec.removed(array[1]); + root.removeResource(project); + } + + // if we couldn't find the Project then it has to be new + else if (projectRec == null) { +// LOG.debug("Cannot find a project record for it. Add it."); + projectRec = (ProjectRecord) root.addResource(project); + } + + // then we can update the Files for the new or updated Project + List<AbstractPMDRecord>[] array = updateFiles(project, changedFiles); + changeRec.added(array[0]); + changeRec.removed(array[1]); + changeRec.changed(array[2]); + } + + // the additions, removals and changes are given to the viewer + // so that it can update itself + // updating the table MUST be in sync + // this.treeViewer.getControl().getDisplay().syncExec(new Runnable() { + // public void run() { + // updateViewer(additions, removals, changes); + // } + // }); + + return changeRec; + } + + /** + * Updates the Files for a given Project + * + * @param project + * @param changedFiles, a List of all changed Files + * @return an List of Lists containing additions [0], removals [1] + * and changes [2] (Array-Position in Brackets) + */ + private List<AbstractPMDRecord>[] updateFiles(IProject project, List<IResource> changedFiles) { + + // TODO use ChangeRecord + List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); + List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); + List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); + List<AbstractPMDRecord>[] updatedFiles = new List[] { additions, removals, changes }; + + // we search for the ProjectRecord to the Project + // if it doesn't exist, we return nothing + ProjectRecord projectRec = (ProjectRecord) root.findResource(project); + + // we got through all files + if (projectRec != null && project.isAccessible()) { + updatedFiles = searchProjectForModifications(projectRec, changedFiles); + } + + // if the project is deleted or closed + else if (projectRec != null) { + List<AbstractPMDRecord> packages = projectRec.getChildrenAsList(); + // ... we add all Packages to the removals so they are not shown anymore + removals.addAll(packages); + for (int k = 0; k < packages.size(); k++) { + PackageRecord packageRec = (PackageRecord) packages.get(k); + removals.addAll(packageRec.getChildrenAsList()); + } + updatedFiles = new List[] { additions, removals, changes }; + } + + return updatedFiles; + } + + /** + * Analyzes the modification inside a single project and compute the list of additions, updates and removals. + * + * @param projectRec + * @param changedFiles + * @return + */ + private static List<AbstractPMDRecord>[] searchProjectForModifications(ProjectRecord projectRec, List<IResource> changedFiles) { + + // TODO use ChangeRecord + List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); + List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); + List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); + IProject project = (IProject) projectRec.getResource(); + +// LOG.debug("Analyses project " + project.getName()); + + for (IResource resource : changedFiles) { + // LOG.debug("Analyses resource " + resource.getName()); + + // ... and first check, if the project is the right one + if (project.equals(resource.getProject())) { + AbstractPMDRecord rec = projectRec.findResource(resource); + if (rec != null && rec.getResourceType() == IResource.FILE) { + FileRecord fileRec = (FileRecord) rec; + fileRec.updateChildren(); + if (fileRec.getResource().isAccessible() && fileRec.hasMarkers()) { +// LOG.debug("The file has changed"); + changes.add(fileRec); + } else { +// LOG.debug("The file has been removed"); + projectRec.removeResource(fileRec.getResource()); + removals.add(fileRec); + + // remove parent if no more markers + PackageRecord packageRec = (PackageRecord) fileRec.getParent(); + if (!packageRec.hasMarkers()) { + projectRec.removeResource(fileRec.getParent().getResource()); + removals.add(packageRec); + } + } + } else if (rec == null) { + // LOG.debug("This is a new file."); + AbstractPMDRecord fileRec = projectRec.addResource(resource); + additions.add(fileRec); + } else { +// LOG.debug("The resource found is not a file! type found : " + rec.getResourceType()); + } + } else { +// LOG.debug("The project resource is not the same! (" + resource.getProject().getName() + ')'); + } + } + + return new List[] { additions, removals, changes }; + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ChangeRecord.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ChangeRecord.java new file mode 100755 index 00000000000..018910bd072 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ChangeRecord.java @@ -0,0 +1,62 @@ +package net.sourceforge.pmd.eclipse.ui.views; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * + * @author Brian Remedios + * + */ +public class ChangeRecord<T extends Object> { + + final List<T> additions = new ArrayList<T>(); + final List<T> removals = new ArrayList<T>(); + final List<T> changes = new ArrayList<T>(); + + public ChangeRecord() { } + + public boolean hasAdditions() { + return !additions.isEmpty(); + } + + public boolean hasRemovals() { + return !removals.isEmpty(); + } + + public boolean hasChanges() { + return !changes.isEmpty(); + } + + public void added(T record) { + additions.add(record); + } + + public void added(Collection<T> record) { + additions.addAll(record); + } + + public void removed(T record) { + removals.add(record); + } + + public void removed(Collection<T> record) { + removals.addAll(record); + } + + public void changed(T record) { + changes.add(record); + } + + public void changed(Collection<T> record) { + changes.addAll(record); + } + + public void mergeWith(ChangeRecord<T> otherRecord) { + added(otherRecord.additions); + removed(otherRecord.removals); + changed(otherRecord.changes); + } + +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutline.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutline.java index 96038520f09..fbed0006d34 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutline.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutline.java @@ -2,7 +2,6 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; import java.util.List; import net.sourceforge.pmd.RulePriority; @@ -60,6 +59,7 @@ public void createPartControl(Composite parent) { getSite().setSelectionProvider(this); } + protected String pageMessageId() { return StringKeys.MSGKEY_VIEW_OUTLINE_DEFAULT_TEXT; } protected String mementoFileId() { return PMDUiConstants.MEMENTO_OUTLINE_FILE; } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineContentProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineContentProvider.java index fd582418c16..aa19844c0e5 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineContentProvider.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineContentProvider.java @@ -3,7 +3,7 @@ import java.util.ArrayList; import java.util.List; -import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; +import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; import net.sourceforge.pmd.eclipse.ui.model.FileRecord; import net.sourceforge.pmd.eclipse.util.Util; @@ -69,27 +69,27 @@ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } tableViewer = (TableViewer) viewer; } - + /* @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) */ public void resourceChanged(IResourceChangeEvent event) { - IMarkerDelta[] markerDeltas = event.findMarkerDeltas(PMDRuntimeConstants.PMD_MARKER, true); + + if (resource == null || !resource.getResource().exists()) return; + + List<IMarkerDelta> markerDeltas = MarkerUtil.markerDeltasIn(event); - if (!resource.getResource().exists() - || resource == null - || markerDeltas == null) - return; + if (markerDeltas.isEmpty()) return; // we search for removed, added or changed Markers final List<IMarker> additions = new ArrayList<IMarker>(); final List<IMarker> removals = new ArrayList<IMarker>(); final List<IMarker> changes = new ArrayList<IMarker>(); - for (int i=0; i<markerDeltas.length; i++) { - if (!markerDeltas[i].getResource().equals(resource.getResource())) + for (IMarkerDelta delta : markerDeltas) { + if (!delta.getResource().equals(resource.getResource())) continue; - IMarker marker = markerDeltas[i].getMarker(); - switch (markerDeltas[i].getKind()) { + IMarker marker = delta.getMarker(); + switch (delta.getKind()) { case IResourceDelta.ADDED: additions.add(marker); break; diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineLabelProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineLabelProvider.java index d7c86e0b286..7fec79d6b43 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineLabelProvider.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOutlineLabelProvider.java @@ -7,22 +7,14 @@ import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; /** - * Provied the ViolationsOutlinePages with Texts and Labels + * Provides the ViolationsOutlinePages with labels and images * * @author SebastianRaffel ( 08.05.2005 ) */ -public class ViolationOutlineLabelProvider extends LabelProvider implements ITableLabelProvider { - - private static final String KEY_IMAGE_ERR1 = "error1"; - private static final String KEY_IMAGE_ERR2 = "error2"; - private static final String KEY_IMAGE_ERR3 = "error3"; - private static final String KEY_IMAGE_ERR4 = "error4"; - private static final String KEY_IMAGE_ERR5 = "error5"; +public class ViolationOutlineLabelProvider extends AbstractViolationLabelProvider { /* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) */ public Image getColumnImage(Object element, int columnIndex) { @@ -37,24 +29,10 @@ public Image getColumnImage(Object element, int columnIndex) { try { priority = (Integer) marker.getAttribute(PMDUiConstants.KEY_MARKERATT_PRIORITY); } catch (CoreException ce) { - PMDPlugin.getDefault().logError(StringKeys.MSGKEY_ERROR_CORE_EXCEPTION + this.toString(), ce); - } - - // set the Image by the Priority of the Error - - switch (priority.intValue()) { - case 1: - return getImage(KEY_IMAGE_ERR1, PMDUiConstants.ICON_LABEL_ERR1); - case 2: - return getImage(KEY_IMAGE_ERR2, PMDUiConstants.ICON_LABEL_ERR2); - case 3: - return getImage(KEY_IMAGE_ERR3, PMDUiConstants.ICON_LABEL_ERR3); - case 4: - return getImage(KEY_IMAGE_ERR4, PMDUiConstants.ICON_LABEL_ERR4); - case 5: - return getImage(KEY_IMAGE_ERR5, PMDUiConstants.ICON_LABEL_ERR5); + PMDPlugin.getDefault().logError(StringKeys.MSGKEY_ERROR_CORE_EXCEPTION + toString(), ce); } + return getPriorityImage(priority); } return null; @@ -80,14 +58,4 @@ public String getColumnText(Object element, int columnIndex) { return ""; } - /** - * - * @param key - * @param iconPath - * @return - */ - private Image getImage(String key, String iconPath) { - return PMDPlugin.getDefault().getImage(key, iconPath); - } - } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverview.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverview.java index a3bf84a7630..75efb4b82ff 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverview.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverview.java @@ -87,21 +87,21 @@ */ public class ViolationOverview extends ViewPart implements ISelectionProvider, ITreeViewerListener { // NOPMD by Sven on 13.11.06 11:45 - private TreeViewer treeViewer; - private ViolationOverviewContentProvider contentProvider; - private ViolationOverviewLabelProvider labelProvider; - private PriorityFilter priorityFilter; - private ProjectFilter projectFilter; + private TreeViewer treeViewer; + private ViolationOverviewContentProvider contentProvider; + private ViolationOverviewLabelProvider labelProvider; + private PriorityFilter priorityFilter; + private ProjectFilter projectFilter; + private ViolationOverviewMenuManager menuManager; private ViolationOverviewDoubleClickListener doubleClickListener; - private ViolationOverviewMenuManager menuManager; - private RootRecord root; - private ViewMemento memento; + private RootRecord root; + private ViewMemento memento; - protected final Integer[] columnWidths = new Integer[5]; - protected final int[] columnSortOrder = { 1, -1, -1, -1, 1 }; - protected int currentSortedColumn; - private int showType; + protected final Integer[] columnWidths = new Integer[5]; + protected final int[] columnSortOrder = { 1, -1, -1, -1, 1 }; + protected int currentSortedColumn; + private int showType; protected final static String PACKAGE_SWITCH = "packageSwitch"; protected final static String PRIORITY_LIST = "priorityFilterList"; @@ -109,18 +109,9 @@ public class ViolationOverview extends ViewPart implements ISelectionProvider, I protected final static String COLUMN_WIDTHS = "tableColumnWidths"; protected final static String COLUMN_SORTER = "tableColumnSorter"; - /** - * Shows packages -> files -> markers. - */ - public final static int SHOW_PACKAGES_FILES_MARKERS = 1; - /** - * Shows files -> markers without packages. - */ - public final static int SHOW_FILES_MARKERS = 2; - /** - * Shows markers -> files without packages. - */ - public final static int SHOW_MARKERS_FILES = 3; + public final static int SHOW_PACKAGES_FILES_MARKERS = 1; // Shows packages -> files -> markers + public final static int SHOW_FILES_MARKERS = 2; // Shows files -> markers without packages + public final static int SHOW_MARKERS_FILES = 3; // Shows markers -> files without packages /** * @see org.eclipse.ui.ViewPart#init(org.eclipse.ui.IViewSite) @@ -131,22 +122,21 @@ public void init(IViewSite site) throws PartInitException { // init the View, create Content-, LabelProvider and Filters // this is called before createPartControl() - this.root = (RootRecord) getInitialInput(); - this.contentProvider = new ViolationOverviewContentProvider(this); - this.labelProvider = new ViolationOverviewLabelProvider(this); - this.priorityFilter = new PriorityFilter(); - this.projectFilter = new ProjectFilter(); - this.doubleClickListener = new ViolationOverviewDoubleClickListener(this); - this.menuManager = new ViolationOverviewMenuManager(this); + root = (RootRecord) getInitialInput(); + contentProvider = new ViolationOverviewContentProvider(this); + labelProvider = new ViolationOverviewLabelProvider(this); + priorityFilter = new PriorityFilter(); + projectFilter = new ProjectFilter(); + doubleClickListener = new ViolationOverviewDoubleClickListener(this); + menuManager = new ViolationOverviewMenuManager(this); - this.showType = SHOW_PACKAGES_FILES_MARKERS; + showType = SHOW_PACKAGES_FILES_MARKERS; // we can load the Memento here - this.memento = new ViewMemento(PMDUiConstants.MEMENTO_OVERVIEW_FILE); - if (this.memento != null) { + memento = new ViewMemento(PMDUiConstants.MEMENTO_OVERVIEW_FILE); + if (memento != null) { rememberFilterSettings(); } - } /** @@ -154,33 +144,33 @@ public void init(IViewSite site) throws PartInitException { */ @Override public void createPartControl(Composite parent) { - this.treeViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); - this.treeViewer.setUseHashlookup(true); - this.treeViewer.getTree().setHeaderVisible(true); - this.treeViewer.getTree().setLinesVisible(true); + treeViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); + treeViewer.setUseHashlookup(true); + treeViewer.getTree().setHeaderVisible(true); + treeViewer.getTree().setLinesVisible(true); // set Content- and LabelProvider as well as Filters - this.treeViewer.setContentProvider(contentProvider); - this.treeViewer.setLabelProvider(labelProvider); - this.treeViewer.addFilter(priorityFilter); - this.treeViewer.addFilter(projectFilter); - this.treeViewer.addTreeListener(this); + treeViewer.setContentProvider(contentProvider); + treeViewer.setLabelProvider(labelProvider); + treeViewer.addFilter(priorityFilter); + treeViewer.addFilter(projectFilter); + treeViewer.addTreeListener(this); - // create the necessary Stuff + // create the necessary stuff menuManager.setupActions(); - createColumns(this.treeViewer.getTree()); + createColumns(treeViewer.getTree()); menuManager.createActionBars(getViewSite().getActionBars().getToolBarManager()); menuManager.createDropDownMenu(getViewSite().getActionBars().getMenuManager()); menuManager.createContextMenu(); // put in the Input // and add Listeners - this.treeViewer.setInput(root); - this.treeViewer.addDoubleClickListener(doubleClickListener); + treeViewer.setInput(root); + treeViewer.addDoubleClickListener(doubleClickListener); getSite().setSelectionProvider(this); // load the State from a Memento into the View if there is one - if (this.memento != null) { + if (memento != null) { rememberTreeSettings(); } } @@ -190,33 +180,35 @@ public void createPartControl(Composite parent) { */ @Override public void dispose() { - this.memento.putList(PRIORITY_LIST, this.priorityFilter.getPriorityFilterList()); + memento.putList(PRIORITY_LIST, priorityFilter.getPriorityFilterList()); // on Dispose of the View we save its State into a Memento // we save the filtered Projects - final List<AbstractPMDRecord> projects = this.projectFilter.getProjectFilterList(); - final List<String> projectNames = new ArrayList<String>(); + List<AbstractPMDRecord> projects = projectFilter.getProjectFilterList(); + List<String> projectNames = new ArrayList<String>(); for (int k = 0; k < projects.size(); k++) { - final AbstractPMDRecord project = projects.get(k); + AbstractPMDRecord project = projects.get(k); projectNames.add(project.getName()); } - this.memento.putList(PROJECT_LIST, projectNames); + memento.putList(PROJECT_LIST, projectNames); // ... the Columns Widths - final List<Integer> widthList = Arrays.asList(columnWidths); - this.memento.putList(COLUMN_WIDTHS, widthList); + List<Integer> widthList = Arrays.asList(columnWidths); + memento.putList(COLUMN_WIDTHS, widthList); // ... what Element is sorted in what way - final Integer[] sorterProps = new Integer[] { Integer.valueOf(currentSortedColumn), - Integer.valueOf(columnSortOrder[currentSortedColumn]) }; - final List<Integer> sorterList = Arrays.asList(sorterProps); + Integer[] sorterProps = new Integer[] { + Integer.valueOf(currentSortedColumn), + Integer.valueOf(columnSortOrder[currentSortedColumn]) + }; + List<Integer> sorterList = Arrays.asList(sorterProps); memento.putList(COLUMN_SORTER, sorterList); // ... and how we should display the Elements - this.memento.putInteger(PACKAGE_SWITCH, getShowType()); + memento.putInteger(PACKAGE_SWITCH, getShowType()); - this.memento.save(PMDUiConstants.MEMENTO_OVERVIEW_FILE); + memento.save(PMDUiConstants.MEMENTO_OVERVIEW_FILE); super.dispose(); } @@ -247,12 +239,12 @@ private void createColumns(Tree tree) { vioTotalColumn.setText(getString(StringKeys.MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_TOTAL)); vioTotalColumn.setWidth(100); - // Violations / Lines of code + // Violations / 1K lines of code (KLOC) final TreeColumn vioLocColumn = new TreeColumn(tree, SWT.RIGHT); - vioLocColumn.setText(getString(StringKeys.MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_LOC)); + vioLocColumn.setText(getString(StringKeys.MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_KLOC)); vioLocColumn.setWidth(100); - // Violations / Number of Methods + // Violations / Method final TreeColumn vioMethodColumn = new TreeColumn(tree, SWT.RIGHT); vioMethodColumn.setText(getString(StringKeys.MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_METHOD)); vioMethodColumn.setWidth(100); @@ -273,17 +265,15 @@ private void createColumns(Tree tree) { * @param tree */ private void createColumnAdapters(Tree tree) { - final TreeColumn[] columns = tree.getColumns(); + TreeColumn[] columns = tree.getColumns(); for (int k = 0; k < columns.length; k++) { - this.columnWidths[k] = Integer.valueOf(columns[k].getWidth()); // NOPMD by Herlin on 09/10/06 15:02 + columnWidths[k] = Integer.valueOf(columns[k].getWidth()); // NOPMD by Herlin on 09/10/06 15:02 - // each Column gets a SelectionAdapter - // on Selection the Column is sorted + // each Column gets a SelectionAdapter on Selection the Column is sorted columns[k].addSelectionListener(new ColumnSelectionAdapter(k)); - // the ResizeListener saves the current Width - // for storing it easily into a Memento later + // the ResizeListener saves the current Width for storing it easily into a Memento later columns[k].addControlListener(new ColumnControlAdapter(k)); } } @@ -342,9 +332,9 @@ private ViewerSorter getViewerSorter(int columnNr) { public int getNumberOfFilteredViolations(AbstractPMDRecord record) { int number = 0; - final List<Integer> filterList = this.priorityFilter.getPriorityFilterList(); + List<Integer> filterList = priorityFilter.getPriorityFilterList(); for (int i = 0; i < filterList.size(); i++) { - final Integer priority = filterList.get(i); + Integer priority = filterList.get(i); number += record.getNumberOfViolationsToPriority( priority.intValue(), getShowType() == SHOW_MARKERS_FILES); } @@ -359,14 +349,14 @@ public int getNumberOfFilteredViolations(AbstractPMDRecord record) { * @see #SHOW_PACKAGES_FILES_MARKERS */ public void setShowType(int type) { - this.showType = type; + showType = type; } /** * @return show type */ public int getShowType() { - return this.showType; + return showType; } /** @@ -374,7 +364,7 @@ public int getShowType() { * @return project filter list */ public List<AbstractPMDRecord> getProjectFilterList() { - return this.projectFilter.getProjectFilterList(); + return projectFilter.getProjectFilterList(); } /** @@ -382,20 +372,20 @@ public List<AbstractPMDRecord> getProjectFilterList() { * @return project filter list */ public List<Integer> getPriorityFilterList() { - return this.priorityFilter.getPriorityFilterList(); + return priorityFilter.getPriorityFilterList(); } /** * Sets the Widths of the Columns */ public void setColumnWidths() { - if (!this.treeViewer.getTree().isDisposed()) { - final TreeColumn[] columns = this.treeViewer.getTree().getColumns(); - for (int k = 0; k < this.columnWidths.length; k++) { - if (this.columnWidths[k] == null) { - this.columnWidths[k] = Integer.valueOf(75); + if (!treeViewer.getTree().isDisposed()) { + TreeColumn[] columns = treeViewer.getTree().getColumns(); + for (int k = 0; k < columnWidths.length; k++) { + if (columnWidths[k] == null) { + columnWidths[k] = Integer.valueOf(75); } - columns[k].setWidth(this.columnWidths[k].intValue()); + columns[k].setWidth(columnWidths[k].intValue()); } } } @@ -409,9 +399,9 @@ public void setColumnWidths() { */ public void setSorterProperties(Integer[] properties) { // NOPMD by Herlin on 09/10/06 15:03 if (properties.length > 0) { - this.currentSortedColumn = properties[0].intValue(); - this.columnSortOrder[this.currentSortedColumn] = properties[1].intValue(); - this.treeViewer.setSorter(getViewerSorter(this.currentSortedColumn)); + currentSortedColumn = properties[0].intValue(); + columnSortOrder[currentSortedColumn] = properties[1].intValue(); + treeViewer.setSorter(getViewerSorter(currentSortedColumn)); } } @@ -420,20 +410,20 @@ public void setSorterProperties(Integer[] properties) { // NOPMD by Herlin on 09 */ @Override public void setFocus() { - this.treeViewer.getTree().setFocus(); + treeViewer.getTree().setFocus(); } /** * @return the viewer */ public TreeViewer getViewer() { - return this.treeViewer; + return treeViewer; } public AbstractPMDRecord[] getAllProjects() { AbstractPMDRecord[] projects = AbstractPMDRecord.EMPTY_RECORDS; - if (this.root != null) { - projects = this.root.getChildren(); + if (root != null) { + projects = root.getChildren(); } return projects; } @@ -444,43 +434,43 @@ public AbstractPMDRecord[] getAllProjects() { public void refresh() { if (!this.treeViewer.getControl().isDisposed()) { //this.treeViewer.getControl().setRedraw(false); - this.treeViewer.refresh(); + treeViewer.refresh(); refreshMenu(); //this.treeViewer.getControl().setRedraw(true); } } public void refreshMenu() { - this.menuManager.createDropDownMenu(getViewSite().getActionBars().getMenuManager()); - this.menuManager.createContextMenu(); + menuManager.createDropDownMenu(getViewSite().getActionBars().getMenuManager()); + menuManager.createContextMenu(); } /** * @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) */ public void addSelectionChangedListener(ISelectionChangedListener listener) { - this.treeViewer.addSelectionChangedListener(listener); + treeViewer.addSelectionChangedListener(listener); } /** * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection() */ public ISelection getSelection() { - return this.treeViewer.getSelection(); + return treeViewer.getSelection(); } /** * @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { - this.treeViewer.removeSelectionChangedListener(listener); + treeViewer.removeSelectionChangedListener(listener); } /** * @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection) */ public void setSelection(ISelection selection) { - this.treeViewer.setSelection(selection); + treeViewer.setSelection(selection); } /** @@ -498,26 +488,26 @@ private String getString(String key) { private void rememberFilterSettings() { // Provide the Filters with their last State - final List<Integer> priorityList = this.memento.getIntegerList(PRIORITY_LIST); + List<Integer> priorityList = memento.getIntegerList(PRIORITY_LIST); if (!priorityList.isEmpty()) { - this.priorityFilter.setPriorityFilterList(priorityList); + priorityFilter.setPriorityFilterList(priorityList); } - final List<String> projectNames = this.memento.getStringList(PROJECT_LIST); + List<String> projectNames = memento.getStringList(PROJECT_LIST); if (!projectNames.isEmpty()) { - final List<AbstractPMDRecord> projectList = new ArrayList<AbstractPMDRecord>(); + List<AbstractPMDRecord> projectList = new ArrayList<AbstractPMDRecord>(); for (int k = 0; k < projectNames.size(); k++) { - final AbstractPMDRecord project = this.root.findResourceByName(projectNames.get(k).toString(), + AbstractPMDRecord project = root.findResourceByName(projectNames.get(k).toString(), AbstractPMDRecord.TYPE_PROJECT); if (project != null) { projectList.add(project); } } - this.projectFilter.setProjectFilterList(projectList); + projectFilter.setProjectFilterList(projectList); } - final Integer type = this.memento.getInteger(PACKAGE_SWITCH); + Integer type = memento.getInteger(PACKAGE_SWITCH); if (type != null) { setShowType(type.intValue()); } @@ -531,16 +521,16 @@ private void rememberFilterSettings() { private void rememberTreeSettings() { // the Memento sets the Widths of Columns - final List<Integer> widthList = this.memento.getIntegerList(COLUMN_WIDTHS); + List<Integer> widthList = memento.getIntegerList(COLUMN_WIDTHS); if (!widthList.isEmpty()) { widthList.toArray(this.columnWidths); setColumnWidths(); } // ... and also the Sorter - final List<Integer> sorterList = this.memento.getIntegerList(COLUMN_SORTER); + List<Integer> sorterList = memento.getIntegerList(COLUMN_SORTER); if (!sorterList.isEmpty()) { - final Integer[] sorterProps = new Integer[sorterList.size()]; + Integer[] sorterProps = new Integer[sorterList.size()]; sorterList.toArray(sorterProps); setSorterProperties(sorterProps); } @@ -707,13 +697,13 @@ public void treeCollapsed(TreeExpansionEvent event) { * @see org.eclipse.jface.viewers.ITreeViewerListener#treeExpanded(org.eclipse.jface.viewers.TreeExpansionEvent) */ public void treeExpanded(TreeExpansionEvent event) { - final Object object = event.getElement(); + Object object = event.getElement(); if (object instanceof PackageRecord) { - final PackageRecord record = (PackageRecord) object; - final AbstractPMDRecord[] children = record.getChildren(); + PackageRecord record = (PackageRecord) object; + AbstractPMDRecord[] children = record.getChildren(); for (AbstractPMDRecord element : children) { if (element instanceof FileRecord) { - final FileRecord fileRecord = (FileRecord) element; + FileRecord fileRecord = (FileRecord) element; fileRecord.calculateLinesOfCode(); fileRecord.calculateNumberOfMethods(); } @@ -737,7 +727,7 @@ public void run() { */ public void deleteMarkers(AbstractPMDRecord element) throws CoreException { if (element instanceof MarkerRecord) { - final MarkerRecord record = (MarkerRecord) element; + MarkerRecord record = (MarkerRecord) element; IMarker[] markers = MarkerUtil.EMPTY_MARKERS; switch (getShowType()) { @@ -747,7 +737,7 @@ public void deleteMarkers(AbstractPMDRecord element) throws CoreException { markers = record.findMarkers(); break; case SHOW_MARKERS_FILES: - final AbstractPMDRecord packRec = record.getParent().getParent(); + AbstractPMDRecord packRec = record.getParent().getParent(); markers = packRec.findMarkersByAttribute(PMDUiConstants.KEY_MARKERATT_RULENAME, record.getName()); break; default: @@ -755,19 +745,19 @@ public void deleteMarkers(AbstractPMDRecord element) throws CoreException { } deleteMarkers(markers); } else if (element instanceof FileToMarkerRecord) { - final FileToMarkerRecord record = (FileToMarkerRecord) element; + FileToMarkerRecord record = (FileToMarkerRecord) element; IMarker[] markers = record.findMarkers(); deleteMarkers(markers); } else if (element instanceof AbstractPMDRecord) { // simply delete markers from resource - final AbstractPMDRecord record = element; + AbstractPMDRecord record = element; MarkerUtil.deleteAllMarkersIn(record.getResource()); } } private void deleteMarkers(IMarker[] markers) { if (markers.length > 0) { - final DeleteMarkersCommand cmd = new DeleteMarkersCommand(); + DeleteMarkersCommand cmd = new DeleteMarkersCommand(); cmd.setMarkers(markers); try { cmd.performExecute(); @@ -822,7 +812,7 @@ public ColumnSelectionAdapter(int column) { @Override public void widgetSelected(SelectionEvent e) { columnSortOrder[this.column] *= -1; - treeViewer.setSorter(getViewerSorter(this.column)); + treeViewer.setSorter(getViewerSorter(column)); } } @@ -839,7 +829,7 @@ public ColumnControlAdapter(int column) { @Override public void controlResized(ControlEvent e) { - columnWidths[this.column] = Integer.valueOf(treeViewer.getTree().getColumn(this.column).getWidth()); + columnWidths[column] = Integer.valueOf(treeViewer.getTree().getColumn(column).getWidth()); } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewContentProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewContentProvider.java index a6fd44a0f86..7b4f3739d5c 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewContentProvider.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewContentProvider.java @@ -41,7 +41,6 @@ import java.util.List; import java.util.Map; -import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; import net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord; import net.sourceforge.pmd.eclipse.ui.model.FileRecord; import net.sourceforge.pmd.eclipse.ui.model.FileToMarkerRecord; @@ -53,9 +52,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.eclipse.core.resources.IMarkerDelta; -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.IWorkspaceRoot; @@ -80,6 +76,7 @@ public class ViolationOverviewContentProvider implements ITreeContentProvider, I private TreeViewer treeViewer; private RootRecord root; + private ChangeEvaluator changeEvaluator; /** * Constructor @@ -89,8 +86,8 @@ public class ViolationOverviewContentProvider implements ITreeContentProvider, I public ViolationOverviewContentProvider(ViolationOverview view) { super(); - this.violationView = view; - this.treeViewer = view.getViewer(); + violationView = view; + treeViewer = view.getViewer(); } /** @@ -98,7 +95,7 @@ public ViolationOverviewContentProvider(ViolationOverview view) { */ public void dispose() { if (root != null) { - final IWorkspaceRoot workspaceRoot = (IWorkspaceRoot) this.root.getResource(); + IWorkspaceRoot workspaceRoot = (IWorkspaceRoot) root.getResource(); workspaceRoot.getWorkspace().removeResourceChangeListener(this); } } @@ -156,15 +153,12 @@ private Object[] getChildrenOfMarker(MarkerRecord record) { */ private Object[] getChildrenOfPackage(PackageRecord record) { - if (this.violationView.getShowType() == ViolationOverview.SHOW_MARKERS_FILES) { - final Map<String, AbstractPMDRecord> markers = new HashMap<String, AbstractPMDRecord>(); - final List<AbstractPMDRecord> files = record.getChildrenAsList(); - for (int i = 0; i < files.size(); i++) { - final AbstractPMDRecord fileRec = files.get(i); - final List<AbstractPMDRecord> newMarkers = fileRec.getChildrenAsList(); - - for (int j = 0; j < newMarkers.size(); j++) { - final AbstractPMDRecord markerRec = newMarkers.get(j); + if (violationView.getShowType() == ViolationOverview.SHOW_MARKERS_FILES) { + Map<String, AbstractPMDRecord> markers = new HashMap<String, AbstractPMDRecord>(); + List<AbstractPMDRecord> files = record.getChildrenAsList(); + for (AbstractPMDRecord fileRec : files) { + List<AbstractPMDRecord> newMarkers = fileRec.getChildrenAsList(); + for (AbstractPMDRecord markerRec : newMarkers) { markers.put(markerRec.getName(), markerRec); } } @@ -182,19 +176,19 @@ private Object[] getChildrenOfPackage(PackageRecord record) { private Object[] getChildrenOfRoot() { // ... we care about its Project's - final List<AbstractPMDRecord> projects = root.getChildrenAsList(); - final ProjectRecord[] projectArray = new ProjectRecord[projects.size()]; + List<AbstractPMDRecord> projects = root.getChildrenAsList(); + ProjectRecord[] projectArray = new ProjectRecord[projects.size()]; projects.toArray(projectArray); // we make a List of all Packages - final List<AbstractPMDRecord> packages = new ArrayList<AbstractPMDRecord>(); + List<AbstractPMDRecord> packages = new ArrayList<AbstractPMDRecord>(); for (ProjectRecord element : projectArray) { if (element.isProjectOpen()) { packages.addAll(element.getChildrenAsList()); } } - switch (this.violationView.getShowType()) { + switch (violationView.getShowType()) { case ViolationOverview.SHOW_MARKERS_FILES: case ViolationOverview.SHOW_PACKAGES_FILES_MARKERS: // show packages @@ -202,9 +196,8 @@ private Object[] getChildrenOfRoot() { case ViolationOverview.SHOW_FILES_MARKERS: // show files - final List<AbstractPMDRecord> files = new ArrayList<AbstractPMDRecord>(); - for (int j = 0; j < packages.size(); j++) { - final AbstractPMDRecord packageRec = packages.get(j); + List<AbstractPMDRecord> files = new ArrayList<AbstractPMDRecord>(); + for (AbstractPMDRecord packageRec : packages) { files.addAll(packageRec.getChildrenAsList()); } @@ -221,12 +214,12 @@ private Object[] getChildrenOfRoot() { */ public Object getParent(Object element) { Object parent = null; - final AbstractPMDRecord record = (AbstractPMDRecord) element; + AbstractPMDRecord record = (AbstractPMDRecord) element; switch (violationView.getShowType()) { case ViolationOverview.SHOW_FILES_MARKERS: if (element instanceof FileRecord) { - parent = this.root; + parent = root; } else { parent = record.getParent(); } @@ -235,7 +228,7 @@ public Object getParent(Object element) { if (element instanceof FileToMarkerRecord) { parent = record.getParent(); } else if (element instanceof PackageRecord) { - parent = this.root; + parent = root; } else if (element instanceof MarkerRecord) { parent = record.getParent().getParent(); } @@ -243,7 +236,7 @@ public Object getParent(Object element) { break; case ViolationOverview.SHOW_PACKAGES_FILES_MARKERS: if (element instanceof PackageRecord) { - parent = this.root; + parent = root; } else { parent = record.getParent(); } @@ -287,16 +280,16 @@ public boolean hasChildren(Object element) { */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { LOG.debug("ViolationOverview inputChanged"); - this.treeViewer = (TreeViewer) viewer; + treeViewer = (TreeViewer) viewer; // this is called, when the View is instantiated and gets Input // or if the Source of Input changes // we remove an existing ResourceChangeListener IWorkspaceRoot workspaceRoot = null; - if (this.root != null) { + if (root != null) { LOG.debug("remove current listener"); - workspaceRoot = (IWorkspaceRoot) this.root.getResource(); + workspaceRoot = (IWorkspaceRoot) root.getResource(); workspaceRoot.getWorkspace().removeResourceChangeListener(this); } @@ -306,90 +299,106 @@ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { LOG.debug("the new input is a workspace root"); // either we got a WorkspaceRoot workspaceRoot = (IWorkspaceRoot) newInput; - this.root = new RootRecord(workspaceRoot); + root = new RootRecord(workspaceRoot); workspaceRoot.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); } else if (newInput instanceof RootRecord) { LOG.debug("the new input is a root record"); // ... or already a Record for it - this.root = (RootRecord) newInput; - workspaceRoot = (IWorkspaceRoot) this.root.getResource(); + root = (RootRecord) newInput; + workspaceRoot = (IWorkspaceRoot) root.getResource(); workspaceRoot.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); } + + changeEvaluator = new ChangeEvaluator(root); } /** * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) */ public void resourceChanged(IResourceChangeEvent event) { - LOG.debug("resource changed event"); - final IMarkerDelta[] markerDeltas = event.findMarkerDeltas(PMDRuntimeConstants.PMD_MARKER, true); - - // first we get a List of changes to Files and Projects - // so we won't need updating everything - final List<IResource> changedFiles = new ArrayList<IResource>(); - final List<IProject> changedProjects = new ArrayList<IProject>(); - for (IMarkerDelta markerDelta : markerDeltas) { - final IResource resource = markerDelta.getResource(); - final IProject project = resource.getProject(); - - // the lists should not contain - // Projects or Resources twice - - if (!changedFiles.contains(resource)) { - changedFiles.add(resource); - LOG.debug("Resource " + resource.getName() + " has changed"); - } - if (!changedProjects.contains(project)) { - changedProjects.add(project); - LOG.debug("Project " + project.getName() + " has changed"); - } - } - - // we can add, change or remove Resources - // all this changes are given to the viewer later - final List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); - final List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); - final List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); - - // we got through the changed Projects - for (IProject project : changedProjects) { - LOG.debug("Processing changes for project " + project.getName()); - ProjectRecord projectRec = (ProjectRecord) this.root.findResource(project); - - // if the Project is closed or deleted, - // we also delete it from the Model and go on - if (!(project.isOpen() && project.isAccessible())) { // NOPMD by Sven on 09.11.06 22:17 - LOG.debug("The project is not open or not accessible. Remove it"); - final List<AbstractPMDRecord>[] array = updateFiles(project, changedFiles); - removals.addAll(array[1]); - this.root.removeResource(project); - } - - // if we couldn't find the Project - // then it has to be new - else if (projectRec == null) { - LOG.debug("Cannot find a project record for it. Add it."); - projectRec = (ProjectRecord) this.root.addResource(project); - } + final ChangeRecord<AbstractPMDRecord> changes = changeEvaluator.changeRecordFor(event); - // then we can update the Files for the new or updated Project - final List<AbstractPMDRecord>[] array = updateFiles(project, changedFiles); - additions.addAll(array[0]); - removals.addAll(array[1]); - changes.addAll(array[2]); - } - - // the additions, removals and changes are given to the viewer - // so that it can update itself - // updating the table MUST be in sync - this.treeViewer.getControl().getDisplay().syncExec(new Runnable() { - public void run() { - updateViewer(additions, removals, changes); - } - }); + // the additions, removals and changes are given to the viewer so that it can update itself + // updating the table MUST be in sync + treeViewer.getControl().getDisplay().syncExec(new Runnable() { + public void run() { + updateViewer(changes); + } + }); } +// public void resourceChanged(IResourceChangeEvent event) { +// +// LOG.debug("resource changed event"); +// +// List<IMarkerDelta> markerDeltas = MarkerUtil.markerDeltasIn(event); +// +// // first we get a List of changes to Files and Projects +// // so we won't need updating everything +// List<IResource> changedFiles = new ArrayList<IResource>(); +// List<IProject> changedProjects = new ArrayList<IProject>(); +// for (IMarkerDelta markerDelta : markerDeltas) { +// IResource resource = markerDelta.getResource(); +// IProject project = resource.getProject(); +// +// // the lists should not contain Projects or Resources twice +// +// if (!changedFiles.contains(resource)) { +// changedFiles.add(resource); +// LOG.debug("Resource " + resource.getName() + " has changed"); +// } +// +// if (!changedProjects.contains(project)) { +// changedProjects.add(project); +// LOG.debug("Project " + project.getName() + " has changed"); +// } +// } +// +// // we can add, change or remove Resources +// // all this changes are given to the viewer later +// final List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); +// final List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); +// final List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); +// +// // we go through the changed Projects +// for (IProject project : changedProjects) { +// LOG.debug("Processing changes for project " + project.getName()); +// ProjectRecord projectRec = (ProjectRecord) root.findResource(project); +// +// // if the Project is closed or deleted, +// // we also delete it from the Model and go on +// if (!(project.isOpen() && project.isAccessible())) { // NOPMD by Sven on 09.11.06 22:17 +// LOG.debug("The project is not open or not accessible. Remove it"); +// List<AbstractPMDRecord>[] array = updateFiles(project, changedFiles); +// removals.addAll(array[1]); +// root.removeResource(project); +// } +// +// // if we couldn't find the Project +// // then it has to be new +// else if (projectRec == null) { +// LOG.debug("Cannot find a project record for it. Add it."); +// projectRec = (ProjectRecord) root.addResource(project); +// } +// +// // then we can update the Files for the new or updated Project +// List<AbstractPMDRecord>[] array = updateFiles(project, changedFiles); +// additions.addAll(array[0]); +// removals.addAll(array[1]); +// changes.addAll(array[2]); +// } +// +// // the additions, removals and changes are given to the viewer +// // so that it can update itself +// // updating the table MUST be in sync +// treeViewer.getControl().getDisplay().syncExec(new Runnable() { +// public void run() { +// updateViewer(additions, removals, changes); +// } +// }); +// } + /** * Updates the Files for a given Project * @@ -398,90 +407,91 @@ public void run() { * @return an List of Lists containing additions [0], removals [1] * and changes [2] (Array-Position in Brackets) */ - protected List<AbstractPMDRecord>[] updateFiles(IProject project, List<IResource> changedFiles) { - final List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); - final List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); - final List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); - List<AbstractPMDRecord>[] updatedFiles = new List[] { additions, removals, changes }; - - // we search for the ProjectRecord to the Project - // if it doesn't exist, we return nothing - final ProjectRecord projectRec = (ProjectRecord) this.root.findResource(project); - - // we got through all files - if (projectRec != null && project.isAccessible()) { - updatedFiles = searchProjectForModifications(projectRec, changedFiles); - } - - // if the project is deleted or closed - else if (projectRec != null) { - final List<AbstractPMDRecord> packages = projectRec.getChildrenAsList(); - // ... we add all Packages to the removals - // so they are not shown anymore - removals.addAll(packages); - for (int k = 0; k < packages.size(); k++) { - final PackageRecord packageRec = (PackageRecord) packages.get(k); - removals.addAll(packageRec.getChildrenAsList()); - } - updatedFiles = new List[] { additions, removals, changes }; - } - - return updatedFiles; - } - - /** - * Analyzes the modification inside a single project and compute the list of additions, updates and removals. - * - * @param projectRec - * @param changedFiles - * @return - */ - private List<AbstractPMDRecord>[] searchProjectForModifications(ProjectRecord projectRec, List<IResource> changedFiles) { - final List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); - final List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); - final List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); - final IProject project = (IProject) projectRec.getResource(); - - LOG.debug("Analyses project " + project.getName()); - - for (IResource resource : changedFiles) { - LOG.debug("Analyses resource " + resource.getName()); - - // ... and first check, if the project is the right one - if (project.equals(resource.getProject())) { - final AbstractPMDRecord rec = projectRec.findResource(resource); - if (rec != null && rec.getResourceType() == IResource.FILE) { - final FileRecord fileRec = (FileRecord) rec; - fileRec.updateChildren(); - if (fileRec.getResource().isAccessible() && fileRec.hasMarkers()) { - LOG.debug("The file has changed"); - changes.add(fileRec); - } else { - LOG.debug("The file has been removed"); - projectRec.removeResource(fileRec.getResource()); - removals.add(fileRec); - - // remove parent if no more markers - final PackageRecord packageRec = (PackageRecord) fileRec.getParent(); - if (!packageRec.hasMarkers()) { - projectRec.removeResource(fileRec.getParent().getResource()); - removals.add(packageRec); - } - } - } else if (rec == null) { - LOG.debug("This is a new file."); - final AbstractPMDRecord fileRec = projectRec.addResource(resource); - additions.add(fileRec); - } else { - LOG.debug("The resource found is not a file! type found : " + rec.getResourceType()); - } - } else { - LOG.debug("The project resource is not the same! (" + resource.getProject().getName() + ')'); - } - } - - return new List[] { additions, removals, changes }; - } +// protected List<AbstractPMDRecord>[] updateFiles(IProject project, List<IResource> changedFiles) { +// +// final List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); +// final List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); +// final List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); +// List<AbstractPMDRecord>[] updatedFiles = new List[] { additions, removals, changes }; +// +// // we search for the ProjectRecord to the Project +// // if it doesn't exist, we return nothing +// final ProjectRecord projectRec = (ProjectRecord) root.findResource(project); +// +// // we got through all files +// if (projectRec != null && project.isAccessible()) { +// updatedFiles = ChangeEvaluator.searchProjectForModifications(projectRec, changedFiles); +// } +// +// // if the project is deleted or closed +// else if (projectRec != null) { +// final List<AbstractPMDRecord> packages = projectRec.getChildrenAsList(); +// // ... we add all Packages to the removals +// // so they are not shown anymore +// removals.addAll(packages); +// for (int k = 0; k < packages.size(); k++) { +// final PackageRecord packageRec = (PackageRecord) packages.get(k); +// removals.addAll(packageRec.getChildrenAsList()); +// } +// updatedFiles = new List[] { additions, removals, changes }; +// } +// +// return updatedFiles; +// } + +// /** +// * Analyzes the modification inside a single project and compute the list of additions, updates and removals. +// * +// * @param projectRec +// * @param changedFiles +// * @return +// */ +// private List<AbstractPMDRecord>[] searchProjectForModifications(ProjectRecord projectRec, List<IResource> changedFiles) { +// final List<AbstractPMDRecord> additions = new ArrayList<AbstractPMDRecord>(); +// final List<AbstractPMDRecord> removals = new ArrayList<AbstractPMDRecord>(); +// final List<AbstractPMDRecord> changes = new ArrayList<AbstractPMDRecord>(); +// final IProject project = (IProject) projectRec.getResource(); +// +// LOG.debug("Analyses project " + project.getName()); +// +// for (IResource resource : changedFiles) { +// LOG.debug("Analyses resource " + resource.getName()); +// +// // ... and first check, if the project is the right one +// if (project.equals(resource.getProject())) { +// final AbstractPMDRecord rec = projectRec.findResource(resource); +// if (rec != null && rec.getResourceType() == IResource.FILE) { +// final FileRecord fileRec = (FileRecord) rec; +// fileRec.updateChildren(); +// if (fileRec.getResource().isAccessible() && fileRec.hasMarkers()) { +// LOG.debug("The file has changed"); +// changes.add(fileRec); +// } else { +// LOG.debug("The file has been removed"); +// projectRec.removeResource(fileRec.getResource()); +// removals.add(fileRec); +// +// // remove parent if no more markers +// final PackageRecord packageRec = (PackageRecord) fileRec.getParent(); +// if (!packageRec.hasMarkers()) { +// projectRec.removeResource(fileRec.getParent().getResource()); +// removals.add(packageRec); +// } +// } +// } else if (rec == null) { +// LOG.debug("This is a new file."); +// final AbstractPMDRecord fileRec = projectRec.addResource(resource); +// additions.add(fileRec); +// } else { +// LOG.debug("The resource found is not a file! type found : " + rec.getResourceType()); +// } +// } else { +// LOG.debug("The project resource is not the same! (" + resource.getProject().getName() + ')'); +// } +// } +// +// return new List[] { additions, removals, changes }; +// } /** * Applies found updates on the table, adapted from Philippe Herlin @@ -490,31 +500,57 @@ private List<AbstractPMDRecord>[] searchProjectForModifications(ProjectRecord pr * @param removals * @param changes */ - protected void updateViewer(List<AbstractPMDRecord> additions, List<AbstractPMDRecord> removals, List<AbstractPMDRecord> changes) { +// protected void updateViewer(List<AbstractPMDRecord> additions, List<AbstractPMDRecord> removals, List<AbstractPMDRecord> changes) { +// +// // perform removals +// if (removals.size() > 0) { +// treeViewer.cancelEditing(); +// treeViewer.remove(removals.toArray()); +// } +// +// // perform additions +// if (additions.size() > 0) { +// for (int i = 0; i < additions.size(); i++) { +// final AbstractPMDRecord addedRec = additions.get(i); +// if (addedRec instanceof FileRecord) { +// treeViewer.add(addedRec.getParent(), addedRec); +// } else { +// treeViewer.add(root, addedRec); +// } +// } +// } +// +// // perform changes +// if (changes.size() > 0) { +// treeViewer.update(changes.toArray(), null); +// } +// +// violationView.refresh(); +// } + + protected void updateViewer(ChangeRecord<AbstractPMDRecord> changes) { // perform removals - if (removals.size() > 0) { - this.treeViewer.cancelEditing(); - this.treeViewer.remove(removals.toArray()); + if (changes.hasRemovals()) { + treeViewer.cancelEditing(); + treeViewer.remove(changes.removals.toArray()); } - // perform additions - if (additions.size() > 0) { - for (int i = 0; i < additions.size(); i++) { - final AbstractPMDRecord addedRec = additions.get(i); - if (addedRec instanceof FileRecord) { - this.treeViewer.add(addedRec.getParent(), addedRec); - } else { - this.treeViewer.add(this.root, addedRec); - } - } + // perform additions (if any) + for (AbstractPMDRecord addedRec : changes.additions) { + if (addedRec instanceof FileRecord) { + treeViewer.add(addedRec.getParent(), addedRec); + } else { + treeViewer.add(root, addedRec); + } } + // perform changes - if (changes.size() > 0) { - this.treeViewer.update(changes.toArray(), null); + if (changes.hasChanges()) { + treeViewer.update(changes.changes.toArray(), null); } - this.violationView.refresh(); + violationView.refresh(); } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewLabelProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewLabelProvider.java index 0408a3e0b3e..c70e75d2985 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewLabelProvider.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewLabelProvider.java @@ -38,10 +38,14 @@ import java.text.DecimalFormat; import java.text.NumberFormat; +import java.util.HashMap; import java.util.Locale; +import java.util.Map; import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.RulePriority; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.plugin.UISettings; import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; import net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord; @@ -50,6 +54,7 @@ import net.sourceforge.pmd.eclipse.ui.model.MarkerRecord; import net.sourceforge.pmd.eclipse.ui.model.PackageRecord; +import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; @@ -60,14 +65,10 @@ * @author SebastianRaffel ( 09.05.2005 ), Philippe Herlin * */ -public class ViolationOverviewLabelProvider extends LabelProvider implements ITableLabelProvider { +public class ViolationOverviewLabelProvider extends AbstractViolationLabelProvider { + private static final String KEY_IMAGE_PACKAGE = "package"; private static final String KEY_IMAGE_JAVAFILE = "javafile"; - private static final String KEY_IMAGE_ERR1 = "error1"; - private static final String KEY_IMAGE_ERR2 = "error2"; - private static final String KEY_IMAGE_ERR3 = "error3"; - private static final String KEY_IMAGE_ERR4 = "error4"; - private static final String KEY_IMAGE_ERR5 = "error5"; private final ViolationOverview violationView; @@ -78,12 +79,11 @@ public class ViolationOverviewLabelProvider extends LabelProvider implements ITa */ public ViolationOverviewLabelProvider(ViolationOverview overview) { super(); - this.violationView = overview; + violationView = overview; } - + /** - * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, - * int) + * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) */ public Image getColumnImage(Object element, int columnIndex) { Image image = null; @@ -95,46 +95,15 @@ public Image getColumnImage(Object element, int columnIndex) { } else if (element instanceof FileRecord || element instanceof FileToMarkerRecord) { image = getImage(KEY_IMAGE_JAVAFILE, PMDUiConstants.ICON_JAVACU); } else if (element instanceof MarkerRecord) { - final MarkerRecord markerRecord = (MarkerRecord)element; - final int priority = markerRecord.getPriority(); + MarkerRecord markerRecord = (MarkerRecord)element; + int priority = markerRecord.getPriority(); image = getPriorityImage(priority); } } return image; } - - /** - * Gets the image to a priority. - * @param priority priority - * @return Image - */ - private Image getPriorityImage(int priority) { - Image image = null; - - switch (priority) { - case 1: - image = getImage(KEY_IMAGE_ERR1, PMDUiConstants.ICON_LABEL_ERR1); - break; - case 2: - image = getImage(KEY_IMAGE_ERR2, PMDUiConstants.ICON_LABEL_ERR2); - break; - case 3: - image = getImage(KEY_IMAGE_ERR3, PMDUiConstants.ICON_LABEL_ERR3); - break; - case 4: - image = getImage(KEY_IMAGE_ERR4, PMDUiConstants.ICON_LABEL_ERR4); - break; - case 5: - image = getImage(KEY_IMAGE_ERR5, PMDUiConstants.ICON_LABEL_ERR5); - break; - default: - // do nothing - } - - return image; - } - + /** * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, * int) @@ -156,9 +125,9 @@ public String getColumnText(Object element, int columnIndex) { result = getNumberOfViolations(record); break; - // show the Number of Violations per Line of Code + // show the Number of Violations per 1K lines of code case 2: - result = getViolationsPerLOC(record); + result = getViolationsPerKLOC(record); break; // show the Number of Violations per Number of Methods @@ -253,21 +222,21 @@ private String getElementName(Object element) { * @param element * @return */ - private String getViolationsPerLOC(AbstractPMDRecord element) { + private String getViolationsPerKLOC(AbstractPMDRecord element) { String result = ""; - final int vioCount = this.violationView.getNumberOfFilteredViolations(element); - final int loc = this.violationView.getLOC(element); + int vioCount = violationView.getNumberOfFilteredViolations(element); + int loc = violationView.getLOC(element); if (loc == 0) { result = "N/A"; } else { - final double vioPerLoc = (double)(vioCount * 1000) / loc; + double vioPerLoc = (double)(vioCount * 1000) / loc; if (vioPerLoc < 0.1) { - result = "< 0.1 / 1000"; + result = "< 0.1"; } else { - final DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(Locale.US); + DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(Locale.US); format.applyPattern("##0.0"); - result = format.format(vioPerLoc) + " / 1000"; + result = format.format(vioPerLoc); } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewMenuManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewMenuManager.java index 37aa343a2b9..7c04abc0ef0 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewMenuManager.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ViolationOverviewMenuManager.java @@ -130,7 +130,7 @@ public void createDropDownMenu(IMenuManager manager) { * Creates the Context Menu */ public void createContextMenu() { - final MenuManager manager = new MenuManager(); + MenuManager manager = new MenuManager(); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { @@ -160,10 +160,10 @@ public void menuAboutToShow(IMenuManager manager) { } }); - final Tree tree = this.overview.getViewer().getTree(); + Tree tree = overview.getViewer().getTree(); tree.setMenu(manager.createContextMenu(tree)); - this.overview.getSite().registerContextMenu(manager, this.overview.getViewer()); + overview.getSite().registerContextMenu(manager, overview.getViewer()); } /** diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/AbstractPMDAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/AbstractPMDAction.java index 8d9893ce595..b1bc1912e50 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/AbstractPMDAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/AbstractPMDAction.java @@ -2,6 +2,7 @@ import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; +import net.sourceforge.pmd.eclipse.ui.nls.StringTable; import org.eclipse.jface.action.Action; @@ -11,6 +12,15 @@ */ public abstract class AbstractPMDAction extends Action { + private static StringTable stringTable; + + static { + PMDPlugin plugin = PMDPlugin.getDefault(); + if (plugin != null) { + stringTable = plugin.getStringTable(); + } + } + protected AbstractPMDAction() { setupWidget(); } @@ -19,7 +29,7 @@ protected AbstractPMDAction() { protected abstract String tooltipMsgId(); public static String getString(String messageId) { - return PMDPlugin.getDefault().getStringTable().getString(messageId); + return stringTable == null ? messageId : stringTable.getString(messageId); } protected void setupWidget() { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CalculateStatisticsAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CalculateStatisticsAction.java index fd952c97565..a8083b71ff8 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CalculateStatisticsAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CalculateStatisticsAction.java @@ -46,7 +46,7 @@ public void run() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { final TreeItem[] items = getViewer().getTree().getItems(); final int unitCount = calculateWorkUnits(items); - monitor.beginTask(getString(StringKeys.MSGKEY_MONITOR_CALC_STATS_TASK), unitCount); + monitor.beginTask(getString(StringKeys.MONITOR_CALC_STATS_TASK), unitCount); for (TreeItem item : items) { if (monitor.isCanceled()) { break; @@ -54,7 +54,7 @@ public void run(IProgressMonitor monitor) throws InvocationTargetException, Inte if (item.getData() instanceof PackageRecord) { final PackageRecord record = (PackageRecord) item.getData(); final AbstractPMDRecord[] children = record.getChildren(); - monitor.subTask(getString(StringKeys.MSGKEY_MONITOR_CALC_STATS_OF_PACKAGE) + ": " + record.getName()); + monitor.subTask(getString(StringKeys.MONITOR_CALC_STATS_OF_PACKAGE) + ": " + record.getName()); for (AbstractPMDRecord kid : children) { if (kid instanceof FileRecord) { calculateFileRecord((FileRecord)kid); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CollapseAllAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CollapseAllAction.java index 9d48c9a5d2e..6865c7bd443 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CollapseAllAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/CollapseAllAction.java @@ -64,7 +64,7 @@ public CollapseAllAction(ViolationOverview view) { protected String imageId() { return PMDUiConstants.ICON_BUTTON_COLLAPSE; } - protected String tooltipMsgId() { return StringKeys.MSGKEY_VIEW_TOOLTIP_COLLAPSE_ALL; } + protected String tooltipMsgId() { return StringKeys.VIEW_TOOLTIP_COLLAPSE_ALL; } /** * Performs the Action diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/PackageSwitchAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/PackageSwitchAction.java index 64ca815cf42..bcb35c9a38d 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/PackageSwitchAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/PackageSwitchAction.java @@ -25,7 +25,7 @@ public PackageSwitchAction(ViolationOverview view) { protected String imageId() { return PMDUiConstants.ICON_BUTTON_FILES; } - protected String tooltipMsgId() { return StringKeys.MSGKEY_VIEW_TOOLTIP_PACKAGES_FILES; } + protected String tooltipMsgId() { return StringKeys.VIEW_TOOLTIP_PACKAGES_FILES; } /** * @return the Style, in which the Button is displayed diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ProjectFilterAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ProjectFilterAction.java index f778f5db769..85261e6dacb 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ProjectFilterAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ProjectFilterAction.java @@ -37,7 +37,7 @@ public ProjectFilterAction(AbstractPMDRecord projectRecord, ViolationOverview vi } // we set Image and Text for the Action - setText(getString(StringKeys.MSGKEY_VIEW_FILTER_PROJECT_PREFIX) + " " + projectRecord.getName()); + setText(getString(StringKeys.VIEW_FILTER_PROJECT_PREFIX) + " " + projectRecord.getName()); } protected String imageId() { return PMDUiConstants.ICON_PROJECT; } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewAction.java index 0fc67b75a1f..b754f6ee413 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewAction.java @@ -79,7 +79,7 @@ public void run() { dialog.run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { setMonitor(monitor); - monitor.beginTask(getString(StringKeys.MSGKEY_MONITOR_REVIEW), 5); + monitor.beginTask(getString(StringKeys.MONITOR_REVIEW), 5); insertReview(markers[0], reviewPmdStyle); monitor.done(); } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewResourceAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewResourceAction.java index c8aa58cd4bb..61c63b04757 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewResourceAction.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/actions/ReviewResourceAction.java @@ -48,7 +48,7 @@ public void run() { dialog.run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { setMonitor(monitor); - monitor.beginTask(getString(StringKeys.MSGKEY_MONITOR_REVIEW), 5); + monitor.beginTask(getString(StringKeys.MONITOR_REVIEW), 5); ReviewCodeCmd cmd = new ReviewCodeCmd(); cmd.addResource(resource); cmd.setStepCount(1); diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTContentProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTContentProvider.java new file mode 100644 index 00000000000..441ba846b51 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTContentProvider.java @@ -0,0 +1,60 @@ +package net.sourceforge.pmd.eclipse.ui.views.ast; + +import net.sourceforge.pmd.lang.ast.AbstractNode; +import net.sourceforge.pmd.lang.ast.Node; + +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.Viewer; + +/** + * + * @author Brian Remedios + */ +public class ASTContentProvider implements ITreeContentProvider { + + public ASTContentProvider() { + } + + public void dispose() { } + + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + + } + + public Object[] getElements(Object inputElement) { + + AbstractNode parent = (AbstractNode)inputElement; + + Node[] kids = new Node[ parent.jjtGetNumChildren()]; + for (int i=0; i<kids.length; i++) { + kids[i] = parent.jjtGetChild(i); + } + + return kids; + } + + public Object[] getChildren(Object parentElement) { + + AbstractNode parent = (AbstractNode)parentElement; + + Node[] kids = new Node[ parent.jjtGetNumChildren()]; + for (int i=0; i<kids.length; i++) { + kids[i] = parent.jjtGetChild(i); + } + + return kids; + } + + public Object getParent(Object element) { + + AbstractNode parent = (AbstractNode)element; + return parent.jjtGetParent(); + } + + public boolean hasChildren(Object element) { + + AbstractNode parent = (AbstractNode)element; + return parent.jjtGetNumChildren() > 0; + } + +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTLabelProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTLabelProvider.java new file mode 100644 index 00000000000..991a3f788ce --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTLabelProvider.java @@ -0,0 +1,33 @@ +package net.sourceforge.pmd.eclipse.ui.views.ast; + +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.swt.graphics.Image; + +public class ASTLabelProvider implements ILabelProvider { + + public void addListener(ILabelProviderListener listener) { } + + public void dispose() { } + + public boolean isLabelProperty(Object element, String property) { + return false; + } + + public void removeListener(ILabelProviderListener listener) { } + + public Image getImage(Object element) { + return null; + } + + public String getText(Object element) { + return null; +// AbstractNode node = (AbstractNode)element; +// String extra = node.getImage(); +// +// return extra == null ? +// node.toString() : +// node.toString() + ": " + extra; + } + +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTView.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTView.java new file mode 100755 index 00000000000..265b6614b6e --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTView.java @@ -0,0 +1,136 @@ +package net.sourceforge.pmd.eclipse.ui.views.ast; + +import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; +import net.sourceforge.pmd.eclipse.ui.model.FileRecord; +import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +import net.sourceforge.pmd.eclipse.ui.views.AbstractPMDPagebookView; +import net.sourceforge.pmd.eclipse.ui.views.AbstractStructureInspectorPage; + +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.eclipse.core.runtime.IPath; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.part.IPage; + +/** + * + * @author Brian Remedios + */ +public class ASTView extends AbstractPMDPagebookView implements IResourceChangeListener { + + public ASTView() { + } + + @Override + public void createPartControl(Composite parent) { + super.createPartControl(parent); + } + + protected String pageMessageId() { return StringKeys.VIEW_AST_DEFAULT_TEXT; } + + @Override + protected String mementoFileId() { return PMDUiConstants.MEMENTO_AST_FILE; } + + @Override + protected PageRec doCreatePage(IWorkbenchPart part) { + + FileRecord resourceRecord = getFileRecordFromWorkbenchPart(part); + if (resourceRecord != null) { + resourceRecord.getResource().getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); + + // creates a new DataflowViewPage, when a Resource exists + ASTViewPage page = new ASTViewPage(part, resourceRecord); + initPage(page); + page.createControl(getPageBook()); + + return new PageRec(part, page); + } + return null; + } + + @Override + protected void doDestroyPage(IWorkbenchPart part, PageRec pageRecord) { + + FileRecord resourceRecord = getFileRecordFromWorkbenchPart(part); + if (resourceRecord != null) { + resourceRecord.getResource().getWorkspace().removeResourceChangeListener(this); + } + + ASTViewPage page = (ASTViewPage) pageRecord.page; + + if (page != null) { + page.dispose(); + } + + pageRecord.dispose(); + } + + /* @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IPartListener) */ + @Override + public void partActivated(IWorkbenchPart part) { + IWorkbenchPart activePart = getSitePage().getActivePart(); + if (activePart == null) getSitePage().activate(this); + super.partActivated(part); + } + + /** + * @return the currently displayed Page + */ + private ASTViewPage getCurrentASTViewPage() { + IPage page = super.getCurrentPage(); + if (!(page instanceof ASTViewPage)) + return null; + + return (ASTViewPage) page; + } + + private IPath getResourcePath() { + AbstractStructureInspectorPage page = getCurrentASTViewPage(); + FileRecord record = page.getFileRecord(); + IResource resource = record.getResource(); + return resource.getFullPath(); + } + + public void resourceChanged(IResourceChangeEvent event) { + try { + event.getDelta().accept(new IResourceDeltaVisitor() { + public boolean visit(final IResourceDelta delta) throws CoreException { + // find the resource for the path of the current page + IPath path = getResourcePath(); + if (delta.getFullPath().equals(path)) { + Display.getDefault().asyncExec(new Runnable() { + public void run() { + refresh(delta.getResource()); + } + }); + + return false; + } + return true; + } + + }); + } catch (CoreException e) { + PMDPlugin.getDefault().logError( + StringKeys.MSGKEY_ERROR_CORE_EXCEPTION, e); + } + + } + + /** + * Refresh, reloads the View with a given new resource. + * @param newResource new resource for the current active page. + */ + private void refresh(IResource newResource) { + ASTViewPage page = getCurrentASTViewPage(); + if (page != null) + page.refresh(newResource); + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTViewPage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTViewPage.java new file mode 100755 index 00000000000..7e5ecdf6a5e --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/ASTViewPage.java @@ -0,0 +1,358 @@ +package net.sourceforge.pmd.eclipse.ui.views.ast; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; +import net.sourceforge.pmd.eclipse.ui.model.FileRecord; +import net.sourceforge.pmd.eclipse.ui.views.AbstractStructureInspectorPage; +import net.sourceforge.pmd.lang.ast.AbstractNode; +import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; +import net.sourceforge.pmd.lang.java.ast.ParseException; +import net.sourceforge.pmd.lang.rule.xpath.XPathRuleQuery; + +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.graphics.TextLayout; +import org.eclipse.swt.graphics.TextStyle; +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.Event; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.ui.IWorkbenchPart; + +/** + * A combined abstract syntax tree viewer for a whole class or selected methods + * and an XPath editor/evaluator on the right that works with it. + * + * @author Brian Remedios + * + */ +public class ASTViewPage extends AbstractStructureInspectorPage { + + private Composite astFrame; + + protected TreeViewer astViewer; + + private TextLayout textLayout; + private Font renderFont; + private TextStyle labelStyle; + private TextStyle imageStyle; + + private StyledText xpathField; + private StyledText outputField; + + private Node classNode; + + private static Set<String> keywords = new HashSet<String>(); + + /** + * Constructor + * @param part + * @param record the FileRecord + */ + public ASTViewPage(IWorkbenchPart part, FileRecord record) { + super(part, record); + } + + public void createControl(Composite parent) { + + astFrame = new Composite(parent, SWT.NONE); + + GridLayout mainLayout = new GridLayout(3, false); + astFrame.setLayout(mainLayout); + + Composite titleArea = new Composite(astFrame, SWT.NONE); + GridData tableData = new GridData(GridData.FILL_HORIZONTAL); + tableData.horizontalSpan = 2; + titleArea.setLayoutData(tableData); + titleArea.setLayout(new GridLayout(4, false)); + + Label showLabel = new Label(titleArea, 0); + showLabel.setText("Show: "); + + final Button classBtn = new Button(titleArea, SWT.RADIO); + classBtn.setText("Class"); + classBtn.addSelectionListener( new SelectionAdapter() { + public void widgetSelected(SelectionEvent se) { + if (classBtn.getSelection()) showClass(); + } + } ); + + final Button methodBtn = new Button(titleArea, SWT.RADIO); + methodBtn.setText("Method"); + methodBtn.addSelectionListener( new SelectionAdapter() { + public void widgetSelected(SelectionEvent se) { + methodSelector.setEnabled( methodBtn.getSelection() ); + methodPicked(); + } + } ); + + buildMethodSelector(titleArea); + + astViewer = new TreeViewer(astFrame); + astViewer.setContentProvider( new ASTContentProvider() ); + astViewer.setLabelProvider( new ASTLabelProvider() ); + setupListeners(astViewer.getTree()); + + GridData data = new GridData(GridData.FILL_BOTH); + data.horizontalSpan = 2; + astViewer.getTree().setLayoutData(data); + + Composite xpathTestPanel = new Composite(astFrame, SWT.NONE); + data = new GridData(GridData.FILL_BOTH); + data.horizontalSpan = 1; + xpathTestPanel.setLayoutData(data); + + GridLayout playLayout = new GridLayout(2, false); + xpathTestPanel.setLayout(playLayout); + + xpathField = new StyledText(xpathTestPanel, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); + GridData gridData = new GridData(GridData.FILL_BOTH); + gridData.grabExcessHorizontalSpace = true; + gridData.horizontalSpan = 1; + xpathField.setLayoutData(gridData); + SyntaxManager.adapt(xpathField, "xpath", null); + + Button goButton = new Button(xpathTestPanel, SWT.PUSH); + goButton.setText("GO"); + gridData = new GridData(GridData.FILL_BOTH); + gridData.grabExcessHorizontalSpace = false; + gridData.horizontalSpan = 1; + goButton.setLayoutData(gridData); + goButton.addSelectionListener( new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + evaluateXPath(); + } + } ); + + outputField = new StyledText(xpathTestPanel, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); + gridData = new GridData(GridData.FILL_BOTH); + gridData.grabExcessHorizontalSpace = true; + gridData.horizontalSpan = 2; + outputField.setLayoutData(gridData); + SyntaxManager.adapt(outputField, "xpath", null); + + showFirstMethod(); + } + + private static void displayOn(Node node, StringBuilder sb) { + + sb.append(node); + + String imgData = node.getImage(); +// sb.append( "[" + node.getBeginColumn() +", " + node.getEndColumn() + "] " ); + + if (imgData != null ) sb.append(" ").append( imgData ); + } + + private void evaluateXPath() { + + outputField.setText(""); + + if (xpathField.getText().length() == 0) { + outputField.setText("XPath query field is empty."); + return; + } + + List<Node> results = null; + try { + results = XPathEvaluator.instance.evaluate( + getDocument().get(), + xpathField.getText(), + XPathRuleQuery.XPATH_1_0 + ); + } catch (ParseException pe) { + outputField.setText(pe.fillInStackTrace().getMessage()); + return; + } + + if (results.isEmpty()) { + outputField.setText("No matching nodes " + System.currentTimeMillis()); + return; + } + + StringBuilder sb = new StringBuilder(); + for (Node node : results) { + displayOn(node, sb); + sb.append('\n'); + } + outputField.setText( sb.toString() ); + } + + private TextLayout layoutFor(TreeItem item) { + + AbstractNode node = (AbstractNode)item.getData(); + String label = node.toString(); + + keywords.add(label); + + String extra = node.getImage(); + + textLayout.setText(label + (extra == null ? "" : " " + extra)); + + int labelLength = label.length(); + + textLayout.setStyle(labelStyle, 0, labelLength); + if (extra != null) { + textLayout.setStyle(imageStyle, labelLength, labelLength + extra.length() + 1); + } + + return textLayout; + } + + private void setupListeners(Tree tree) { + + setupResources(tree.getDisplay()); + + tree.addListener(SWT.PaintItem, new Listener() { + public void handleEvent(Event event) { + TextLayout layout = layoutFor((TreeItem)event.item); + layout.draw(event.gc, event.x, event.y + 5); + } + }); + + tree.addListener(SWT.MeasureItem, new Listener() { + public void handleEvent(Event e) { + Rectangle textLayoutBounds = layoutFor((TreeItem)e.item).getBounds(); + e.width = textLayoutBounds.width + 2; + e.height = textLayoutBounds.height + 2; + } + }); + } + + private void setupResources(Display display) { + textLayout = new TextLayout(display); + renderFont = new Font(display, "Tahoma", 10, SWT.NORMAL); + labelStyle = new TextStyle(renderFont, display.getSystemColor(SWT.COLOR_BLACK), null); + imageStyle = new TextStyle(renderFont, display.getSystemColor(SWT.COLOR_BLUE), null); + } + + public void dispose() { + renderFont.dispose(); + } + + public Control getControl() { + return astFrame; + } + + protected void showClass() { + + if (classNode == null) { + String source = getDocument().get(); + classNode = XPathEvaluator.instance.getCompilationUnit(source); + } + + astViewer.setInput(classNode); + astViewer.expandAll(); + } + + protected void showMethod(ASTMethodDeclaration pmdMethod) { + + if (pmdMethod == null) return; + + astViewer.setInput(pmdMethod); + astViewer.expandAll(); + } + + /** + * Shows the DataflowGraph (and Dataflow-Anomalies) for a Method. + * + * @param pmdMethod Method to show in the graph + */ +// protected void showMethod(final ASTMethodDeclaration pmdMethod) { +// if (pmdMethod != null) { +// +// final String resourceString = getDocument().get(); +// give the Data to the GraphViewer +// astViewer.setVisible(true); +// astViewer.setData(pmdMethod, resourceString); +// astViewer.addMouseListener(new MouseAdapter() { +// +// @Override +// public void mouseDown(MouseEvent e) { +// if (textEditor != null) { +// final int row = (int)((double)e.y / DataflowGraphViewer.ROW_HEIGHT); +// astViewer.getGraph().demark(); +// astViewer.getGraph().markNode(row); +// final int startLine = pmdMethod.getDataFlowNode().getFlow().get(row).getLine()-1; +// int offset = 0; +// int length = 0; +// try { +// offset = getDocument().getLineOffset(startLine); +// length = getDocument().getLineLength(startLine); +// } catch (BadLocationException ble) { +// logError(StringKeys.MSGKEY_ERROR_RUNTIME_EXCEPTION + "Exception when selecting a line in the editor" , ble); +// } +// textEditor.selectAndReveal(offset, length); +// astViewer.getTree().deselectAll(); +// } +// } +// }); +// showTableArea(isTableShown); +// } +// } + + /** + * Refreshes the page with a new resource. + * @param newResource new resource for the page + */ + public void refresh(IResource newResource) { + if (newResource.getType() == IResource.FILE) { + // set a new filerecord + resourceRecord = new FileRecord(newResource); + } + + classNode = null; + + // if (isTableShown) { + // refreshDFATable(newResource); + // } else { + // this.isTableRefreshed = false; + // } + + // refresh the methods and select the old selected method + final int index = methodSelector.getSelectionIndex(); + refreshPMDMethods(); + showMethod(index); + methodSelector.select(index); + + } + + /** + * Executes a command to refresh the DFA table. + * After execution {@link #refresh(IResource)} will be called. + * @param newResource the new resource + */ + // public void refreshDFATable(IResource newResource) { + // this.isTableRefreshed = true; + // try { + // final ReviewResourceForRuleCommand cmd = new ReviewResourceForRuleCommand(); + // final DataflowAnomalyAnalysisRule rule = new DataflowAnomalyAnalysisRule(); + // rule.setUsesDFA(); + // cmd.setUserInitiated(false); + // cmd.setRule(rule); + // cmd.setResource(newResource); + // cmd.addPropertyListener(this); + // cmd.performExecute(); + // } catch (CommandException e) { + // logErrorByKey(StringKeys.MSGKEY_ERROR_PMD_EXCEPTION, e); + // } + // } + +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/XPathEvaluator.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/XPathEvaluator.java new file mode 100644 index 00000000000..592a7cb73f8 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/ast/XPathEvaluator.java @@ -0,0 +1,80 @@ +package net.sourceforge.pmd.eclipse.ui.views.ast; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import net.sourceforge.pmd.RuleContext; +import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.RuleSets; +import net.sourceforge.pmd.lang.Language; +import net.sourceforge.pmd.lang.LanguageVersion; +import net.sourceforge.pmd.lang.LanguageVersionHandler; +import net.sourceforge.pmd.lang.Parser; +import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.java.ast.ParseException; +import net.sourceforge.pmd.lang.rule.XPathRule; + +/** + * + * @author Brian Remedios + */ +public class XPathEvaluator { + + public static final XPathEvaluator instance = new XPathEvaluator(); + + private XPathEvaluator() {} + + public Node getCompilationUnit(String source) { + + LanguageVersionHandler languageVersionHandler = getLanguageVersionHandler(); + Parser parser = languageVersionHandler.getParser(languageVersionHandler.getDefaultParserOptions()); + Node node = parser.parse(null, new StringReader(source)); + languageVersionHandler.getSymbolFacade().start(node); + languageVersionHandler.getTypeResolutionFacade(null).start(node); + return node; + } + + private LanguageVersionHandler getLanguageVersionHandler() { + LanguageVersion languageVersion = getLanguageVersion(); + return languageVersion.getLanguageVersionHandler(); + } + + private LanguageVersion getLanguageVersion() { + return Language.JAVA.getDefaultVersion(); + } + + public List<Node> evaluate(String source, String xpathQuery, String xpathVersion) throws ParseException { + + Node c = getCompilationUnit(source); + + final List<Node> results = new ArrayList<Node>(); + + XPathRule xpathRule = new XPathRule() { + public void addViolation(Object data, Node node, String arg) { + results.add(node); + } + }; + + xpathRule.setMessage(""); + xpathRule.setLanguage(getLanguageVersion().getLanguage()); + xpathRule.setProperty(XPathRule.XPATH_DESCRIPTOR, xpathQuery); + xpathRule.setProperty(XPathRule.VERSION_DESCRIPTOR, xpathVersion); + + RuleSet ruleSet = new RuleSet(); + ruleSet.addRule(xpathRule); + + RuleSets ruleSets = new RuleSets(ruleSet); + + RuleContext ruleContext = new RuleContext(); + ruleContext.setLanguageVersion(getLanguageVersion()); + + List<Node> nodes = new ArrayList<Node>(1); + nodes.add(c); + + ruleSets.apply(nodes, ruleContext, xpathRule.getLanguage()); + + return results; + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowView.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowView.java index 5bc9f53557e..1a9f5444f03 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowView.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowView.java @@ -1,13 +1,11 @@ package net.sourceforge.pmd.eclipse.ui.views.dataflow; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; -import net.sourceforge.pmd.eclipse.runtime.cmd.AbstractDefaultCommand; import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; import net.sourceforge.pmd.eclipse.ui.model.FileRecord; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; import net.sourceforge.pmd.eclipse.ui.views.AbstractPMDPagebookView; -import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; @@ -17,9 +15,6 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.part.IPage; @@ -44,6 +39,7 @@ public void createPartControl(Composite parent) { /* @see org.eclipse.ui.part.PageBookView#doCreatePage(org.eclipse.ui.IWorkbenchPart) */ @Override protected PageRec doCreatePage(IWorkbenchPart part) { + FileRecord resourceRecord = getFileRecordFromWorkbenchPart(part); if (resourceRecord != null) { resourceRecord.getResource().getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); @@ -129,31 +125,6 @@ private DataflowViewPage getCurrentDataflowViewPage() { return (DataflowViewPage) page; } - /** - * Gets the fileRecord from the currently active editor. - * @param part IWorkbenchPart - * @return a new FileRecord - */ - private FileRecord getFileRecordFromWorkbenchPart(IWorkbenchPart part) { - if (part instanceof IEditorPart) { - // If there is a file opened in the editor, we create a record for it - IEditorInput input = ((IEditorPart) part).getEditorInput(); - if (input != null && input instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) input).getFile(); - return AbstractDefaultCommand.isJavaFile(file) ? - new FileRecord(file) : - null; - } - } else { - // We also want to get the editors when it's not active - // so we pretend, that the editor has been activated - IEditorPart editorPart = getSite().getPage().getActiveEditor(); - if (editorPart != null) { - return getFileRecordFromWorkbenchPart(editorPart); - } - } - return null; - } /** * Refresh, reloads the View with a given new resource. diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowViewPage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowViewPage.java index 4a1e6c9f139..37e30c34831 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowViewPage.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/dataflow/DataflowViewPage.java @@ -1,49 +1,33 @@ package net.sourceforge.pmd.eclipse.ui.views.dataflow; -import java.io.StringReader; -import java.util.ArrayList; import java.util.Iterator; -import java.util.List; import name.herlin.command.CommandException; -import net.sourceforge.pmd.PMDException; -import net.sourceforge.pmd.RuleContext; -import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleViolation; -import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; -import net.sourceforge.pmd.eclipse.runtime.cmd.PMDEngine; import net.sourceforge.pmd.eclipse.runtime.cmd.ReviewResourceForRuleCommand; import net.sourceforge.pmd.eclipse.ui.model.FileRecord; import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +import net.sourceforge.pmd.eclipse.ui.views.AbstractStructureInspectorPage; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.rule.controversial.DataflowAnomalyAnalysisRule; import net.sourceforge.pmd.util.StringUtil; -import net.sourceforge.pmd.util.designer.DFAGraphRule; import org.eclipse.core.resources.IResource; import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; 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.events.SelectionListener; -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.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; -import org.eclipse.ui.IPropertyListener; import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.part.Page; -import org.eclipse.ui.texteditor.ITextEditor; /** * A page for the dataflow - view. @@ -51,18 +35,14 @@ * @author Sven Jacob * */ -public class DataflowViewPage extends Page implements IPropertyListener, ISelectionChangedListener, SelectionListener { - private Composite dfaFrame; - private Combo methodSelector; - private Button switchButton; +public class DataflowViewPage extends AbstractStructureInspectorPage { + + private Composite dfaFrame; + private Button switchButton; - protected DataflowGraphViewer graphViewer; + protected DataflowGraphViewer graphViewer; protected DataflowAnomalyTableViewer tableViewer; - private List<ASTMethodDeclaration> pmdMethodList; - private FileRecord resourceRecord; - private ITextEditor textEditor; // NOPMD by Sven on 09.11.06 22:18 - private boolean isTableShown; private boolean isTableRefreshed; @@ -72,11 +52,8 @@ public class DataflowViewPage extends Page implements IPropertyListener, ISelect * @param record the FileRecord */ public DataflowViewPage(IWorkbenchPart part, FileRecord record) { - super(); - this.resourceRecord = record; - if (part instanceof ITextEditor) { - textEditor = (ITextEditor) part; - } + super(part, record); + } /* @see org.eclipse.ui.part.IPage#createControl(org.eclipse.swt.widgets.Composite) */ @@ -88,7 +65,7 @@ public void createControl(Composite parent) { // upper title area Composite titleArea = new Composite(dfaFrame, SWT.NONE); - final GridData tableData = new GridData(GridData.FILL_HORIZONTAL); + GridData tableData = new GridData(GridData.FILL_HORIZONTAL); tableData.horizontalSpan = 2; titleArea.setLayoutData(tableData); titleArea.setLayout(new GridLayout(4, false)); @@ -96,21 +73,33 @@ public void createControl(Composite parent) { Label methodLabel = new Label(titleArea, 0); methodLabel.setText("Method: "); - // the drop down box for showing all methods of the given resource - methodSelector = new Combo(titleArea, SWT.LEFT | SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER); - refreshPMDMethods(); - methodSelector.setText(getString(StringKeys.MSGKEY_VIEW_DATAFLOW_CHOOSE_METHOD)); - methodSelector.setLayoutData(new GridData(300, SWT.DEFAULT)); - methodSelector.addSelectionListener(this); + buildMethodSelector(titleArea); // a label for the spacing - final Label label = new Label(titleArea, SWT.NONE); + Label label = new Label(titleArea, SWT.NONE); label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // the Button for showing or hiding the Anomaly-List switchButton = new Button(titleArea, SWT.RIGHT); switchButton.setLayoutData(new GridData(130, 25)); - switchButton.addSelectionListener(this); + switchButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent se) { + isTableShown = !isTableShown; + showTableArea(isTableShown); + + if (!isTableShown) { + if (graphViewer == null || graphViewer.getGraph() == null) { + return; + } + + final DataflowGraph graph = graphViewer.getGraph(); + if (graph.isMarked()) { + graph.demark(); + } + } + }} + ); + switchButton.setText(getString(StringKeys.MSGKEY_VIEW_DATAFLOW_SWITCHBUTTON_SHOW)); // ////////////////////////////////////////////////// @@ -124,9 +113,9 @@ public void createControl(Composite parent) { tableViewer.addSelectionChangedListener(this); tableViewer.setContentProvider(new DataflowAnomalyTableContentProvider()); tableViewer.setLabelProvider(new DataflowAnomalyTableLabelProvider()); - this.isTableRefreshed = false; + isTableRefreshed = false; - final GridLayout mainLayout = new GridLayout(2, true); + GridLayout mainLayout = new GridLayout(2, true); mainLayout.horizontalSpacing = mainLayout.verticalSpacing = 7; mainLayout.marginWidth = 3; mainLayout.marginHeight = 3; @@ -137,29 +126,6 @@ public void createControl(Composite parent) { showFirstMethod(); } - - /* @see org.eclipse.ui.part.Page#dispose() */ - @Override - public void dispose() { - } - - /** - * Refreshes the list of PMD methods for the combobox. - * @see #getPMDMethods(IResource) - */ - private void refreshPMDMethods() { - pmdMethodList = getPMDMethods(); - methodSelector.removeAll(); - for (int i = 0; i < pmdMethodList.size(); i++) { - final ASTMethodDeclaration pmdMethod = pmdMethodList.get(i); - methodSelector.add(getMethodLabel(pmdMethod), i); - } - } - - public void showFirstMethod() { - methodSelector.select(0); - showMethod(0); - } /** * Gets the label of a method for an element of the combobox. * @param pmdMethod the method to create a label for @@ -175,39 +141,15 @@ public Control getControl() { return dfaFrame; } - /* @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ - @Override - public void setFocus() { - methodSelector.setFocus(); - } - - /** - * @return the underlying FileRecord - */ - public FileRecord getFileRecord() { - return resourceRecord; - } - - /** - * Confort method to show a method. - * @param index index position of the combobox - */ - private void showMethod(final int index) { - if (index >= 0 && index < pmdMethodList.size() ) { - final ASTMethodDeclaration method = pmdMethodList.get(index); - showMethod(method); - } - } - /** * Shows the DataflowGraph (and Dataflow-Anomalies) for a Method. * * @param pmdMethod Method to show in the graph */ - private void showMethod(final ASTMethodDeclaration pmdMethod) { + protected void showMethod(final ASTMethodDeclaration pmdMethod) { if (pmdMethod != null) { - final String resourceString = getDocument().get(); + String resourceString = getDocument().get(); // give the Data to the GraphViewer graphViewer.setVisible(true); graphViewer.setData(pmdMethod, resourceString); @@ -216,10 +158,10 @@ private void showMethod(final ASTMethodDeclaration pmdMethod) { @Override public void mouseDown(MouseEvent e) { if (textEditor != null) { - final int row = (int)((double)e.y / DataflowGraphViewer.ROW_HEIGHT); + int row = (int)((double)e.y / DataflowGraphViewer.ROW_HEIGHT); graphViewer.getGraph().demark(); graphViewer.getGraph().markNode(row); - final int startLine = pmdMethod.getDataFlowNode().getFlow().get(row).getLine()-1; + int startLine = pmdMethod.getDataFlowNode().getFlow().get(row).getLine()-1; int offset = 0; int length = 0; try { @@ -237,65 +179,6 @@ public void mouseDown(MouseEvent e) { } } - /** - * Shows the method that belongs to a violation (to a line). - * @param violation RuleViolation - */ - private void showMethodToViolation(RuleViolation violation) { - final int beginLine = violation.getBeginLine(); - - for (int i = 0; i < pmdMethodList.size(); i++) { - final ASTMethodDeclaration pmdMethod = pmdMethodList.get(i); - if (beginLine >= pmdMethod.getBeginLine() && beginLine <= pmdMethod.getEndLine()) { - showMethod(pmdMethod); - // select the method in the combobox - methodSelector.select(i); - return; - } - } - } - - /** - * Gets a List of all PMD-Methods. - * - * @return an List of ASTMethodDeclarations - */ - private List<ASTMethodDeclaration> getPMDMethods() { - final List<ASTMethodDeclaration> methodList = new ArrayList<ASTMethodDeclaration>(); - - // we need PMD to run over the given Resource - // with the DFAGraphRule to get the Methods; - // PMD needs this Resource as a String - try { - final DFAGraphRule dfaGraphRule = new DFAGraphRule(); - final RuleSet rs = new RuleSet(); - rs.addRule(dfaGraphRule); - final RuleContext ctx = new RuleContext(); - ctx.setSourceCodeFilename("[scratchpad]"); - - final StringReader reader = new StringReader(getDocument().get()); - - // run PMD using the DFAGraphRule - // and the Text of the Resource - new PMDEngine().processFile(reader, rs, ctx); - - // the Rule then can give us the Methods - methodList.addAll(dfaGraphRule.getMethods()); - } catch (PMDException pmde) { - logError(StringKeys.MSGKEY_ERROR_PMD_EXCEPTION + this.toString(), pmde); - } - - return methodList; - } - - /** - * Gets the Document of the page. - * @return instance of IDocument of the page - */ - public IDocument getDocument() { - return textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - } - /** * Shows or hides the DataflowAnomalyTable, set the right text for the button. * @@ -322,35 +205,24 @@ private void showTableArea(boolean isShown) { // lay out to update the View dfaFrame.layout(true, true); } - - private RuleViolation selectedViolationFrom(SelectionChangedEvent event) { - - if (event.getSelection() instanceof IStructuredSelection) { - final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); - return element instanceof RuleViolation ? - (RuleViolation) element : null; - } - - return null; // should never happen - } /* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { - final RuleViolation violation = selectedViolationFrom(event); + RuleViolation violation = selectedViolationFrom(event); if (violation == null) return; - final String varName = violation.getVariableName(); + String varName = violation.getVariableName(); if (StringUtil.isEmpty(varName)) return; - final int beginLine = violation.getBeginLine(); - final int endLine = violation.getEndLine(); + int beginLine = violation.getBeginLine(); + int endLine = violation.getEndLine(); if (beginLine != 0 && endLine != 0) { try { - final int offset = getDocument().getLineOffset(violation.getBeginLine() - 1); - final int length = getDocument().getLineOffset(violation.getEndLine()) - offset; - this.textEditor.selectAndReveal(offset, length); + int offset = getDocument().getLineOffset(violation.getBeginLine() - 1); + int length = getDocument().getLineOffset(violation.getEndLine()) - offset; + textEditor.selectAndReveal(offset, length); } catch (BadLocationException ble) { logError(StringKeys.MSGKEY_ERROR_RUNTIME_EXCEPTION + "Exception when selecting a line in the editor", ble); } @@ -360,45 +232,13 @@ public void selectionChanged(SelectionChangedEvent event) { // then we calculate and color _a possible_ Path // for this Error in the Dataflow - final DataflowGraph graph = graphViewer.getGraph(); + DataflowGraph graph = graphViewer.getGraph(); if (!graphViewer.isDisposed() && graph != null) { graph.markPath(beginLine, endLine, varName); } } } - /* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) */ - public void widgetDefaultSelected(SelectionEvent e) { - if (methodSelector.equals(e.widget)) { - showMethod(methodSelector.getSelectionIndex()); - } - } - - /* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ - public void widgetSelected(SelectionEvent e) { - if (switchButton.equals(e.widget)) { - // the event can be caught from the switchbutton ... - isTableShown = !isTableShown; - showTableArea(isTableShown); - - if (!isTableShown) { - if (graphViewer == null || graphViewer.getGraph() == null) { - return; - } - - final DataflowGraph graph = graphViewer.getGraph(); - if (graph.isMarked()) { - graph.demark(); - } - } - } else if (methodSelector.equals(e.widget)) { - // ... or from the combobox - final int index = methodSelector.getSelectionIndex(); - methodSelector.setSelection(new Point(0,0)); - showMethod(index); - } - } - /** * Refreshes the page with a new resource. * @param newResource new resource for the page @@ -412,11 +252,11 @@ public void refresh(IResource newResource) { if (isTableShown) { refreshDFATable(newResource); } else { - this.isTableRefreshed = false; + isTableRefreshed = false; } // refresh the methods and select the old selected method - final int index = methodSelector.getSelectionIndex(); + int index = methodSelector.getSelectionIndex(); refreshPMDMethods(); showMethod(index); methodSelector.select(index); @@ -428,10 +268,10 @@ public void refresh(IResource newResource) { * @param newResource the new resource */ public void refreshDFATable(IResource newResource) { - this.isTableRefreshed = true; + isTableRefreshed = true; try { - final ReviewResourceForRuleCommand cmd = new ReviewResourceForRuleCommand(); - final DataflowAnomalyAnalysisRule rule = new DataflowAnomalyAnalysisRule(); + ReviewResourceForRuleCommand cmd = new ReviewResourceForRuleCommand(); + DataflowAnomalyAnalysisRule rule = new DataflowAnomalyAnalysisRule(); rule.setUsesDFA(); cmd.setUserInitiated(false); cmd.setRule(rule); @@ -453,18 +293,4 @@ public void propertyChanged(Object source, int propId) { } } - /** - * Helper method to return an NLS string from its key. - */ - private static String getString(String key) { - return PMDPlugin.getDefault().getStringTable().getString(key); - } - - public static void logError(String message, Throwable error) { - PMDPlugin.getDefault().logError(message, error); - } - - public static void logErrorByKey(String messageId, Throwable error) { - PMDPlugin.getDefault().logError(getString(messageId), error); - } } diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/rules/RuleEditorView.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/rules/RuleEditorView.java new file mode 100755 index 00000000000..9f50aaddd78 --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/views/rules/RuleEditorView.java @@ -0,0 +1,612 @@ +package net.sourceforge.pmd.eclipse.ui.views.rules; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import net.sourceforge.pmd.PropertyDescriptor; +import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; +import net.sourceforge.pmd.eclipse.runtime.preferences.impl.PreferenceUIStore; +import net.sourceforge.pmd.eclipse.ui.Shape; +import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +import net.sourceforge.pmd.eclipse.ui.preferences.br.FormatManager; +import net.sourceforge.pmd.eclipse.ui.preferences.br.ImageColumnDescriptor; +import net.sourceforge.pmd.eclipse.ui.preferences.br.IndexedString; +import net.sourceforge.pmd.eclipse.ui.preferences.br.ModifyListener; +import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleColumnDescriptor; +import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleSelection; +import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleSelectionListener; +import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleTableManager; +import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleUtil; +import net.sourceforge.pmd.eclipse.ui.preferences.br.TextColumnDescriptor; +import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; +import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueFormatter; +import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.Configuration; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.DescriptionPanelManager; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.EditorUsageMode; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ExamplePanelManager; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ExclusionPanelManager; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.PerRulePropertyPanelManager; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.QuickFixPanelManager; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.RulePanelManager; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.RulePropertyManager; +import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.XPathPanelManager; +import net.sourceforge.pmd.eclipse.util.FontBuilder; +import net.sourceforge.pmd.eclipse.util.Util; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.FormAttachment; +import org.eclipse.swt.layout.FormData; +import org.eclipse.swt.layout.FormLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.layout.RowLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Sash; +import org.eclipse.swt.widgets.TabFolder; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.ui.part.ViewPart; + +public class RuleEditorView extends ViewPart implements RuleSelectionListener, ModifyListener, ValueChangeListener { + + private TabFolder tabFolder; + private RulePropertyManager[] rulePropertyManagers; + private RuleTableManager tableManager; + + public static final Shape PriorityShape = Shape.diamond; + public static final Shape RegexFilterShape = Shape.square; + public static final Shape XPathFilterShape = Shape.circle; + + public static final FontBuilder blueBold11 = new FontBuilder("Tahoma", 11, SWT.BOLD, SWT.COLOR_BLUE); + public static final FontBuilder redBold11 = new FontBuilder("Tahoma", 11, SWT.BOLD, SWT.COLOR_RED); + public static final FontBuilder ChangedPropertyFont = blueBold11; + + private IPreferences preferences = PMDPlugin.getDefault().loadPreferences(); + + protected static PMDPlugin plugin = PMDPlugin.getDefault(); + + // columns shown in the rule treetable in the desired order + private static final RuleColumnDescriptor[] availableColumns = new RuleColumnDescriptor[] { + TextColumnDescriptor.name, + //TextColumnDescriptor.priorityName, + // IconColumnDescriptor.priority, + ImageColumnDescriptor.priority, + TextColumnDescriptor.fixCount, + TextColumnDescriptor.since, + TextColumnDescriptor.ruleSetName, + TextColumnDescriptor.ruleType, + TextColumnDescriptor.minLangVers, + TextColumnDescriptor.maxLangVers, + TextColumnDescriptor.language, + ImageColumnDescriptor.filterViolationRegex, // regex text -> compact color squares (for comparison) + ImageColumnDescriptor.filterViolationXPath, // xpath text -> compact color circles (for comparison) + TextColumnDescriptor.modCount, + // TextColumnDescriptor.properties + ImageColumnDescriptor.properties + }; + + // last item in this list is the grouping used at startup + private static final Object[][] groupingChoices = new Object[][] { + { TextColumnDescriptor.ruleSetName, StringKeys.MSGKEY_PREF_RULESET_COLUMN_RULESET}, + { TextColumnDescriptor.since, StringKeys.MSGKEY_PREF_RULESET_GROUPING_PMD_VERSION }, + { TextColumnDescriptor.priorityName, StringKeys.MSGKEY_PREF_RULESET_COLUMN_PRIORITY }, + { TextColumnDescriptor.ruleType, StringKeys.MSGKEY_PREF_RULESET_COLUMN_RULE_TYPE }, + { TextColumnDescriptor.language, StringKeys.MSGKEY_PREF_RULESET_COLUMN_LANGUAGE }, + { ImageColumnDescriptor.filterViolationRegex, StringKeys.MSGKEY_PREF_RULESET_GROUPING_REGEX }, + { null, StringKeys.MSGKEY_PREF_RULESET_GROUPING_NONE } + }; + + public RuleEditorView() { + + } + + /** + * @param rule Rule + * @return String + */ + public static String propertyStringFrom(Rule rule, String modifiedTag) { + + Map<PropertyDescriptor<?>, Object> valuesByProp = Configuration.filteredPropertiesOf(rule); + + if (valuesByProp.isEmpty()) return ""; + StringBuilder sb = new StringBuilder(); + + Iterator<Map.Entry<PropertyDescriptor<?>, Object>> iter = valuesByProp.entrySet().iterator(); + + Map.Entry<PropertyDescriptor<?>, Object> entry = iter.next(); + sb.append(entry.getKey().name()).append(": "); + formatValueOn(sb, entry, modifiedTag); + + while (iter.hasNext()) { + entry = iter.next(); + sb.append(", ").append(entry.getKey().name()).append(": "); + formatValueOn(sb, entry, modifiedTag); + } + return sb.toString(); + } + + private static int formatValueOn(StringBuilder target, Map.Entry<PropertyDescriptor<?>, Object> entry, String modifiedTag) { + + Object value = entry.getValue(); + Class<?> datatype = entry.getKey().type(); + + boolean isModified = !RuleUtil.isDefaultValue(entry); + if (isModified) target.append(modifiedTag); + + ValueFormatter formatter = FormatManager.formatterFor(datatype); + if (formatter != null) { + String output = formatter.format(value); + target.append(output); + return isModified ? output.length() : 0; + } + + String out = String.valueOf(value); + target.append(out); // should not get here..breakpoint here + return isModified ? out.length() : 0; + } + + public static String ruleSetNameFrom(Rule rule) { + return ruleSetNameFrom( rule.getRuleSetName() ); + } + + public static String ruleSetNameFrom(String rulesetName) { + + int pos = rulesetName.toUpperCase().indexOf("RULES"); + return pos < 0 ? rulesetName : rulesetName.substring(0, pos-1); + } + + /** + * @param rule Rule + * @return String + */ + public static IndexedString indexedPropertyStringFrom(Rule rule) { + + Map<PropertyDescriptor<?>, Object> valuesByProp = Configuration.filteredPropertiesOf(rule); + + if (valuesByProp.isEmpty()) return IndexedString.Empty; + StringBuilder sb = new StringBuilder(); + + Iterator<Map.Entry<PropertyDescriptor<?>, Object>> iter = valuesByProp.entrySet().iterator(); + + List<int[]> modValueIndexes = new ArrayList<int[]>(valuesByProp.size()); + + Map.Entry<PropertyDescriptor<?>, Object> entry = iter.next(); + sb.append(entry.getKey().name()).append(": "); + int start = sb.length(); + int stop = start + formatValueOn(sb, entry, ""); + if (stop > start) modValueIndexes.add(new int[] { start, stop }); + + while (iter.hasNext()) { + entry = iter.next(); + sb.append(", ").append(entry.getKey().name()).append(": "); + start = sb.length(); + stop = start + formatValueOn(sb, entry, ""); + if (stop > start) modValueIndexes.add(new int[] { start, stop }); + } + return new IndexedString(sb.toString(), modValueIndexes); + } + + protected String descriptionId() { + return StringKeys.MSGKEY_PREF_RULESET_TITLE; + } + + @Override + public void createPartControl(Composite parent) { + + tableManager = new RuleTableManager(availableColumns, PMDPlugin.getDefault().loadPreferences()); + tableManager.modifyListener(this); + tableManager.selectionListener(this); + + populateRuleset(); + + Composite composite = new Composite(parent, SWT.NULL); + layoutControls(composite); + + tableManager.populateRuleTable(); + int i = PreferenceUIStore.instance.selectedPropertyTab() ; + tabFolder.setSelection( i ); + + } + +// public void createControl(Composite parent) { +// super.createControl(parent); +// +// setModified(false); +// } + /** + * Create buttons for rule properties table management + * @param parent Composite + * @return Composite + */ + private Composite buildRulePropertiesTableButtons(Composite parent) { + Composite composite = new Composite(parent, SWT.NULL); + RowLayout rowLayout = new RowLayout(); + rowLayout.type = SWT.VERTICAL; + rowLayout.wrap = false; + rowLayout.pack = false; + composite.setLayout(rowLayout); + + return composite; + } + + private Composite createRuleSection(Composite parent) { + + Composite ruleSection = new Composite(parent, SWT.NULL); + + // Create the controls (order is important !) + Composite groupCombo = tableManager.buildGroupCombo(ruleSection, StringKeys.MSGKEY_PREF_RULESET_RULES_GROUPED_BY, groupingChoices); + + Tree ruleTree = tableManager.buildRuleTreeViewer(ruleSection); + tableManager.groupBy(null); + + Composite ruleTableButtons = tableManager.buildRuleTableButtons(ruleSection); + Composite rulePropertiesTableButtons = buildRulePropertiesTableButtons(ruleSection); + + // Place controls on the layout + GridLayout gridLayout = new GridLayout(3, false); + ruleSection.setLayout(gridLayout); + + GridData data = new GridData(); + data.horizontalSpan = 3; + groupCombo.setLayoutData(data); + + data = new GridData(); + data.heightHint = 200; data.widthHint = 350; + data.horizontalSpan = 1; + data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; + ruleTree.setLayoutData(data); + + data = new GridData(); + data.horizontalSpan = 1; + data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; + ruleTableButtons.setLayoutData(data); + + data = new GridData(); + data.horizontalSpan = 1; + data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; + rulePropertiesTableButtons.setLayoutData(data); + + return ruleSection; + } + + /** + * Method buildTabFolder. + * @param parent Composite + * @return TabFolder + */ + private TabFolder buildTabFolder(Composite parent) { + + tabFolder = new TabFolder(parent, SWT.TOP); + + rulePropertyManagers = new RulePropertyManager[] { + buildRuleTab(tabFolder, 0, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_RULE)), + buildDescriptionTab(tabFolder, 1, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_DESCRIPTION)), + buildPropertyTab(tabFolder, 2, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_PROPERTIES)), + buildUsageTab(tabFolder, 3, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FILTERS)), + buildXPathTab(tabFolder, 4, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_XPATH)), +// buildQuickFixTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FIXES)), + buildExampleTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_EXAMPLES)), + }; + + tabFolder.pack(); + return tabFolder; + } + + /** + * @param parent TabFolder + * @param index int + */ + private RulePropertyManager buildRuleTab(TabFolder parent, int index, String title) { + + TabItem tab = new TabItem(parent, 0, index); + tab.setText(title); + + RulePanelManager manager = new RulePanelManager(title, EditorUsageMode.Editing, this, null); + tab.setControl( + manager.setupOn(parent) + ); + manager.tab(tab); + return manager; + } + + /** + * @param parent TabFolder + * @param index int + */ + private RulePropertyManager buildPropertyTab(TabFolder parent, int index, String title) { + + TabItem tab = new TabItem(parent, 0, index); + tab.setText(title); + + PerRulePropertyPanelManager manager = new PerRulePropertyPanelManager(title, EditorUsageMode.Editing, this); + tab.setControl( + manager.setupOn(parent) + ); + manager.tab(tab); + return manager; + } + + /** + * @param parent TabFolder + * @param index int + */ + private RulePropertyManager buildDescriptionTab(TabFolder parent, int index, String title) { + + TabItem tab = new TabItem(parent, 0, index); + tab.setText(title); + + DescriptionPanelManager manager = new DescriptionPanelManager(title, EditorUsageMode.Editing, this); + tab.setControl( + manager.setupOn(parent) + ); + manager.tab(tab); + return manager; + } + + /** + * @param parent TabFolder + * @param index int + */ + private RulePropertyManager buildXPathTab(TabFolder parent, int index, String title) { + + TabItem tab = new TabItem(parent, 0, index); + tab.setText(title); + + XPathPanelManager manager = new XPathPanelManager(title, EditorUsageMode.Editing, this); + tab.setControl( + manager.setupOn(parent) + ); + manager.tab(tab); + return manager; + } + + /** + * @param parent TabFolder + * @param index int + */ + private RulePropertyManager buildExampleTab(TabFolder parent, int index, String title) { + + TabItem tab = new TabItem(parent, 0, index); + tab.setText(title); + + ExamplePanelManager manager = new ExamplePanelManager(title, EditorUsageMode.Editing, this); + tab.setControl( + manager.setupOn(parent) + ); + manager.tab(tab); + return manager; + } + + /** + * @param parent TabFolder + * @param index int + */ + private RulePropertyManager buildQuickFixTab(TabFolder parent, int index, String title) { + + TabItem tab = new TabItem(parent, 0, index); + tab.setText(title); + + QuickFixPanelManager manager = new QuickFixPanelManager(title, EditorUsageMode.Editing, this); + tab.setControl( + manager.setupOn(parent) + ); + manager.tab(tab); + return manager; + } + + /** + * + * @param parent TabFolder + * @param index int + * @param title String + */ + private RulePropertyManager buildUsageTab(TabFolder parent, int index, String title) { + + TabItem tab = new TabItem(parent, 0, index); + tab.setText(title); + + ExclusionPanelManager manager = new ExclusionPanelManager(title, EditorUsageMode.Editing, this, true); + tab.setControl( + manager.setupOn(parent) + ); + manager.tab(tab); + return manager; + } + + public void changed(Rule rule, PropertyDescriptor<?> desc, Object newValue) { + // TODO enhance to recognize default values + setModified(); + tableManager.updated(rule); + } + + public void changed(RuleSelection selection, PropertyDescriptor<?> desc, Object newValue) { + // TODO enhance to recognize default values + + for (Rule rule : selection.allRules()) { + if (newValue != null) { // non-reliable update behaviour, alternate trigger option - weird + tableManager.changed(selection, desc, newValue); + // System.out.println("doing redraw"); + } else { + tableManager.changed(rule, desc, newValue); + // System.out.println("viewer update"); + } + } + for (RulePropertyManager manager : rulePropertyManagers) { + manager.validate(); + } + + setModified(); + } + + /** + * Main layout + * @param parent Composite + */ + private void layoutControls(Composite parent) { + + parent.setLayout(new FormLayout()); + int ruleTableFraction = 55; //PreferenceUIStore.instance.tableFraction(); + + // Create the sash first, so the other controls can be attached to it. + final Sash sash = new Sash(parent, SWT.HORIZONTAL); + FormData data = new FormData(); + data.left = new FormAttachment(0, 0); // attach to left + data.right = new FormAttachment(100, 0); // attach to right + data.top = new FormAttachment(ruleTableFraction, 0); + sash.setLayoutData(data); + sash.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + // Re-attach to the top edge, and we use the y value of the event to determine the offset from the top + ((FormData)sash.getLayoutData()).top = new FormAttachment(0, event.y); +// PreferenceUIStore.instance.tableFraction(event.y); + sash.getParent().layout(); + } + }); + + // Create the first text box and attach its bottom edge to the sash + Composite ruleSection = createRuleSection(parent); + data = new FormData(); + data.top = new FormAttachment(0, 0); + data.bottom = new FormAttachment(sash, 0); + data.left = new FormAttachment(0, 0); + data.right = new FormAttachment(100, 0); + ruleSection.setLayoutData(data); + + // Create the second text box and attach its top edge to the sash + TabFolder propertySection = buildTabFolder(parent); + data = new FormData(); + data.top = new FormAttachment(sash, 0); + data.bottom = new FormAttachment(100, 0); + data.left = new FormAttachment(0, 0); + data.right = new FormAttachment(100, 0); + propertySection.setLayoutData(data); + } + + /** + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + + public void performOk() { + + saveUIState(); + +// if (isModified()) { +// updateRuleSet(); +// rebuildProjects(); +// storeActiveRules(); +// } + } + + /** + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + + protected void performDefaults() { + tableManager.populateRuleTable(); + } + + private void populateRuleset() { + + RuleSet defaultRuleSet = plugin.getPreferencesManager().getRuleSet(); + RuleSet ruleSet = new RuleSet(); + ruleSet.addRuleSet(defaultRuleSet); + ruleSet.setName(defaultRuleSet.getName()); + ruleSet.setDescription(Util.asCleanString(defaultRuleSet.getDescription())); + ruleSet.addExcludePatterns(defaultRuleSet.getExcludePatterns()); + ruleSet.addIncludePatterns(defaultRuleSet.getIncludePatterns()); + + tableManager.useRuleSet(ruleSet); + } + + public void selection(RuleSelection selection) { + + if (rulePropertyManagers == null) return; + + for (RulePropertyManager manager : rulePropertyManagers) { + manager.manage(selection); + manager.validate(); + } + } + + /** + * If user wants to, rebuild all projects + */ + private void rebuildProjects() { +// if (MessageDialog.openQuestion(getShell(), getMessage(StringKeys.MSGKEY_QUESTION_TITLE), +// getMessage(StringKeys.MSGKEY_QUESTION_RULES_CHANGED))) { +// try { +// ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(getShell()); +// monitorDialog.run(true, true, new IRunnableWithProgress() { +// public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { +// try { +// ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor); +// } catch (CoreException e) { +// plugin.logError("Exception building all projects after a preference change", e); +// } +// } +// }); +// } catch (Exception e) { +// plugin.logError("Exception building all projects after a preference change", e); +// } +// } + } + + private void saveUIState() { + tableManager.saveUIState(); + int i = tabFolder.getSelectionIndex(); + PreferenceUIStore.instance.selectedPropertyTab( i ); + PreferenceUIStore.instance.save(); + } + + + private void storeActiveRules() { + + List<Rule> chosenRules = tableManager.activeRules(); + for (Rule rule : chosenRules) { + preferences.isActive(rule.getName(), true); + } + + System.out.println("Active rules: " + preferences.getActiveRuleNames()); + } + + /** + * Update the configured rule set + * Update also all configured projects + */ + private void updateRuleSet() { +// try { +// ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(getShell()); +// monitorDialog.run(true, true, new IRunnableWithProgress() { +// public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { +// plugin.getPreferencesManager().setRuleSet(tableManager.ruleSet()); +// } +// }); +// } catch (Exception e) { +// plugin.logError("Exception updating all projects after a preference change", e); +// } + } + + protected String getMessage(String key) { + return PMDPlugin.getDefault().getStringTable().getString(key); + } + + public void setModified() { + // TODO Auto-generated method stub + + } + + @Override + public void setFocus() { + // TODO Auto-generated method stub + + } +} diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/FontBuilder.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/FontBuilder.java index 150811711a7..827a1373602 100755 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/FontBuilder.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/FontBuilder.java @@ -4,7 +4,10 @@ import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.widgets.Display; - +/** + * + * @author Brian Remedios + */ public class FontBuilder { public final String name; diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/Util.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/Util.java index 75effb446a5..e95e104d7bc 100644 --- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/Util.java +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/util/Util.java @@ -10,12 +10,14 @@ import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; +import net.sourceforge.pmd.eclipse.ui.Shape; +import net.sourceforge.pmd.eclipse.ui.ShapeDescriptor; +import net.sourceforge.pmd.eclipse.ui.ShapePainter; import net.sourceforge.pmd.eclipse.ui.preferences.br.CellPainterBuilder; import net.sourceforge.pmd.eclipse.ui.preferences.br.IndexedString; import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleCollection; import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleFieldAccessor; import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleUtil; -import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ShapeDescriptor; import net.sourceforge.pmd.util.ClassUtil; import net.sourceforge.pmd.util.StringUtil; @@ -71,7 +73,10 @@ public static List<int[]> referencedNamePositionsIn(String source, char prefix) int end = pos+1; while (end < max && Character.isLetter(source.charAt(end)) ) end++; int length = end - pos -1; - if (length < 1) continue; + if (length < 1) { + pos = source.indexOf(prefix, pos + 1); + continue; + } namePositions.add( new int[] {pos+1, length} ); pos = source.indexOf(prefix, pos + length); @@ -196,9 +201,8 @@ public static String asCleanString(String original) { return original == null ? "" : original.trim(); } - public static enum shape { square, circle, diamond, triangleUp, triangleDown, triangleNorthEast, triangleSouthEast }; - public static CellPainterBuilder textAsColorShapeFor(final int width, final int height, final shape shapeId) { + public static CellPainterBuilder textAsColorShapeFor(final int width, final int height, final Shape shapeId) { return new CellPainterBuilder() { @@ -238,7 +242,7 @@ public void handleEvent(Event event) { Color clr = colorManager().colourFor(text); event.gc.setBackground(clr); - drawShape(width, height, shapeId, event.gc, event.x, event.y); + ShapePainter.drawShape(width, height, shapeId, event.gc, event.x, event.y, null); event.gc.setBackground(original); } @@ -258,7 +262,7 @@ public void handleEvent(Event e) { }; } - public static CellPainterBuilder itemAsShapeFor(final int width, final int height, final shape shapeId, final int horizAlignment, final Map<Object, RGB> coloursByItem) { + public static CellPainterBuilder itemAsShapeFor(final int width, final int height, final Shape shapeId, final int horizAlignment, final Map<Object, RGB> coloursByItem) { return new CellPainterBuilder() { @@ -319,7 +323,7 @@ public void handleEvent(Event event) { case SWT.LEFT: xOffset = 0; } - drawShape(width, height, shapeId, event.gc, event.x + xOffset, event.y); + ShapePainter.drawShape(width, height, shapeId, event.gc, event.x + xOffset, event.y, null); event.gc.setBackground(original); } @@ -340,34 +344,6 @@ public void handleEvent(Event e) { }; } - /** - * Creates an image initialized with the transparent colour with the shape drawn within. - * - * - */ - public static Image newDrawnImage(Display display, int width, int height, shape shape, RGB transparentColour, RGB fillColour) { - - Image image = new Image(display, width, height); - GC gc = new GC(image); - - gc.setBackground(PMDPlugin.getDefault().colorFor(transparentColour)); - gc.fillRectangle(0, 0, width, height); - - gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); - gc.setBackground(PMDPlugin.getDefault().colorFor(fillColour)); - - drawShape(width-1, height-1, shape, gc, 0, 0); - - ImageData data = image.getImageData(); - int clrIndex = data.palette.getPixel(transparentColour); - data.transparentPixel = clrIndex; - - image = new Image(display, data); - - gc.dispose(); - return image; - } - public static CellPainterBuilder uniqueItemsAsShapeFor(final int width, final int height, final int horizAlignment, final Map<Object, ShapeDescriptor> shapesByItem) { return new CellPainterBuilder() { @@ -437,7 +413,7 @@ public void handleEvent(Event event) { case SWT.LEFT: xOffset = xBoundary + step; } - drawShape(width, height, shape.shape, gc, event.x + xOffset, event.y + verticalOffset); + ShapePainter.drawShape(width, height, shape.shape, gc, event.x + xOffset, event.y + verticalOffset, null); } gc.setBackground(original); @@ -475,46 +451,7 @@ private static void addListener(Control control, int eventType, Listener listene listenersByEventCode.get(eventCode).add(listener); } - public static void drawShape(int width, int height, shape shapeId, GC gc, int x, int y) { - - switch (shapeId) { - case square: { - gc.fillRectangle(x, y, width, height); // fill it - gc.drawRectangle(x, y, width, height); // then the border on top - break; - } - case circle: { - gc.fillArc(x, y, width, height, 0, 360*64); // fill it - gc.drawArc(x, y, width, height, 0, 360*64); // then the border on top - break; - } - case triangleDown: { - gc.fillPolygon(new int[] {x, y, x+width, y, x+(width/2), y+height}); - gc.drawPolygon(new int[] {x, y, x+width, y, x+(width/2), y+height}); - break; - } - case triangleUp: { - gc.fillPolygon(new int[] {x, y+height, x+width, y+height, x+(width/2), y}); - gc.drawPolygon(new int[] {x, y+height, x+width, y+height, x+(width/2), y}); - break; - } - case triangleNorthEast: { - gc.fillPolygon(new int[] {x, y, x+width, y, x+width, y+height}); - gc.drawPolygon(new int[] {x, y, x+width, y, x+width, y+height}); - break; - } - case triangleSouthEast: { - gc.fillPolygon(new int[] {x, y+height, x+width, y+height, x+width, y}); - gc.drawPolygon(new int[] {x, y+height, x+width, y+height, x+width, y}); - break; - } - case diamond: { - gc.fillPolygon(new int[] {x+(width/2), y, x+width, y+(height/2), x+(width/2), y+height, x, y+(height/2)}); - gc.drawPolygon(new int[] {x+(width/2), y, x+width, y+(height/2), x+(width/2), y+height, x, y+(height/2)}); - break; - } - } - } + public static CellPainterBuilder backgroundBuilderFor(final int systemColourIndex) { diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/test/net/sourceforge/pmd/eclipse/ui/ShapeSetCanvasTest.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/test/net/sourceforge/pmd/eclipse/ui/ShapeSetCanvasTest.java new file mode 100755 index 00000000000..5529c055a7f --- /dev/null +++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/test/net/sourceforge/pmd/eclipse/ui/ShapeSetCanvasTest.java @@ -0,0 +1,37 @@ +package net.sourceforge.pmd.eclipse.ui; + +import net.sourceforge.pmd.eclipse.plugin.UISettings; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +public class ShapeSetCanvasTest { + + public static void main(String [] args) { + final Display display = new Display(); + final Shell shell = new Shell(display); + shell.setLayout (new GridLayout()); + + ShapePicker<Shape> ssc = new ShapePicker<Shape>(shell, SWT.None, 36); + ssc.setLayoutData( new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); + ssc.setSize(770, 55); + + ssc.setShapeMap(UISettings.shapeSet(new RGB(255,255,255), 15)); + ssc.setItems( UISettings.allShapes() ); + shell.pack(); + + shell.setBounds(10, 10, 780, 200); + shell.open(); + + while (!shell.isDisposed()) { + if (!display.readAndDispatch()) display.sleep(); + } + display.dispose(); + } + } + +
f9f7c57dbf2cd80f2f486d78da0c90a014617e19
camel
[CAMEL-1510] BatchProcessor interrupt has side- effects (submitted on behalf of Christopher Hunt)--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@765686 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java index a35b33f052d10..0589899f52972 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java @@ -18,7 +18,12 @@ import java.util.Collection; import java.util.Iterator; -import java.util.concurrent.LinkedBlockingQueue; +import java.util.LinkedList; +import java.util.Queue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; import org.apache.camel.Exchange; import org.apache.camel.Processor; @@ -30,13 +35,12 @@ import org.apache.camel.util.ServiceHelper; /** - * A base class for any kind of {@link Processor} which implements some kind of - * batch processing. + * A base class for any kind of {@link Processor} which implements some kind of batch processing. * * @version $Revision$ */ public class BatchProcessor extends ServiceSupport implements Processor { - + public static final long DEFAULT_BATCH_TIMEOUT = 1000L; public static final int DEFAULT_BATCH_SIZE = 100; @@ -82,9 +86,9 @@ public int getBatchSize() { } /** - * Sets the <b>in</b> batch size. This is the number of incoming exchanges that this batch processor - * will process before its completed. The default value is {@link #DEFAULT_BATCH_SIZE}. - * + * Sets the <b>in</b> batch size. This is the number of incoming exchanges that this batch processor will + * process before its completed. The default value is {@link #DEFAULT_BATCH_SIZE}. + * * @param batchSize the size */ public void setBatchSize(int batchSize) { @@ -96,10 +100,10 @@ public int getOutBatchSize() { } /** - * Sets the <b>out</b> batch size. If the batch processor holds more exchanges than this out size then - * the completion is triggered. Can for instance be used to ensure that this batch is completed when - * a certain number of exchanges has been collected. By default this feature is <b>not</b> enabled. - * + * Sets the <b>out</b> batch size. If the batch processor holds more exchanges than this out size then the + * completion is triggered. Can for instance be used to ensure that this batch is completed when a certain + * number of exchanges has been collected. By default this feature is <b>not</b> enabled. + * * @param outBatchSize the size */ public void setOutBatchSize(int outBatchSize) { @@ -127,16 +131,16 @@ public Processor getProcessor() { } /** - * A strategy method to decide if the "in" batch is completed. That is, whether the resulting - * exchanges in the in queue should be drained to the "out" collection. + * A strategy method to decide if the "in" batch is completed. That is, whether the resulting exchanges in + * the in queue should be drained to the "out" collection. */ protected boolean isInBatchCompleted(int num) { return num >= batchSize; } - + /** - * A strategy method to decide if the "out" batch is completed. That is, whether the resulting - * exchange in the out collection should be sent. + * A strategy method to decide if the "out" batch is completed. That is, whether the resulting exchange in + * the out collection should be sent. */ protected boolean isOutBatchCompleted() { if (outBatchSize == 0) { @@ -147,9 +151,8 @@ protected boolean isOutBatchCompleted() { } /** - * Strategy Method to process an exchange in the batch. This method allows - * derived classes to perform custom processing before or after an - * individual exchange is processed + * Strategy Method to process an exchange in the batch. This method allows derived classes to perform + * custom processing before or after an individual exchange is processed */ protected void processExchange(Exchange exchange) throws Exception { processor.process(exchange); @@ -181,53 +184,119 @@ public void process(Exchange exchange) throws Exception { * Sender thread for queued-up exchanges. */ private class BatchSender extends Thread { - - private volatile boolean cancelRequested; - private LinkedBlockingQueue<Exchange> queue; - + private Queue<Exchange> queue; + private Lock queueLock = new ReentrantLock(); + private boolean exchangeEnqueued; + private Condition exchangeEnqueuedCondition = queueLock.newCondition(); + public BatchSender() { super("Batch Sender"); - this.queue = new LinkedBlockingQueue<Exchange>(); + this.queue = new LinkedList<Exchange>(); } @Override public void run() { - while (true) { - try { - Thread.sleep(batchTimeout); - queue.drainTo(collection, batchSize); - } catch (InterruptedException e) { - if (cancelRequested) { - return; - } - - while (isInBatchCompleted(queue.size())) { - queue.drainTo(collection, batchSize); - } - - if (!isOutBatchCompleted()) { - continue; + // Wait until one of either: + // * an exchange being queued; + // * the batch timeout expiring; or + // * the thread being cancelled. + // + // If an exchange is queued then we need to determine whether the + // batch is complete. If it is complete then we send out the batched + // exchanges. Otherwise we move back into our wait state. + // + // If the batch times out then we send out the batched exchanges + // collected so far. + // + // If we receive an interrupt then all blocking operations are + // interrupted and our thread terminates. + // + // The goal of the following algorithm in terms of synchronisation + // is to provide fine grained locking i.e. retaining the lock only + // when required. Special consideration is given to releasing the + // lock when calling an overloaded method such as isInBatchComplete, + // isOutBatchComplete and around sendExchanges. The latter is + // especially important as the process of sending out the exchanges + // would otherwise block new exchanges from being queued. + + queueLock.lock(); + try { + do { + try { + if (!exchangeEnqueued) { + exchangeEnqueuedCondition.await(batchTimeout, TimeUnit.MILLISECONDS); + } + + if (!exchangeEnqueued) { + drainQueueTo(collection, batchSize); + } else { + exchangeEnqueued = false; + while (isInBatchCompleted(queue.size())) { + drainQueueTo(collection, batchSize); + } + + queueLock.unlock(); + try { + if (!isOutBatchCompleted()) { + continue; + } + } finally { + queueLock.lock(); + } + } + + queueLock.unlock(); + try { + try { + sendExchanges(); + } catch (Exception e) { + getExceptionHandler().handleException(e); + } + } finally { + queueLock.lock(); + } + + } catch (InterruptedException e) { + break; } - } - try { - sendExchanges(); - } catch (Exception e) { - getExceptionHandler().handleException(e); + + } while (true); + + } finally { + queueLock.unlock(); + } + } + + /** + * This method should be called with queueLock held + */ + private void drainQueueTo(Collection<Exchange> collection, int batchSize) { + for (int i = 0; i < batchSize; ++i) { + Exchange e = queue.poll(); + if (e != null) { + collection.add(e); + } else { + break; } } } - + public void cancel() { - cancelRequested = true; interrupt(); } - + public void enqueueExchange(Exchange exchange) { - queue.add(exchange); - interrupt(); + queueLock.lock(); + try { + queue.add(exchange); + exchangeEnqueued = true; + exchangeEnqueuedCondition.signal(); + } finally { + queueLock.unlock(); + } } - + private void sendExchanges() throws Exception { GroupedExchange grouped = null; @@ -253,5 +322,5 @@ private void sendExchanges() throws Exception { } } } - + }
bd270ae7311518b5986d1d1ede93b8a970a05126
eclipsesource$tabris
Improves Passe-Partout and Tracking API Test Stability Integrates the TabrisEnvironment into the Passe-Partout and Tracking API tests. Change-Id: I6e16aceba9cc4913156a5efa589e039817368589
p
https://github.com/eclipsesource/tabris
diff --git a/com.eclipsesource.tabris.passepartout.test/META-INF/MANIFEST.MF b/com.eclipsesource.tabris.passepartout.test/META-INF/MANIFEST.MF index 7ffac42..47b2954 100644 --- a/com.eclipsesource.tabris.passepartout.test/META-INF/MANIFEST.MF +++ b/com.eclipsesource.tabris.passepartout.test/META-INF/MANIFEST.MF @@ -8,6 +8,6 @@ Fragment-Host: com.eclipsesource.tabris.passepartout;bundle-version="0.10.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: org.junit;bundle-version="[4.10.0,5.0.0)", org.mockito.mockito-all;bundle-version="1.9.5", - org.eclipse.rap.rwt.testfixture;bundle-version="2.2.0", org.eclipse.rap.rwt;bundle-version="2.2.0", - org.eclipse.rap.jface;bundle-version="2.2.0" + org.eclipse.rap.jface;bundle-version="2.2.0", + com.eclipsesource.tabris.test.util;bundle-version="1.4.0" diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/FluidGridLayoutTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/FluidGridLayoutTest.java index 63837da..9f0630c 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/FluidGridLayoutTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/FluidGridLayoutTest.java @@ -20,7 +20,6 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; @@ -29,30 +28,28 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import com.eclipsesource.tabris.passepartout.internal.RelayoutListener; import com.eclipsesource.tabris.passepartout.internal.condition.AlwaysTrueContidtion; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; @SuppressWarnings("restriction") public class FluidGridLayoutTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Shell shell; @Before public void setUp() { - Fixture.setUp(); shell = new Shell( new Display() ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test( expected = IllegalArgumentException.class ) public void testFailsWithNullMode() { new FluidGridLayout( null ); diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/PassePartoutTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/PassePartoutTest.java index 225f9ca..0f87900 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/PassePartoutTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/PassePartoutTest.java @@ -18,11 +18,8 @@ import java.math.BigDecimal; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -41,23 +38,21 @@ import com.eclipsesource.tabris.passepartout.internal.unit.Em; import com.eclipsesource.tabris.passepartout.internal.unit.Percentage; import com.eclipsesource.tabris.passepartout.internal.unit.Pixel; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class PassePartoutTest { + @org.junit.Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Display display; @Before public void setUp() { - Fixture.setUp(); display = new Display(); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test public void testCreatesFluidGridWithoutMode() { FluidGridLayout grid = PassePartout.createFluidGrid(); @@ -73,23 +68,23 @@ public void testCreatesFluidGridWithMode() { } @Test - public void testCreateFluidGridData() { - Rule rule1 = mock( Rule.class ); - Rule rule2 = mock( Rule.class ); - - FluidGridData data = PassePartout.createFluidGridData( rule1, rule2 ); - - assertNotNull( data ); - assertEquals( rule1, data.getRules().get( 1 ) ); - assertEquals( rule2, data.getRules().get( 2 ) ); - } + public void testCreateFluidGridData() { + Rule rule1 = mock( Rule.class ); + Rule rule2 = mock( Rule.class ); + + FluidGridData data = PassePartout.createFluidGridData( rule1, rule2 ); + + assertNotNull( data ); + assertEquals( rule1, data.getRules().get( 1 ) ); + assertEquals( rule2, data.getRules().get( 2 ) ); + } @Test( expected = IllegalArgumentException.class ) - public void testCreateFluidGridDataFailsWithNullRule() { - Rule rule1 = mock( Rule.class ); - - PassePartout.createFluidGridData( rule1, null ); - } + public void testCreateFluidGridDataFailsWithNullRule() { + Rule rule1 = mock( Rule.class ); + + PassePartout.createFluidGridData( rule1, null ); + } @Test public void testCreateResourceCreatesResource() { @@ -280,16 +275,14 @@ public void testBackgroundCreatesBackgroundInstruction() { @Test public void testImageCreatesImageInstruction() { - Instruction instruction = PassePartout.image( new Image( display, - Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ) ); + Instruction instruction = PassePartout.image( environment.getTestImage() ); assertTrue( instruction instanceof ImageInstruction ); } @Test public void testBackgroundImageCreatesBackgroundImageInstruction() { - Instruction instruction = PassePartout.backgroundImage( new Image( display, - Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ) ); + Instruction instruction = PassePartout.backgroundImage( environment.getTestImage() ); assertTrue( instruction instanceof BackgroundImageInstruction ); } diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/RelayoutListenerTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/RelayoutListenerTest.java index 9cecea8..7666203 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/RelayoutListenerTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/RelayoutListenerTest.java @@ -14,7 +14,6 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; @@ -22,22 +21,26 @@ import org.eclipse.swt.widgets.Shell; import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + public class RelayoutListenerTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Shell shell; @Before public void setUp() { - Fixture.setUp(); shell = new Shell( new Display() ); } @After public void tearDown() { - Fixture.tearDown(); } @Test( expected = IllegalArgumentException.class ) diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/ResourceImplTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/ResourceImplTest.java index 9bbef1c..ff87afb 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/ResourceImplTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/ResourceImplTest.java @@ -15,7 +15,6 @@ import static org.mockito.Mockito.mock; import org.eclipse.jface.resource.FontDescriptor; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; @@ -28,7 +27,6 @@ import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Widget; -import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -40,23 +38,21 @@ import com.eclipsesource.tabris.passepartout.internal.instruction.FontInstruction; import com.eclipsesource.tabris.passepartout.internal.instruction.ForegroundInstruction; import com.eclipsesource.tabris.passepartout.internal.instruction.ImageInstruction; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class ResourceImplTest { + @org.junit.Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Shell shell; @Before public void setUp() { - Fixture.setUp(); shell = new Shell( new Display() ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test( expected = IllegalArgumentException.class ) public void testFailsWithNullRules() { Rule[] rules = null; @@ -124,7 +120,7 @@ public void testAppliesBackground() { @Test public void testAppliesBackgroundImage() { - Image image = new Image( shell.getDisplay(), Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ); + Image image = environment.getTestImage(); Rule rule = PassePartout.when( new AlwaysTrueContidtion() ).then( new BackgroundImageInstruction( image ) ); ResourceImpl resource = new ResourceImpl( rule ); @@ -136,7 +132,7 @@ public void testAppliesBackgroundImage() { @Test public void testAppliesImageOnLabel() { Label label = new Label( shell, SWT.NONE ); - Image image = new Image( shell.getDisplay(), Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ); + Image image = environment.getTestImage(); Rule rule = PassePartout.when( new AlwaysTrueContidtion() ).then( new ImageInstruction( image ) ); ResourceImpl resource = new ResourceImpl( rule ); @@ -148,7 +144,7 @@ public void testAppliesImageOnLabel() { @Test public void testAppliesImageOnButton() { Button button = new Button( shell, SWT.PUSH ); - Image image = new Image( shell.getDisplay(), Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ); + Image image = environment.getTestImage(); Rule rule = PassePartout.when( new AlwaysTrueContidtion() ).then( new ImageInstruction( image ) ); ResourceImpl resource = new ResourceImpl( rule ); @@ -161,7 +157,7 @@ public void testAppliesImageOnButton() { public void testAppliesImageOnItem() { ToolBar toolBar = new ToolBar( shell, SWT.NONE ); ToolItem toolItem = new ToolItem( toolBar, SWT.NONE ); - Image image = new Image( shell.getDisplay(), Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ); + Image image = environment.getTestImage(); Rule rule = PassePartout.when( new AlwaysTrueContidtion() ).then( new ImageInstruction( image ) ); ResourceImpl resource = new ResourceImpl( rule ); shell.open(); diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/UIEnvironmentFactoryTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/UIEnvironmentFactoryTest.java index ec98420..68091a2 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/UIEnvironmentFactoryTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/UIEnvironmentFactoryTest.java @@ -12,36 +12,33 @@ import static org.junit.Assert.assertEquals; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import com.eclipsesource.tabris.passepartout.Bounds; import com.eclipsesource.tabris.passepartout.UIEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class UIEnvironmentFactoryTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Shell shell; @Before public void setUp() { - Fixture.setUp(); shell = new Shell( new Display() ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test( expected = IllegalArgumentException.class ) public void testFailsWithNullWidget() { UIEnvironmentFactory.createEnvironment( null ); diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundImageInstructionTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundImageInstructionTest.java index 875bb57..dc476e5 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundImageInstructionTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundImageInstructionTest.java @@ -12,24 +12,23 @@ import static org.junit.Assert.assertSame; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + public class BackgroundImageInstructionTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + @Before public void setUp() { - Fixture.setUp(); - } - - @After - public void tearDown() { - Fixture.tearDown(); + new Display(); } @Test( expected = IllegalArgumentException.class ) @@ -39,8 +38,7 @@ public void testFailsWithNullImage() { @Test public void testHasImage() { - Display display = new Display(); - Image image = new Image( display, Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ); + Image image = environment.getTestImage(); BackgroundImageInstruction instruction = new BackgroundImageInstruction( image ); Image actualimage = instruction.getImage(); diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundInstructionTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundInstructionTest.java index bafc255..8c70156 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundInstructionTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/BackgroundInstructionTest.java @@ -12,25 +12,24 @@ import static org.junit.Assert.assertSame; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + public class BackgroundInstructionTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + @Before public void setUp() { - Fixture.setUp(); - } - - @After - public void tearDown() { - Fixture.tearDown(); + new Display(); } @Test( expected = IllegalArgumentException.class ) @@ -40,8 +39,7 @@ public void testFailsWithNullColor() { @Test public void testHasColor() { - Display display = new Display(); - Color color = display.getSystemColor( SWT.COLOR_BLACK ); + Color color = Display.getCurrent().getSystemColor( SWT.COLOR_BLACK ); BackgroundInstruction instruction = new BackgroundInstruction( color ); Color actualColor = instruction.getColor(); diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/FontInstructionTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/FontInstructionTest.java index c2978fe..6d281f8 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/FontInstructionTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/FontInstructionTest.java @@ -12,24 +12,25 @@ import static org.junit.Assert.assertSame; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + public class FontInstructionTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + + private Display display; + @Before public void setUp() { - Fixture.setUp(); - } - - @After - public void tearDown() { - Fixture.tearDown(); + display = new Display(); } @Test( expected = IllegalArgumentException.class ) @@ -39,7 +40,6 @@ public void testFailsWithNullFont() { @Test public void testHasFont() { - Display display = new Display(); Font font = display.getSystemFont(); FontInstruction instruction = new FontInstruction( font ); diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ForegroundInstructionTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ForegroundInstructionTest.java index 826ef9d..50fd19a 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ForegroundInstructionTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ForegroundInstructionTest.java @@ -12,25 +12,26 @@ import static org.junit.Assert.assertSame; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + public class ForegroundInstructionTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + + private Display display; + @Before public void setUp() { - Fixture.setUp(); - } - - @After - public void tearDown() { - Fixture.tearDown(); + display = new Display(); } @Test( expected = IllegalArgumentException.class ) @@ -40,7 +41,6 @@ public void testFailsWithNullColor() { @Test public void testHasColor() { - Display display = new Display(); Color color = display.getSystemColor( SWT.COLOR_BLACK ); ForegroundInstruction instruction = new ForegroundInstruction( color ); diff --git a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ImageInstructionTest.java b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ImageInstructionTest.java index 20c0def..4079d5e 100644 --- a/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ImageInstructionTest.java +++ b/com.eclipsesource.tabris.passepartout.test/src/com/eclipsesource/tabris/passepartout/internal/instruction/ImageInstructionTest.java @@ -12,24 +12,23 @@ import static org.junit.Assert.assertSame; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + public class ImageInstructionTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + @Before public void setUp() { - Fixture.setUp(); - } - - @After - public void tearDown() { - Fixture.tearDown(); + new Display(); } @Test( expected = IllegalArgumentException.class ) @@ -39,8 +38,7 @@ public void testFailsWithNullImage() { @Test public void testHasImage() { - Display display = new Display(); - Image image = new Image( display, Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ); + Image image = environment.getTestImage(); ImageInstruction instruction = new ImageInstruction( image ); Image actualimage = instruction.getImage(); diff --git a/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisEnvironment.java b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisEnvironment.java index 8d06499..65f3d6b 100644 --- a/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisEnvironment.java +++ b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisEnvironment.java @@ -24,6 +24,8 @@ import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.rap.rwt.testfixture.TestRequest; import org.eclipse.rap.rwt.testfixture.internal.engine.ThemeManagerHelper; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Display; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; @@ -116,4 +118,8 @@ public TabrisRequest newGetRequest() { return request; } + public Image getTestImage() { + return new Image( Display.getCurrent(), Fixture.class.getResourceAsStream( "/" + Fixture.IMAGE1 ) ); + } + } diff --git a/com.eclipsesource.tabris.tracking.test/META-INF/MANIFEST.MF b/com.eclipsesource.tabris.tracking.test/META-INF/MANIFEST.MF index 3d48710..494a7bb 100644 --- a/com.eclipsesource.tabris.tracking.test/META-INF/MANIFEST.MF +++ b/com.eclipsesource.tabris.tracking.test/META-INF/MANIFEST.MF @@ -8,5 +8,5 @@ Fragment-Host: com.eclipsesource.tabris.tracking;bundle-version="1.4.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: org.junit;bundle-version="[4.10.0,5.0.0)", org.mockito.mockito-all;bundle-version="1.9.5", - org.eclipse.rap.rwt.testfixture;bundle-version="2.2.0", - com.eclipsesource.rest.client.driver;bundle-version="1.0.0" + com.eclipsesource.rest.client.driver;bundle-version="1.0.0", + com.eclipsesource.tabris.test.util;bundle-version="1.4.0" diff --git a/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/TrackingTest.java b/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/TrackingTest.java index 28c8662..be4e093 100644 --- a/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/TrackingTest.java +++ b/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/TrackingTest.java @@ -21,14 +21,13 @@ import java.lang.Thread.UncaughtExceptionHandler; import java.util.List; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; -import com.eclipsesource.tabris.TabrisClient; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.tracking.TrackingEvent.EventType; import com.eclipsesource.tabris.tracking.internal.EventDispatcher; import com.eclipsesource.tabris.ui.Action; @@ -44,20 +43,16 @@ public class TrackingTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Display display; @Before public void setUp() { - Fixture.setUp(); - Fixture.fakeClient( mock( TabrisClient.class ) ); display = new Display(); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test( expected = IllegalArgumentException.class ) public void testFailsWithNullTracker() { new Tracking( ( Tracker )null ); diff --git a/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/internal/TrackingInfoFactoryTest.java b/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/internal/TrackingInfoFactoryTest.java index 31ec260..448827b 100644 --- a/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/internal/TrackingInfoFactoryTest.java +++ b/com.eclipsesource.tabris.tracking.test/src/com/eclipsesource/tabris/tracking/internal/TrackingInfoFactoryTest.java @@ -23,38 +23,40 @@ import java.util.UUID; import org.eclipse.rap.rwt.client.Client; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.eclipse.rap.rwt.testfixture.TestRequest; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import com.eclipsesource.tabris.ClientStore; import com.eclipsesource.tabris.app.App; import com.eclipsesource.tabris.device.ClientDevice; import com.eclipsesource.tabris.device.ClientDevice.Platform; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; +import com.eclipsesource.tabris.test.util.TabrisRequest; import com.eclipsesource.tabris.tracking.TrackingInfo; import com.eclipsesource.tabris.ui.UI; public class TrackingInfoFactoryTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private UI ui; private ClientStore clientStore; - private TestRequest request; + private TabrisRequest request; @Before public void setUp() { - Fixture.setUp(); Client client = mock( Client.class ); mockApp( client ); mockDevice( client ); mockClientStore( client ); - Fixture.fakeClient( client ); - request = Fixture.fakeNewRequest(); + environment.setClient( client ); + request = environment.newRequest(); mockUi(); } @@ -89,11 +91,6 @@ private void mockClientStore( Client client ) { when( client.getService( ClientStore.class ) ).thenReturn( clientStore ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test public void testCreatesNewClientIdOnFirstAccess() { TrackingInfo info = TrackingInfoFactory.createInfo( ui );
f95ec3f5bf12bee07c90943cff3b135e6a7e7a8b
hadoop
HADOOP-6133. Add a caching layer to- Configuration::getClassByName to alleviate a performance regression- introduced in a compatibility layer. Contributed by Todd Lipcon--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@812285 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index b3e5b2e07573c..a32e6c7905614 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -512,7 +512,8 @@ Trunk (unreleased changes) HADOOP-6176. Add a couple package private methods to AccessTokenHandler for testing. (Kan Zhang via szetszwo) - HADOOP-6182. Fix ReleaseAudit warnings (Giridharan Kesavan and Lee Tucker via gkesavan) + HADOOP-6182. Fix ReleaseAudit warnings (Giridharan Kesavan and Lee Tucker + via gkesavan) HADOOP-6173. Change src/native/packageNativeHadoop.sh to package all native library files. (Hong Tang via szetszwo) @@ -526,6 +527,10 @@ Trunk (unreleased changes) HADOOP-6231. Allow caching of filesystem instances to be disabled on a per-instance basis. (tomwhite) + HADOOP-6133. Add a caching layer to Configuration::getClassByName to + alleviate a performance regression introduced in a compatibility layer. + (Todd Lipcon via cdouglas) + OPTIMIZATIONS HADOOP-5595. NameNode does not need to run a replicator to choose a diff --git a/src/java/org/apache/hadoop/conf/Configuration.java b/src/java/org/apache/hadoop/conf/Configuration.java index cfb1ba8d70a54..8bf4c1c436eb2 100644 --- a/src/java/org/apache/hadoop/conf/Configuration.java +++ b/src/java/org/apache/hadoop/conf/Configuration.java @@ -170,6 +170,9 @@ public class Configuration implements Iterable<Map.Entry<String,String>>, */ private static final ArrayList<String> defaultResources = new ArrayList<String>(); + + private static final Map<ClassLoader, Map<String, Class<?>>> + CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, Class<?>>>(); /** * Flag to indicate if the storage of resource which updates a key needs @@ -1029,7 +1032,27 @@ public void setStrings(String name, String... values) { * @throws ClassNotFoundException if the class is not found. */ public Class<?> getClassByName(String name) throws ClassNotFoundException { - return Class.forName(name, true, classLoader); + Map<String, Class<?>> map; + + synchronized (CACHE_CLASSES) { + map = CACHE_CLASSES.get(classLoader); + if (map == null) { + map = Collections.synchronizedMap( + new WeakHashMap<String, Class<?>>()); + CACHE_CLASSES.put(classLoader, map); + } + } + + Class clazz = map.get(name); + if (clazz == null) { + clazz = Class.forName(name, true, classLoader); + if (clazz != null) { + // two putters can race here, but they'll put the same class + map.put(name, clazz); + } + } + + return clazz; } /**
804bf3ad226dca85c9fa66791bb63b794ab66b73
kotlin
Refactoring of- AnnotationResolver.resolveAnnotation(s)Arguments--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java index 8a2e891bcf974..84ed9c4377f3e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java @@ -144,7 +144,7 @@ private Annotations resolveAnnotationEntries( descriptor = new LazyAnnotationDescriptor(new LazyAnnotationsContextImpl(this, storageManager, trace, scope), entryElement); } if (shouldResolveArguments) { - resolveAnnotationArguments(entryElement, trace); + resolveAnnotationArguments(descriptor); } result.add(descriptor); @@ -202,30 +202,13 @@ public OverloadResolutionResults<FunctionDescriptor> resolveAnnotationCall( ); } - public static void resolveAnnotationsArguments(@Nullable JetModifierList modifierList, @NotNull BindingTrace trace) { - if (modifierList == null) { - return; - } - - for (JetAnnotationEntry annotationEntry : modifierList.getAnnotationEntries()) { - resolveAnnotationArguments(annotationEntry, trace); - } - } - - public static void resolveAnnotationsArguments(@NotNull Annotations annotations, @NotNull BindingTrace trace) { + public static void resolveAnnotationsArguments(@NotNull Annotations annotations) { for (AnnotationDescriptor annotationDescriptor : annotations) { - JetAnnotationEntry annotationEntry = trace.getBindingContext().get(ANNOTATION_DESCRIPTOR_TO_PSI_ELEMENT, annotationDescriptor); - assert annotationEntry != null : "Cannot find annotation entry: " + annotationDescriptor; - resolveAnnotationArguments(annotationEntry, trace); + resolveAnnotationArguments(annotationDescriptor); } } - private static void resolveAnnotationArguments( - @NotNull JetAnnotationEntry annotationEntry, - @NotNull BindingTrace trace - ) { - AnnotationDescriptor annotationDescriptor = trace.getBindingContext().get(BindingContext.ANNOTATION, annotationEntry); - assert annotationDescriptor != null : "Annotation descriptor should be created before resolving arguments for " + annotationEntry.getText(); + private static void resolveAnnotationArguments(@NotNull AnnotationDescriptor annotationDescriptor) { if (annotationDescriptor instanceof LazyAnnotationDescriptor) { ((LazyAnnotationDescriptor) annotationDescriptor).forceResolveAllContents(); } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolver.java index 92d9b51797f80..a8590f09f3a69 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolver.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolver.java @@ -159,7 +159,7 @@ public void resolveSecondaryConstructorBody( @NotNull final ConstructorDescriptor descriptor, @NotNull JetScope declaringScope ) { - AnnotationResolver.resolveAnnotationsArguments(constructor.getModifierList(), trace); + AnnotationResolver.resolveAnnotationsArguments(descriptor.getAnnotations()); final CallChecker callChecker = new ConstructorHeaderCallChecker(descriptor, additionalCheckerProvider.getCallChecker()); resolveFunctionBody(c, trace, constructor, descriptor, declaringScope, @@ -504,14 +504,14 @@ private void resolvePrimaryConstructorParameters(@NotNull BodiesResolveContext c JetClassOrObject klass = entry.getKey(); ClassDescriptorWithResolutionScopes classDescriptor = entry.getValue(); ConstructorDescriptor unsubstitutedPrimaryConstructor = classDescriptor.getUnsubstitutedPrimaryConstructor(); - - AnnotationResolver.resolveAnnotationsArguments(klass.getPrimaryConstructorModifierList(), trace); - if (unsubstitutedPrimaryConstructor != null) { + AnnotationResolver.resolveAnnotationsArguments(unsubstitutedPrimaryConstructor.getAnnotations()); + WritableScope parameterScope = getPrimaryConstructorParametersScope(classDescriptor.getScopeForClassHeaderResolution(), unsubstitutedPrimaryConstructor); - valueParameterResolver.resolveValueParameters(klass.getPrimaryConstructorParameters(), unsubstitutedPrimaryConstructor.getValueParameters(), - parameterScope, c.getOuterDataFlowInfo(), trace); + valueParameterResolver.resolveValueParameters(klass.getPrimaryConstructorParameters(), + unsubstitutedPrimaryConstructor.getValueParameters(), + parameterScope, c.getOuterDataFlowInfo(), trace); } } } @@ -559,7 +559,7 @@ private void resolvePropertyDeclarationBodies(@NotNull BodiesResolveContext c) { resolvePropertyDelegate(c, property, propertyDescriptor, delegateExpression, classDescriptor.getScopeForMemberDeclarationResolution(), propertyScope); } - resolveAnnotationArguments(propertyScope, property); + AnnotationResolver.resolveAnnotationsArguments(propertyDescriptor.getAnnotations()); resolvePropertyAccessors(c, property, propertyDescriptor); processed.add(property); @@ -587,7 +587,7 @@ private void resolvePropertyDeclarationBodies(@NotNull BodiesResolveContext c) { resolvePropertyDelegate(c, property, propertyDescriptor, delegateExpression, propertyScope, propertyScope); } - resolveAnnotationArguments(propertyScope, property); + AnnotationResolver.resolveAnnotationsArguments(propertyDescriptor.getAnnotations()); resolvePropertyAccessors(c, property, propertyDescriptor); } @@ -610,7 +610,7 @@ public void resolvePropertyAccessors( PropertyGetterDescriptor getterDescriptor = propertyDescriptor.getGetter(); if (getter != null && getterDescriptor != null) { JetScope accessorScope = makeScopeForPropertyAccessor(c, getter, propertyDescriptor); - resolveAnnotationArguments(accessorScope, getter); + AnnotationResolver.resolveAnnotationsArguments(getterDescriptor.getAnnotations()); resolveFunctionBody(c, fieldAccessTrackingTrace, getter, getterDescriptor, accessorScope); } @@ -618,7 +618,7 @@ public void resolvePropertyAccessors( PropertySetterDescriptor setterDescriptor = propertyDescriptor.getSetter(); if (setter != null && setterDescriptor != null) { JetScope accessorScope = makeScopeForPropertyAccessor(c, setter, propertyDescriptor); - resolveAnnotationArguments(accessorScope, setter); + AnnotationResolver.resolveAnnotationsArguments(setterDescriptor.getAnnotations()); resolveFunctionBody(c, fieldAccessTrackingTrace, setter, setterDescriptor, accessorScope); } } @@ -778,10 +778,6 @@ public void resolveConstructorParameterDefaultValuesAndAnnotations( c.getOuterDataFlowInfo(), trace); } - private void resolveAnnotationArguments(@NotNull JetScope scope, @NotNull JetModifierListOwner owner) { - AnnotationResolver.resolveAnnotationsArguments(owner.getModifierList(), trace); - } - private static void computeDeferredType(JetType type) { // handle type inference loop: function or property body contains a reference to itself // fun f() = { f() } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java index 273e7c4b80f5a..31492551d9e4a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java @@ -211,7 +211,7 @@ public DeclarationDescriptor visitJetElement(@NotNull JetElement element, Void d throw new IllegalStateException("No descriptor resolved for " + declaration + ":\n" + PsiUtilPackage.getElementTextWithContext(declaration)); } - AnnotationResolver.resolveAnnotationsArguments(result.getAnnotations(), trace); + AnnotationResolver.resolveAnnotationsArguments(result.getAnnotations()); return result; } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt index 78e512311b4f0..3075be4aa5185 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt @@ -90,7 +90,7 @@ public class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Express context.trace, context.dataFlowInfo, context.expectedType ) } - AnnotationResolver.resolveAnnotationsArguments(functionDescriptor.getAnnotations(), context.trace); + AnnotationResolver.resolveAnnotationsArguments(functionDescriptor.getAnnotations()); val functionInnerScope = FunctionDescriptorUtil.getFunctionInnerScope(context.scope, functionDescriptor, context.trace) components.expressionTypingServices.checkFunctionReturnType( @@ -167,7 +167,7 @@ public class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Express initializeFunctionDescriptorAndExplicitReturnType(context.scope.getContainingDeclaration(), context.scope, functionLiteral, functionDescriptor, context.trace, context.expectedType) for (parameterDescriptor in functionDescriptor.getValueParameters()) { - AnnotationResolver.resolveAnnotationsArguments(parameterDescriptor.getAnnotations(), context.trace) + AnnotationResolver.resolveAnnotationsArguments(parameterDescriptor.getAnnotations()) } BindingContextUtils.recordFunctionDeclarationToDescriptor(context.trace, functionLiteral, functionDescriptor) return functionDescriptor diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt index bae1179f575ea..d967702491f4b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt @@ -49,7 +49,7 @@ public class ValueParameterResolver( context: ExpressionTypingContext ) { for ((descriptor, parameter) in valueParameterDescriptors zip valueParameters) { - AnnotationResolver.resolveAnnotationsArguments(parameter.getModifierList(), context.trace) + AnnotationResolver.resolveAnnotationsArguments(descriptor.getAnnotations()) resolveDefaultValue(descriptor, parameter, context) } } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/ElementResolver.kt b/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/ElementResolver.kt index 2d93a071fa192..a8ccdd2ed2f2c 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/ElementResolver.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/ElementResolver.kt @@ -248,21 +248,21 @@ public abstract class ElementResolver protected( val modifierList = jetAnnotationEntry.getParentOfType<JetModifierList>(true) val declaration = modifierList?.getParentOfType<JetDeclaration>(true) if (declaration != null) { - doResolveAnnotations(resolveSession, getAnnotationsByDeclaration(resolveSession, modifierList!!, declaration)) + doResolveAnnotations(getAnnotationsByDeclaration(resolveSession, modifierList!!, declaration)) } else { val fileAnnotationList = jetAnnotationEntry.getParentOfType<JetFileAnnotationList>(true) if (fileAnnotationList != null) { - doResolveAnnotations(resolveSession, resolveSession.getFileAnnotations(fileAnnotationList.getContainingJetFile())) + doResolveAnnotations(resolveSession.getFileAnnotations(fileAnnotationList.getContainingJetFile())) } if (modifierList != null && modifierList.getParent() is JetFile) { - doResolveAnnotations(resolveSession, resolveSession.getDanglingAnnotations(modifierList.getContainingJetFile())) + doResolveAnnotations(resolveSession.getDanglingAnnotations(modifierList.getContainingJetFile())) } } } - private fun doResolveAnnotations(resolveSession: ResolveSession, annotations: Annotations) { - AnnotationResolver.resolveAnnotationsArguments(annotations, resolveSession.getTrace()) + private fun doResolveAnnotations(annotations: Annotations) { + AnnotationResolver.resolveAnnotationsArguments(annotations) ForceResolveUtil.forceResolveAllContents(annotations) }
da05ac3adba1223fadc8f898559a5ebd045f6f3e
Vala
gtk+-2.0: set default values for Gtk.Box.pack_start and end arguments
a
https://github.com/GNOME/vala/
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi index 83904e0a23..5557352af1 100644 --- a/vapi/gtk+-2.0.vapi +++ b/vapi/gtk+-2.0.vapi @@ -401,8 +401,8 @@ namespace Gtk { public weak GLib.List<Gtk.Widget> children; public bool get_homogeneous (); public int get_spacing (); - public void pack_end (Gtk.Widget child, bool expand, bool fill, uint padding); - public void pack_start (Gtk.Widget child, bool expand, bool fill, uint padding); + public void pack_end (Gtk.Widget child, bool expand = true, bool fill = true, uint padding = 0); + public void pack_start (Gtk.Widget child, bool expand = true, bool fill = true, uint padding = 0); public void query_child_packing (Gtk.Widget child, out bool expand, out bool fill, out uint padding, out Gtk.PackType pack_type); public void reorder_child (Gtk.Widget child, int position); public void set_child_packing (Gtk.Widget child, bool expand, bool fill, uint padding, Gtk.PackType pack_type); diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata index 93acd5a19b..02b1f793e3 100644 --- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata +++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata @@ -57,6 +57,12 @@ GtkBindingSet.widget_class_pspecs hidden="1" GtkBindingSet.widget_path_pspecs hidden="1" GtkBorder is_value_type="1" GtkBox.children type_arguments="Widget" +gtk_box_pack_start.expand default_value="true" +gtk_box_pack_start.fill default_value="true" +gtk_box_pack_start.padding default_value="0" +gtk_box_pack_end.expand default_value="true" +gtk_box_pack_end.fill default_value="true" +gtk_box_pack_end.padding default_value="0" gtk_box_query_child_packing.expand is_out="1" gtk_box_query_child_packing.fill is_out="1" gtk_box_query_child_packing.padding is_out="1"
bfad7226bf99c488f5e5063a44cc4a5282c9344d
orientdb
Fixed issue on set password for OUser.--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java index 19b54223d12..248ca2b419d 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java @@ -148,10 +148,10 @@ public String getPassword() { } public OUser setPassword(final String iPassword) { - return setPasswordEncoded(encryptPassword(iPassword)); + return setPasswordEncoded(iPassword); } - public OUser setPasswordEncoded(String iPassword) { + public OUser setPasswordEncoded(final String iPassword) { document.field("password", iPassword); return this; } @@ -164,7 +164,7 @@ public STATUSES getAccountStatus() { return STATUSES.valueOf((String) document.field("status")); } - public void setAccountStatus(STATUSES accountStatus) { + public void setAccountStatus(final STATUSES accountStatus) { document.field("status", accountStatus); }
9b803ed1532623edbeb8e3b82c5ed03a0d3091cc
Valadoc
gtkdoc-importer: Add support for abbrev
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index bec1d065d0..c3f24c5b6f 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -1412,6 +1412,8 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { while (current.type != TokenType.EOF) { if (current.type == TokenType.XML_OPEN && current.content == "firstterm") { append_inline_content_not_null (run, parse_highlighted_template ("firstterm", Run.Style.ITALIC)); + } else if (current.type == TokenType.XML_OPEN && current.content == "abbrev") { + append_inline_content_not_null (run, parse_highlighted_template ("abbrev", Run.Style.ITALIC)); } else if (current.type == TokenType.XML_OPEN && current.content == "term") { append_inline_content_not_null (run, parse_highlighted_template ("term", Run.Style.ITALIC)); } else if (current.type == TokenType.XML_OPEN && current.content == "literal") {
f06af44932d31d1a787425f853f142c98d74f143
hbase
HBASE-9095. AssignmentManager's handleRegion- should respect the single threaded nature of the processing--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1510799 13f79535-47bb-0310-9956-ffa450edef68-
c
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 df8c6090f30b..dc2c0e43ed01 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 @@ -159,6 +159,17 @@ public class AssignmentManager extends ZooKeeperListener { private final ExecutorService executorService; + // For unit tests, keep track of calls to ClosedRegionHandler + private Map<HRegionInfo, AtomicBoolean> closedRegionHandlerCalled = + new HashMap<HRegionInfo, AtomicBoolean>(); + + // For unit tests, keep track of calls to OpenedRegionHandler + private Map<HRegionInfo, AtomicBoolean> openedRegionHandlerCalled = + new HashMap<HRegionInfo, AtomicBoolean>(); + + // For unit tests, keep track of calls to SplitRegionHandler + private AtomicBoolean splitRegionHandlerCalled = new AtomicBoolean(false); + //Thread pool executor service for timeout monitor private java.util.concurrent.ExecutorService threadPoolExecutorService; @@ -836,8 +847,8 @@ private void handleRegion(final RegionTransition rt, int expectedVersion) { break; } // Run handler to do the rest of the SPLIT handling. - this.executorService.submit(new SplitRegionHandler(server, this, - regionState.getRegion(), sn, daughters)); + new SplitRegionHandler(server, this, regionState.getRegion(), sn, daughters).process(); + splitRegionHandlerCalled.set(true); break; case RS_ZK_REGION_MERGING: @@ -872,8 +883,7 @@ private void handleRegion(final RegionTransition rt, int expectedVersion) { + merge_a + ", rs_b=" + merge_b); } // Run handler to do the rest of the MERGED handling. - this.executorService.submit(new MergedRegionHandler( - server, this, sn, mergeRegions)); + new MergedRegionHandler(server, this, sn, mergeRegions).process(); break; case M_ZK_REGION_CLOSING: @@ -907,8 +917,8 @@ private void handleRegion(final RegionTransition rt, int expectedVersion) { regionState = regionStates.updateRegionState(rt, RegionState.State.CLOSED); if (regionState != null) { removeClosedRegion(regionState.getRegion()); - this.executorService.submit(new ClosedRegionHandler(server, - this, regionState.getRegion())); + new ClosedRegionHandler(server, this, regionState.getRegion()).process(); + closedRegionHandlerCalled.put(regionState.getRegion(), new AtomicBoolean(true)); } break; @@ -941,8 +951,7 @@ private void handleRegion(final RegionTransition rt, int expectedVersion) { // When there are more than one region server a new RS is selected as the // destination and the same is updated in the regionplan. (HBASE-5546) getRegionPlan(regionState.getRegion(), sn, true); - this.executorService.submit(new ClosedRegionHandler(server, - this, regionState.getRegion())); + new ClosedRegionHandler(server, this, regionState.getRegion()).process(); } } break; @@ -980,8 +989,9 @@ private void handleRegion(final RegionTransition rt, int expectedVersion) { regionState = regionStates.updateRegionState(rt, RegionState.State.OPEN); if (regionState != null) { failedOpenTracker.remove(encodedName); // reset the count, if any - this.executorService.submit(new OpenedRegionHandler( - server, this, regionState.getRegion(), sn, expectedVersion)); + new OpenedRegionHandler( + server, this, regionState.getRegion(), sn, expectedVersion).process(); + openedRegionHandlerCalled.put(regionState.getRegion(), new AtomicBoolean(true)); } break; @@ -993,6 +1003,32 @@ private void handleRegion(final RegionTransition rt, int expectedVersion) { } } + //For unit tests only + boolean wasClosedHandlerCalled(HRegionInfo hri) { + AtomicBoolean b = closedRegionHandlerCalled.get(hri); + //compareAndSet to be sure that unit tests don't see stale values. Means, + //we will return true exactly once unless the handler code resets to true + //this value. + return b == null ? false : b.compareAndSet(true, false); + } + + //For unit tests only + boolean wasOpenedHandlerCalled(HRegionInfo hri) { + AtomicBoolean b = openedRegionHandlerCalled.get(hri); + //compareAndSet to be sure that unit tests don't see stale values. Means, + //we will return true exactly once unless the handler code resets to true + //this value. + return b == null ? false : b.compareAndSet(true, false); + } + + //For unit tests only + boolean wasSplitHandlerCalled() { + //compareAndSet to be sure that unit tests don't see stale values. Means, + //we will return true exactly once unless the handler code resets to true + //this value. + return splitRegionHandlerCalled.compareAndSet(true, false); + } + /** * @return Returns true if this RegionState is splittable; i.e. the * RegionState is currently in splitting state or pending_close or diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestMaster.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestMaster.java index eb4f2c915215..04c5e5552982 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestMaster.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestMaster.java @@ -24,16 +24,11 @@ import org.apache.hadoop.hbase.catalog.MetaReader; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; -import org.apache.hadoop.hbase.executor.EventHandler; -import org.apache.hadoop.hbase.executor.EventHandler.EventHandlerListener; -import org.apache.hadoop.hbase.executor.EventType; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import java.io.IOException; import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -86,35 +81,27 @@ public void testMasterOpsWhileSplitting() throws Exception { tableRegions.get(0).getFirst().getEndKey()); // Now trigger a split and stop when the split is in progress - CountDownLatch split = new CountDownLatch(1); - CountDownLatch proceed = new CountDownLatch(1); - RegionSplitListener list = new RegionSplitListener(split, proceed); - cluster.getMaster().executorService. - registerListener(EventType.RS_ZK_REGION_SPLIT, list); - LOG.info("Splitting table"); TEST_UTIL.getHBaseAdmin().split(TABLENAME); LOG.info("Waiting for split result to be about to open"); - split.await(60, TimeUnit.SECONDS); - try { - LOG.info("Making sure we can call getTableRegions while opening"); - tableRegions = MetaReader.getTableRegionsAndLocations(m.getCatalogTracker(), + while (!m.assignmentManager.wasSplitHandlerCalled()) { + Thread.sleep(100); + } + LOG.info("Making sure we can call getTableRegions while opening"); + tableRegions = MetaReader.getTableRegionsAndLocations(m.getCatalogTracker(), TABLENAME, false); - LOG.info("Regions: " + Joiner.on(',').join(tableRegions)); - // We have three regions because one is split-in-progress - assertEquals(3, tableRegions.size()); - LOG.info("Making sure we can call getTableRegionClosest while opening"); - Pair<HRegionInfo, ServerName> pair = + LOG.info("Regions: " + Joiner.on(',').join(tableRegions)); + // We have three regions because one is split-in-progress + assertEquals(3, tableRegions.size()); + LOG.info("Making sure we can call getTableRegionClosest while opening"); + Pair<HRegionInfo, ServerName> pair = m.getTableRegionForRow(TABLENAME, Bytes.toBytes("cde")); - LOG.info("Result is: " + pair); - Pair<HRegionInfo, ServerName> tableRegionFromName = + LOG.info("Result is: " + pair); + Pair<HRegionInfo, ServerName> tableRegionFromName = MetaReader.getRegion(m.getCatalogTracker(), pair.getFirst().getRegionName()); - assertEquals(tableRegionFromName.getFirst(), pair.getFirst()); - } finally { - proceed.countDown(); - } + assertEquals(tableRegionFromName.getFirst(), pair.getFirst()); } @Test @@ -175,33 +162,5 @@ public void testMoveThrowsPleaseHoldException() throws IOException { TEST_UTIL.deleteTable(tableName); } } - - static class RegionSplitListener implements EventHandlerListener { - CountDownLatch split, proceed; - - public RegionSplitListener(CountDownLatch split, CountDownLatch proceed) { - this.split = split; - this.proceed = proceed; - } - - @Override - public void afterProcess(EventHandler event) { - if (event.getEventType() != EventType.RS_ZK_REGION_SPLIT) { - return; - } - try { - split.countDown(); - proceed.await(60, TimeUnit.SECONDS); - } catch (InterruptedException ie) { - throw new RuntimeException(ie); - } - return; - } - - @Override - public void beforeProcess(EventHandler event) { - } - } - } diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java index 6902b2543c5f..d7532165310a 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.util.Collection; -import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -43,10 +42,6 @@ import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Durability; -import org.apache.hadoop.hbase.executor.EventHandler; -import org.apache.hadoop.hbase.executor.EventHandler.EventHandlerListener; -import org.apache.hadoop.hbase.executor.EventType; -import org.apache.hadoop.hbase.master.handler.TotesHRegionInfo; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.util.Bytes; @@ -116,29 +111,14 @@ public class TestZKBasedOpenCloseRegion { HRegionInfo hri = getNonMetaRegion(ProtobufUtil.getOnlineRegions(regionServer)); LOG.debug("Asking RS to close region " + hri.getRegionNameAsString()); - AtomicBoolean closeEventProcessed = new AtomicBoolean(false); - AtomicBoolean reopenEventProcessed = new AtomicBoolean(false); - - EventHandlerListener closeListener = - new ReopenEventListener(hri.getRegionNameAsString(), - closeEventProcessed, EventType.RS_ZK_REGION_CLOSED); - cluster.getMaster().executorService. - registerListener(EventType.RS_ZK_REGION_CLOSED, closeListener); - - EventHandlerListener openListener = - new ReopenEventListener(hri.getRegionNameAsString(), - reopenEventProcessed, EventType.RS_ZK_REGION_OPENED); - cluster.getMaster().executorService. - registerListener(EventType.RS_ZK_REGION_OPENED, openListener); - LOG.info("Unassign " + hri.getRegionNameAsString()); cluster.getMaster().assignmentManager.unassign(hri); - while (!closeEventProcessed.get()) { + while (!cluster.getMaster().assignmentManager.wasClosedHandlerCalled(hri)) { Threads.sleep(100); } - while (!reopenEventProcessed.get()) { + while (!cluster.getMaster().assignmentManager.wasOpenedHandlerCalled(hri)) { Threads.sleep(100); } @@ -157,83 +137,6 @@ private HRegionInfo getNonMetaRegion(final Collection<HRegionInfo> regions) { return hri; } - public static class ReopenEventListener implements EventHandlerListener { - private static final Log LOG = LogFactory.getLog(ReopenEventListener.class); - String regionName; - AtomicBoolean eventProcessed; - EventType eventType; - - public ReopenEventListener(String regionName, - AtomicBoolean eventProcessed, EventType eventType) { - this.regionName = regionName; - this.eventProcessed = eventProcessed; - this.eventType = eventType; - } - - @Override - public void beforeProcess(EventHandler event) { - if(event.getEventType() == eventType) { - LOG.info("Received " + eventType + " and beginning to process it"); - } - } - - @Override - public void afterProcess(EventHandler event) { - LOG.info("afterProcess(" + event + ")"); - if(event.getEventType() == eventType) { - LOG.info("Finished processing " + eventType); - String regionName = ""; - if(eventType == EventType.RS_ZK_REGION_OPENED) { - TotesHRegionInfo hriCarrier = (TotesHRegionInfo)event; - regionName = hriCarrier.getHRegionInfo().getRegionNameAsString(); - } else if(eventType == EventType.RS_ZK_REGION_CLOSED) { - TotesHRegionInfo hriCarrier = (TotesHRegionInfo)event; - regionName = hriCarrier.getHRegionInfo().getRegionNameAsString(); - } - if(this.regionName.equals(regionName)) { - eventProcessed.set(true); - } - synchronized(eventProcessed) { - eventProcessed.notifyAll(); - } - } - } - } - - public static class CloseRegionEventListener implements EventHandlerListener { - private static final Log LOG = LogFactory.getLog(CloseRegionEventListener.class); - String regionToClose; - AtomicBoolean closeEventProcessed; - - public CloseRegionEventListener(String regionToClose, - AtomicBoolean closeEventProcessed) { - this.regionToClose = regionToClose; - this.closeEventProcessed = closeEventProcessed; - } - - @Override - public void afterProcess(EventHandler event) { - LOG.info("afterProcess(" + event + ")"); - if(event.getEventType() == EventType.RS_ZK_REGION_CLOSED) { - LOG.info("Finished processing CLOSE REGION"); - TotesHRegionInfo hriCarrier = (TotesHRegionInfo)event; - if (regionToClose.equals(hriCarrier.getHRegionInfo().getRegionNameAsString())) { - LOG.info("Setting closeEventProcessed flag"); - closeEventProcessed.set(true); - } else { - LOG.info("Region to close didn't match"); - } - } - } - - @Override - public void beforeProcess(EventHandler event) { - if(event.getEventType() == EventType.M_RS_CLOSE_REGION) { - LOG.info("Received CLOSE RPC and beginning to process it"); - } - } - } - /** * This test shows how a region won't be able to be assigned to a RS * if it's already "processing" it. @@ -253,13 +156,6 @@ public void testRSAlreadyProcessingRegion() throws Exception { // fake that hr1 is processing the region hr1.getRegionsInTransitionInRS().putIfAbsent(hri.getEncodedNameAsBytes(), true); - AtomicBoolean reopenEventProcessed = new AtomicBoolean(false); - EventHandlerListener openListener = - new ReopenEventListener(hri.getRegionNameAsString(), - reopenEventProcessed, EventType.RS_ZK_REGION_OPENED); - cluster.getMaster().executorService. - registerListener(EventType.RS_ZK_REGION_OPENED, openListener); - // now ask the master to move the region to hr1, will fail TEST_UTIL.getHBaseAdmin().move(hri.getEncodedNameAsBytes(), Bytes.toBytes(hr1.getServerName().toString())); @@ -269,22 +165,14 @@ public void testRSAlreadyProcessingRegion() throws Exception { // remove the block and reset the boolean hr1.getRegionsInTransitionInRS().remove(hri.getEncodedNameAsBytes()); - reopenEventProcessed.set(false); // now try moving a region when there is no region in transition. hri = getNonMetaRegion(ProtobufUtil.getOnlineRegions(hr1)); - openListener = - new ReopenEventListener(hri.getRegionNameAsString(), - reopenEventProcessed, EventType.RS_ZK_REGION_OPENED); - - cluster.getMaster().executorService. - registerListener(EventType.RS_ZK_REGION_OPENED, openListener); - TEST_UTIL.getHBaseAdmin().move(hri.getEncodedNameAsBytes(), Bytes.toBytes(hr0.getServerName().toString())); - while (!reopenEventProcessed.get()) { + while (!cluster.getMaster().assignmentManager.wasOpenedHandlerCalled(hri)) { Threads.sleep(100); } @@ -304,15 +192,9 @@ public void testRSAlreadyProcessingRegion() throws Exception { HRegionInfo hri = getNonMetaRegion(ProtobufUtil.getOnlineRegions(regionServer)); LOG.debug("Asking RS to close region " + hri.getRegionNameAsString()); - AtomicBoolean closeEventProcessed = new AtomicBoolean(false); - EventHandlerListener listener = - new CloseRegionEventListener(hri.getRegionNameAsString(), - closeEventProcessed); - cluster.getMaster().executorService.registerListener(EventType.RS_ZK_REGION_CLOSED, listener); - cluster.getMaster().assignmentManager.unassign(hri); - while (!closeEventProcessed.get()) { + while (!cluster.getMaster().assignmentManager.wasClosedHandlerCalled(hri)) { Threads.sleep(100); } LOG.info("Done with testCloseRegion");
b2b6fb85f6257cca5f28ad34b9a88ca660a9f0d9
aeshell$aesh
Introduce a cleaner lower level API with the Console interface. It provides a signal api, access to the underlying terminal capabilities and stty settings. It also brings support for virtual consoles when using remote connections for example. It�s not much leveraged in the remaining of the code. Things like cursor movements, etc.. should leverage this information. The AeshInputStream hacks for transforming windows arrow keys can be just removed, and it should also be noted that the AeshInputStream does not correctly handle the encoding of the input stream and assumes the default charset, which is always not the case, especially on windows. The only external dependency on those 3 new packages (api, impl, utils) is the LoggerUtil class. This means that this can easily be extracted as the very-low component.
a
https://github.com/aeshell/aesh
diff --git a/pom.xml b/pom.xml index 6de416fdd..d0e97931f 100644 --- a/pom.xml +++ b/pom.xml @@ -100,6 +100,13 @@ </execution> </executions> </plugin> + <plugin> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>1.8</source> + <target>1.8</target> + </configuration> + </plugin> </plugins> </build> diff --git a/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java b/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java index 403a35591..8c6df5f9f 100644 --- a/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java +++ b/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java @@ -30,9 +30,8 @@ import org.jboss.aesh.edit.ViEditMode; import org.jboss.aesh.io.FileResource; import org.jboss.aesh.io.Resource; -import org.jboss.aesh.terminal.POSIXTerminal; +import org.jboss.aesh.terminal.ShellWrapper; import org.jboss.aesh.terminal.Terminal; -import org.jboss.aesh.terminal.WindowsTerminal; import java.io.File; import java.io.InputStream; @@ -372,10 +371,7 @@ public void setStdErr(PrintStream stdErr) { @Override public Terminal getTerminal() { if(terminal == null) { - if(Config.isOSPOSIXCompatible()) - terminal = new POSIXTerminal(); - else - terminal = new WindowsTerminal(); + terminal = new ShellWrapper(this); } return terminal; diff --git a/src/main/java/org/jboss/aesh/terminal/AbstractTerminal.java b/src/main/java/org/jboss/aesh/terminal/AbstractTerminal.java deleted file mode 100644 index 86c9755a8..000000000 --- a/src/main/java/org/jboss/aesh/terminal/AbstractTerminal.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @authors tag. All rights reserved. - * See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.aesh.terminal; - -import org.jboss.aesh.console.Config; -import org.jboss.aesh.console.reader.AeshStandardStream; -import org.jboss.aesh.console.settings.Settings; -import org.jboss.aesh.util.ANSI; - -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author <a href="mailto:[email protected]">Ståle W. Pedersen</a> - */ -public abstract class AbstractTerminal implements Terminal, Shell { - - private final Logger logger; - protected Settings settings; - private boolean mainBuffer = true; - - AbstractTerminal(Logger logger) { - this.logger = logger; - } - - - /** - * Return the row position if we use a ansi terminal - * Send a terminal: '<ESC>[6n' - * and we receive the position as: '<ESC>[n;mR' - * where n = current row and m = current column - */ - @Override - public CursorPosition getCursor() { - if(settings.isAnsiConsole() && Config.isOSPOSIXCompatible()) { - try { - StringBuilder col = new StringBuilder(4); - StringBuilder row = new StringBuilder(4); - out().print(ANSI.CURSOR_ROW); - out().flush(); - boolean gotSep = false; - //read the position - int[] input = read(); - - for(int i=2; i < input.length-1; i++) { - if(input[i] == 59) // we got a ';' which is the separator - gotSep = true; - else { - if(gotSep) - col.append((char) input[i]); - else - row.append((char) input[i]); - } - } - return new CursorPosition(Integer.parseInt(row.toString()), Integer.parseInt(col.toString())); - } - catch (Exception e) { - if(settings.isLogging()) - logger.log(Level.SEVERE, "Failed to find current row with ansi code: ",e); - return new CursorPosition(-1,-1); - } - } - return new CursorPosition(-1,-1); - } - - @Override - public void setCursor(CursorPosition position) { - if(getSize().isPositionWithinSize(position)) { - out().print(position.asAnsi()); - out().flush(); - } - } - - @Override - public void moveCursor(int rows, int columns) { - CursorPosition cp = getCursor(); - cp.move(rows, columns); - if(getSize().isPositionWithinSize(cp)) { - setCursor(cp); - } - } - - @Override - public void clear() { - out().print(ANSI.CLEAR_SCREEN); - out().flush(); - } - - @Override - public boolean isMainBuffer() { - return mainBuffer; - } - - @Override - public void enableAlternateBuffer() { - if(isMainBuffer()) { - out().print(ANSI.ALTERNATE_BUFFER); - out().flush(); - mainBuffer = false; - } - } - - @Override - public void enableMainBuffer() { - if(!isMainBuffer()) { - out().print(ANSI.MAIN_BUFFER); - out().flush(); - mainBuffer = true; - } - } - - @Override - public Shell getShell() { - return this; - } - - @Override - public AeshStandardStream in() { - return null; - } -} diff --git a/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java b/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java index 5d9535388..f6861adf4 100644 --- a/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java +++ b/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java @@ -19,7 +19,9 @@ */ package org.jboss.aesh.terminal; -import org.jboss.aesh.terminal.InfoCmp.Capability; +import org.jboss.aesh.terminal.utils.Curses; +import org.jboss.aesh.terminal.utils.InfoCmp; +import org.jboss.aesh.terminal.utils.InfoCmp.Capability; import org.jboss.aesh.util.LoggerUtil; import java.io.StringWriter; diff --git a/src/main/java/org/jboss/aesh/terminal/POSIXTerminal.java b/src/main/java/org/jboss/aesh/terminal/POSIXTerminal.java deleted file mode 100644 index b7ab7c6d5..000000000 --- a/src/main/java/org/jboss/aesh/terminal/POSIXTerminal.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @authors tag. All rights reserved. - * See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.aesh.terminal; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.jboss.aesh.console.Config; -import org.jboss.aesh.console.reader.ConsoleInputSession; -import org.jboss.aesh.console.settings.Settings; -import org.jboss.aesh.util.LoggerUtil; - -/** - * Terminal that should work on most POSIX systems - * - * @author Ståle W. Pedersen <[email protected]> - */ -public class POSIXTerminal extends AbstractTerminal { - - private TerminalSize size; - private boolean echoEnabled; - private String ttyConfig; - private String ttyProps; - private long ttyPropsLastFetched; - private boolean restored = false; - - private ConsoleInputSession input; - private PrintStream stdOut; - private PrintStream stdErr; - - private static final long TIMEOUT_PERIOD = 3000; - - private static final Logger LOGGER = LoggerUtil.getLogger(POSIXTerminal.class.getName()); - - public POSIXTerminal() { - super(LOGGER); - } - - @Override - public void init(Settings settings) { - this.settings = settings; - // save the initial tty configuration, this should work on posix and cygwin - try { - ttyConfig = stty("-g"); - - // sanity check - if ((ttyConfig.length() == 0) - || ((!ttyConfig.contains("=")) && (!ttyConfig.contains(":")))) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE, "Unrecognized stty code: "+ttyConfig); - throw new RuntimeException("Unrecognized stty code: " + ttyConfig); - } - - if(Config.isCygwin()) { - stty("-ixon -icanon min 1 intr undef -echo"); - } - else { - // set the console to be character-buffered instead of line-buffered - // -ixon will give access to ctrl-s/ctrl-q - //intr undef ctrl-c will no longer send the interrupt signal - //icrnl, translate carriage return to newline (needed when aesh is started in the background) - //susb undef, ctrl-z will no longer send the stop signal - stty("-ixon -icanon min 1 intr undef icrnl susp undef"); - - // disable character echoing - stty("-echo"); - } - echoEnabled = false; - - } - catch (IOException ioe) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE, "tty failed: ",ioe); - } - catch (InterruptedException e) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE, "failed while waiting for process to end: ",e); - e.printStackTrace(); - } - - //setting up input - //input = new AeshInputStream(settings.getInputStream()); - input = new ConsoleInputSession(settings.getInputStream()); - - this.stdOut = settings.getStdOut(); - this.stdErr = settings.getStdErr(); - size = new TerminalSize(getHeight(), getWidth()); - } - - /** - * @see org.jboss.aesh.terminal.Terminal - */ - @Override - public int[] read() throws IOException { - return input.readAll(); - } - - @Override - public boolean hasInput() { - return input.hasInput(); - } - - @Override - public TerminalSize getSize() { - if(propertiesTimedOut()) { - size.setHeight(getHeight()); - size.setWidth(getWidth()); - } - return size; - } - - private int getHeight() { - int height = 0; - try { - height = getTerminalProperty("rows"); - } - catch (Exception e) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE,"Failed to fetch terminal height: ",e); - } - //cant use height < 1 - if(height < 1) - height = 24; - - return height; - } - - private int getWidth() { - int width = 0; - try { - width = getTerminalProperty("columns"); - } - catch (Exception e) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE,"Failed to fetch terminal width: ",e); - } - //cant use with < 1 - if(width < 1) - width = 80; - - return width; - } - - /** - * @see org.jboss.aesh.terminal.Terminal - */ - @Override - public boolean isEchoEnabled() { - return echoEnabled; - } - - /** - * @see org.jboss.aesh.terminal.Terminal - */ - @Override - public void reset() throws IOException { - if(!restored) { - if (ttyConfig != null) { - try { - stty(ttyConfig); - ttyConfig = null; - restored = true; - } - catch (InterruptedException e) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE,"Failed to reset terminal: ",e); - } - } - } - } - - @Override - public void writeToInputStream(String data) { - input.writeToInput(data); - } - - @Override - public void changeOutputStream(PrintStream output) { - stdOut = output; - } - - @Override - public void close() throws IOException { - input.stop(); - } - - private boolean propertiesTimedOut() { - return (System.currentTimeMillis() -ttyPropsLastFetched) > TIMEOUT_PERIOD; - } - - private int getTerminalProperty(String prop) throws IOException, InterruptedException { - // tty properties are cached so we don't have to worry too much about getting term width/height - if (ttyProps == null || propertiesTimedOut()) { - ttyProps = stty("-a"); - ttyPropsLastFetched = System.currentTimeMillis(); - } - // need to be able handle both output formats: - // speed 9600 baud; 24 rows; 140 columns; - // and: - // speed 38400 baud; rows = 49; columns = 111; - for (String str : ttyProps.split(";")) { - str = str.trim(); - if (str.startsWith(prop)) { - int index = str.lastIndexOf(" "); - - return Integer.parseInt(str.substring(index).trim()); - } - else if (str.endsWith(prop)) { - int index = str.indexOf(" "); - - return Integer.parseInt(str.substring(0, index).trim()); - } - } - - return -1; - } - - /** - * Run stty with arguments on the active terminal - * - * @param args arguments - * @return output - * @throws IOException stream - * @throws InterruptedException stream - */ - protected static String stty(final String args) throws IOException, InterruptedException { - return exec("stty " + args + " < /dev/tty").trim(); - } - - /** - * Run a command and return the output - * - * @param cmd what to execute - * @return output - * @throws java.io.IOException stream - * @throws InterruptedException stream - */ - private static String exec(final String cmd) throws IOException, InterruptedException { - return exec(new String[] { "sh", "-c", cmd }); - } - - /** - * Run a command and return the output - * - * @param cmd the command - * @return output - * @throws IOException stream - * @throws InterruptedException stream - */ - private static String exec(final String[] cmd) throws IOException, InterruptedException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - - Process p = Runtime.getRuntime().exec(cmd); - int c; - InputStream in = null; - InputStream err = null; - OutputStream out = null; - - try { - in = p.getInputStream(); - - while ((c = in.read()) != -1) { - bout.write(c); - } - - err = p.getErrorStream(); - - while ((c = err.read()) != -1) { - bout.write(c); - } - - out = p.getOutputStream(); - - p.waitFor(); - } - finally { - try { - if(in != null) - in.close(); - if(err != null) - err.close(); - if(out != null) - out.close(); - } - catch (Exception e) { - LOGGER.log(Level.SEVERE,"Failed to close streams: ",e); - } - } - - return new String(bout.toByteArray()); - } - - @Override - public PrintStream err() { - return stdErr; - } - - @Override - public PrintStream out() { - return stdOut; - } - -} diff --git a/src/main/java/org/jboss/aesh/terminal/ShellWrapper.java b/src/main/java/org/jboss/aesh/terminal/ShellWrapper.java new file mode 100644 index 000000000..2e94b11bf --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/ShellWrapper.java @@ -0,0 +1,211 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @authors tag. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.aesh.terminal; + +import java.io.IOError; +import java.io.IOException; +import java.io.PrintStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.jboss.aesh.console.reader.AeshStandardStream; +import org.jboss.aesh.console.reader.ConsoleInputSession; +import org.jboss.aesh.console.settings.Settings; +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Console; +import org.jboss.aesh.terminal.api.Console.Signal; +import org.jboss.aesh.terminal.api.ConsoleBuilder; +import org.jboss.aesh.terminal.api.Size; +import org.jboss.aesh.terminal.utils.InfoCmp.Capability; +import org.jboss.aesh.util.LoggerUtil; + +public class ShellWrapper implements Terminal, Shell { + + private static final Logger LOGGER = LoggerUtil.getLogger(ShellWrapper.class.getName()); + + private Settings settings; + private Console console; + private PrintStream out; + private PrintStream err; + private ConsoleInputSession input; + private Attributes attributes; + + private boolean mainBuffer = true; + + public ShellWrapper(Settings settings) { + this.settings = settings; + } + + @Override + public void init(Settings settings) { + try { + console = ConsoleBuilder.builder() + .streams(settings.getInputStream(), settings.getStdOut()) + .name("Aesh console") + .build(); + attributes = console.enterRawMode(); + out = new PrintStream(console.output()); + err = settings.getStdErr(); + input = new ConsoleInputSession(console.input()); + // bridge to the current way of supporting signals + console.handle(Signal.INT, s -> input.writeToInput("\u0003")); + } catch (IOException e) { + throw new IOError(e); + } + } + + @Override + public PrintStream out() { + return out; + } + + @Override + public PrintStream err() { + return err; + } + + @Override + public TerminalSize getSize() { + Size size = console.getSize(); + return new TerminalSize(size.getHeight(), size.getWidth()); + } + + @Override + public int[] read() throws IOException { + return input.readAll(); + } + + @Override + public boolean hasInput() { + return input.hasInput(); + } + + @Override + public boolean isEchoEnabled() { + return console.echo(); + } + + @Override + public void reset() throws IOException { + console.setAttributes(attributes); + } + + @Override + public void writeToInputStream(String data) { + input.writeToInput(data); + } + + @Override + public void changeOutputStream(PrintStream output) { + out = output; + } + + @Override + public void close() throws IOException { + console.close(); + } + + @Override + public Shell getShell() { + return this; + } + + @Override + public void clear() throws IOException { + console.puts(Capability.clear_screen); + } + + @Override + public AeshStandardStream in() { + return null; + } + + @Override + public CursorPosition getCursor() { + if (console.puts(Capability.user7)) { + try { + console.flush(); + StringBuilder col = new StringBuilder(4); + StringBuilder row = new StringBuilder(4); + boolean gotSep = false; + //read the position + int[] input = read(); + + for(int i=2; i < input.length-1; i++) { + if(input[i] == 59) // we got a ';' which is the separator + gotSep = true; + else { + if(gotSep) + col.append((char) input[i]); + else + row.append((char) input[i]); + } + } + return new CursorPosition(Integer.parseInt(row.toString()), Integer.parseInt(col.toString())); + } + catch (Exception e) { + if(settings.isLogging()) + LOGGER.log(Level.SEVERE, "Failed to find current row with ansi code: ",e); + return new CursorPosition(-1,-1); + } + } + return new CursorPosition(-1,-1); + } + + @Override + public void setCursor(CursorPosition position) { + if (getSize().isPositionWithinSize(position) + && console.puts(Capability.cursor_address, + position.getRow(), + position.getColumn())) { + console.flush(); + } + } + + @Override + public void moveCursor(int rows, int columns) { + CursorPosition cp = getCursor(); + cp.move(rows, columns); + if (getSize().isPositionWithinSize(cp)) { + setCursor(cp); + } + } + + @Override + public boolean isMainBuffer() { + return mainBuffer; + } + + @Override + public void enableAlternateBuffer() { + if (isMainBuffer() && console.puts(Capability.enter_ca_mode)) { + console.flush(); + mainBuffer = false; + } + } + + @Override + public void enableMainBuffer() { + if (!isMainBuffer() && console.puts(Capability.exit_ca_mode)) { + console.flush(); + mainBuffer = false; + } + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/WindowsTerminal.java b/src/main/java/org/jboss/aesh/terminal/WindowsTerminal.java deleted file mode 100644 index 33406a26b..000000000 --- a/src/main/java/org/jboss/aesh/terminal/WindowsTerminal.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @authors tag. All rights reserved. - * See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jboss.aesh.terminal; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.fusesource.jansi.AnsiOutputStream; -import org.fusesource.jansi.WindowsAnsiOutputStream; -import org.fusesource.jansi.internal.WindowsSupport; -import org.jboss.aesh.console.reader.ConsoleInputSession; -import org.jboss.aesh.console.settings.Settings; -import org.jboss.aesh.util.LoggerUtil; - -/** - * - * @author Ståle W. Pedersen <[email protected]> - */ -public class WindowsTerminal extends AbstractTerminal { - - private PrintStream stdOut; - private PrintStream stdErr; - private TerminalSize size; - private ConsoleInputSession input; - - private long ttyPropsLastFetched; - private static long TIMEOUT_PERIOD = 2000; - - private static final Logger LOGGER = LoggerUtil.getLogger(WindowsTerminal.class.getName()); - - public WindowsTerminal() { - super(LOGGER); - } - - @Override - public void init(Settings settings) { - this.settings = settings; - //setting up reader - try { - //AnsiConsole.systemInstall(); - this.stdOut = new PrintStream( new WindowsAnsiOutputStream(settings.getStdOut()), true); - this.stdErr = new PrintStream( new WindowsAnsiOutputStream(settings.getStdErr()), true); - - } - catch (Exception ioe) { - this.stdOut = new PrintStream( new AnsiOutputStream(settings.getStdOut()), true); - this.stdErr = new PrintStream( new AnsiOutputStream(settings.getStdErr()), true); - } - - if(settings.getInputStream().equals(System.in)) { - InputStream inStream = new InputStream() { - @Override - public int read() throws IOException { - return WindowsSupport.readByte(); - } - - @Override - public int read(byte[] in) throws IOException { - byte[] tmp = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(WindowsSupport.readByte()).array(); - in[0] = tmp[0]; - return 1; - } - - public void close() { - WindowsSupport.flushConsoleInputBuffer(); - } - }; - this.input = new ConsoleInputSession(inStream); - //this.input = new ConsoleInputSession(inStream).getExternalInputStream(); - } - else { - this.input = new ConsoleInputSession(settings.getInputStream()); - } - } - - @Override - public int[] read() throws IOException { - return input.readAll(); - } - - @Override - public boolean hasInput() { - return input.hasInput(); - } - - private int getHeight() { - int height; - height = WindowsSupport.getWindowsTerminalHeight(); - ttyPropsLastFetched = System.currentTimeMillis(); - if(height < 1) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE, "Fetched terminal height is "+height+", setting it to 24"); - height = 24; - } - return height; - } - - private int getWidth() { - int width; - width = WindowsSupport.getWindowsTerminalWidth(); - ttyPropsLastFetched = System.currentTimeMillis(); - if(width < 1) { - if(settings.isLogging()) - LOGGER.log(Level.SEVERE, "Fetched terminal width is "+width+", setting it to 80"); - width = 80; - } - return width; - } - - @Override - public TerminalSize getSize() { - if(propertiesTimedOut()) { - if(size == null) { - size = new TerminalSize(getHeight(), getWidth()); - } - else { - size.setHeight(getHeight()); - size.setWidth(getWidth()); - } - } - return size; - } - - @Override - public boolean isEchoEnabled() { - return false; - } - - @Override - public void reset() throws IOException { - } - - @Override - public void writeToInputStream(String data) { - input.writeToInput(data); - } - - @Override - public void changeOutputStream(PrintStream output) { - stdOut = output; - } - - @Override - public void close() throws IOException { - input.stop(); - } - - private boolean propertiesTimedOut() { - return (System.currentTimeMillis() -ttyPropsLastFetched) > TIMEOUT_PERIOD; - } - - @Override - public PrintStream err() { - return stdErr; - } - - @Override - public PrintStream out() { - return stdOut; - } -} - diff --git a/src/main/java/org/jboss/aesh/terminal/api/Attributes.java b/src/main/java/org/jboss/aesh/terminal/api/Attributes.java new file mode 100644 index 000000000..aa6c45e9e --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/api/Attributes.java @@ -0,0 +1,392 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.api; + +import java.util.EnumSet; + +public class Attributes { + + /** + * Control characters + */ + public enum ControlChar { + VEOF(0), + VEOL(1), + VEOL2(2), + VERASE(3), + VWERASE(4), + VKILL(5), + VREPRINT(6), + VINTR(8), + VQUIT(9), + VSUSP(10), + VDSUSP(11), + VSTART(12), + VSTOP(13), + VLNEXT(14), + VDISCARD(15), + VMIN(16), + VTIME(17), + VSTATUS(18); + + final int value; + + ControlChar(int value) { + this.value = value; + } + + } + + /** + * Input flags - software input processing + */ + public enum InputFlag { + IGNBRK (0x00000001), /* ignore BREAK condition */ + BRKINT (0x00000002), /* map BREAK to SIGINTR */ + IGNPAR (0x00000004), /* ignore (discard) parity errors */ + PARMRK (0x00000008), /* mark parity and framing errors */ + INPCK (0x00000010), /* enable checking of parity errors */ + ISTRIP (0x00000020), /* strip 8th bit off chars */ + INLCR (0x00000040), /* map NL into CR */ + IGNCR (0x00000080), /* ignore CR */ + ICRNL (0x00000100), /* map CR to NL (ala CRMOD) */ + IXON (0x00000200), /* enable output flow control */ + IXOFF (0x00000400), /* enable input flow control */ + IXANY (0x00000800), /* any char will restart after stop */ + IMAXBEL(0x00002000), /* ring bell on input queue full */ + IUTF8 (0x00004000); /* maintain state for UTF-8 VERASE */ + + final int value; + + InputFlag(int value) { + this.value = value; + } + } + + /* + * Output flags - software output processing + */ + public enum OutputFlag { + OPOST (0x00000001), /* enable following output processing */ + ONLCR (0x00000002), /* map NL to CR-NL (ala CRMOD) */ + OXTABS(0x00000004), /* expand tabs to spaces */ + ONOEOT(0x00000008), /* discard EOT's (^D) on output) */ + OCRNL (0x00000010), /* map CR to NL on output */ + ONOCR (0x00000020), /* no CR output at column 0 */ + ONLRET(0x00000040), /* NL performs CR function */ + OFILL (0x00000080), /* use fill characters for delay */ + NLDLY (0x00000300), /* \n delay */ + TABDLY(0x00000c04), /* horizontal tab delay */ + CRDLY (0x00003000), /* \r delay */ + FFDLY (0x00004000), /* form feed delay */ + BSDLY (0x00008000), /* \b delay */ + VTDLY (0x00010000), /* vertical tab delay */ + OFDEL (0x00020000); /* fill is DEL, else NUL */ + + final int value; + + OutputFlag(int value) { + this.value = value; + } + } + + /* + * Control flags - hardware control of terminal + */ + public enum ControlFlag { + CIGNORE (0x00000001), /* ignore control flags */ + CSIZE (0x00000300), /* character size mask */ + CS5 (0x00000000), /* 5 bits (pseudo) */ + CS6 (0x00000100), /* 6 bits */ + CS7 (0x00000200), /* 7 bits */ + CS8 (0x00000300), /* 8 bits */ + CSTOPB (0x00000400), /* send 2 stop bits */ + CREAD (0x00000800), /* enable receiver */ + PARENB (0x00001000), /* parity enable */ + PARODD (0x00002000), /* odd parity, else even */ + HUPCL (0x00004000), /* hang up on last close */ + CLOCAL (0x00008000), /* ignore modem status lines */ + CCTS_OFLOW (0x00010000), /* CTS flow control of output */ + CRTS_IFLOW (0x00020000), /* RTS flow control of input */ + CRTSCTS (CCTS_OFLOW.value | CRTS_IFLOW.value), + CDTR_IFLOW (0x00040000), /* DTR flow control of input */ + CDSR_OFLOW (0x00080000), /* DSR flow control of output */ + CCAR_OFLOW (0x00100000); /* DCD flow control of output */ + + final int value; + + ControlFlag(int value) { + this.value = value; + } + } + + /* + * "Local" flags - dumping ground for other state + * + * Warning: some flags in this structure begin with + * the letter "I" and look like they belong in the + * input flag. + */ + public enum LocalFlag { + ECHOKE (0x00000001), /* visual erase for line kill */ + ECHOE (0x00000002), /* visually erase chars */ + ECHOK (0x00000004), /* echo NL after line kill */ + ECHO (0x00000008), /* enable echoing */ + ECHONL (0x00000010), /* echo NL even if ECHO is off */ + ECHOPRT (0x00000020), /* visual erase mode for hardcopy */ + ECHOCTL (0x00000040), /* echo control chars as ^(Char) */ + ISIG (0x00000080), /* enable signals INTR, QUIT, [D]SUSP */ + ICANON (0x00000100), /* canonicalize input lines */ + ALTWERASE (0x00000200), /* use alternate WERASE algorithm */ + IEXTEN (0x00000400), /* enable DISCARD and LNEXT */ + EXTPROC (0x00000800), /* external processing */ + TOSTOP (0x00400000), /* stop background jobs from output */ + FLUSHO (0x00800000), /* output being flushed (state) */ + NOKERNINFO (0x02000000), /* no kernel output from VSTATUS */ + PENDIN (0x20000000), /* XXX retype pending input (state) */ + NOFLSH (0x80000000); /* don't flush after interrupt */ + + final int value; + + LocalFlag(int value) { + this.value = value; + } + } + + long c_iflag; + long c_oflag; + long c_cflag; + long c_lflag; + byte[] c_cc = new byte[20]; + + public Attributes() { + } + + public Attributes(Attributes attr) { + copy(attr); + } + + // + // Input flags + // + + public EnumSet<InputFlag> getInputFlags() { + EnumSet<InputFlag> flags = EnumSet.noneOf(InputFlag.class); + for (InputFlag flag : InputFlag.values()) { + if (getInputFlag(flag)) { + flags.add(flag); + } + } + return flags; + } + + public void setInputFlags(EnumSet<InputFlag> flags) { + int v = 0; + for (InputFlag f : flags) { + v |= f.value; + } + c_iflag = v; + } + + public boolean getInputFlag(InputFlag flag) { + return (c_iflag & flag.value) == flag.value; + } + + public void setInputFlags(EnumSet<InputFlag> flags, boolean value) { + int v = 0; + for (InputFlag f : flags) { + v |= f.value; + } + if (value) { + c_iflag |= v; + } else { + c_iflag &= ~v; + } + } + + public void setInputFlag(InputFlag flag, boolean value) { + if (value) { + c_iflag |= flag.value; + } else { + c_iflag &= ~flag.value; + } + } + + // + // Output flags + // + + public EnumSet<OutputFlag> getOutputFlags() { + EnumSet<OutputFlag> flags = EnumSet.noneOf(OutputFlag.class); + for (OutputFlag flag : OutputFlag.values()) { + if (getOutputFlag(flag)) { + flags.add(flag); + } + } + return flags; + } + + public void setOutputFlags(EnumSet<OutputFlag> flags) { + int v = 0; + for (OutputFlag f : flags) { + v |= f.value; + } + c_oflag = v; + } + + public boolean getOutputFlag(OutputFlag flag) { + return (c_oflag & flag.value) == flag.value; + } + + public void setOutputFlags(EnumSet<OutputFlag> flags, boolean value) { + int v = 0; + for (OutputFlag f : flags) { + v |= f.value; + } + if (value) { + c_oflag |= v; + } else { + c_oflag &= ~v; + } + } + + public void setOutputFlag(OutputFlag flag, boolean value) { + if (value) { + c_oflag |= flag.value; + } else { + c_oflag &= ~flag.value; + } + } + + // + // Control flags + // + + public EnumSet<ControlFlag> getControlFlags() { + EnumSet<ControlFlag> flags = EnumSet.noneOf(ControlFlag.class); + for (ControlFlag flag : ControlFlag.values()) { + if (getControlFlag(flag)) { + flags.add(flag); + } + } + return flags; + } + + public void setControlFlags(EnumSet<ControlFlag> flags) { + int v = 0; + for (ControlFlag f : flags) { + v |= f.value; + } + c_cflag = v; + } + + public boolean getControlFlag(ControlFlag flag) { + switch (flag) { + case CS5: + case CS6: + case CS7: + case CS8: + return (c_cflag & ControlFlag.CSIZE.value) == flag.value; + case CSIZE: + return false; + default: + return (c_cflag & flag.value) == flag.value; + } + } + + public void setControlFlags(EnumSet<ControlFlag> flags, boolean value) { + int v = 0; + for (ControlFlag f : flags) { + v |= f.value; + } + if (value) { + c_cflag |= v; + } else { + c_cflag &= ~v; + } + } + + public void setControlFlag(ControlFlag flag, boolean value) { + if (value) { + c_cflag |= flag.value; + } else { + c_cflag &= ~flag.value; + } + } + + // + // Local flags + // + + public EnumSet<LocalFlag> getLocalFlags() { + EnumSet<LocalFlag> flags = EnumSet.noneOf(LocalFlag.class); + for (LocalFlag flag : LocalFlag.values()) { + if (getLocalFlag(flag)) { + flags.add(flag); + } + } + return flags; + } + + public void setLocalFlags(EnumSet<LocalFlag> flags) { + int v = 0; + for (LocalFlag f : flags) { + v |= f.value; + } + c_lflag = v; + } + + public boolean getLocalFlag(LocalFlag flag) { + return (c_lflag & flag.value) == flag.value; + } + + public void setLocalFlags(EnumSet<LocalFlag> flags, boolean value) { + int v = 0; + for (LocalFlag f : flags) { + v |= f.value; + } + if (value) { + c_lflag |= v; + } else { + c_lflag &= ~v; + } + } + + public void setLocalFlag(LocalFlag flag, boolean value) { + if (value) { + c_lflag |= flag.value; + } else { + c_lflag &= ~flag.value; + } + } + + // + // Control chars + // + + public int getControlChar(ControlChar c) { + return c_cc[c.value] & 0xff; + } + + public void setControlChar(ControlChar c, int value) { + c_cc[c.value] = (byte) value; + } + + // + // Miscellaneous methods + // + + public void copy(Attributes attributes) { + System.arraycopy(attributes.c_cc, 0, c_cc, 0, c_cc.length); + c_cflag = attributes.c_cflag; + c_iflag = attributes.c_iflag; + c_lflag = attributes.c_lflag; + c_oflag = attributes.c_oflag; + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/api/Console.java b/src/main/java/org/jboss/aesh/terminal/api/Console.java new file mode 100644 index 000000000..fc263be31 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/api/Console.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.api; + +import java.io.Closeable; +import java.io.Flushable; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.Reader; + +import org.jboss.aesh.terminal.impl.NativeSignalHandler; +import org.jboss.aesh.terminal.utils.InfoCmp.Capability; + + +public interface Console extends Closeable, Flushable { + + String getName(); + + // + // Signal support + // + + enum Signal { + INT, + QUIT, + TSTP, + CONT, + INFO, + WINCH + } + + interface SignalHandler { + + SignalHandler SIG_DFL = NativeSignalHandler.SIG_DFL; + SignalHandler SIG_IGN = NativeSignalHandler.SIG_IGN; + + void handle(Signal signal); + } + + SignalHandler handle(Signal signal, SignalHandler handler); + + void raise(Signal signal); + + // + // Input / output + // + + Reader reader(); + + PrintWriter writer(); + + InputStream input(); + + OutputStream output(); + + // + // Pty settings + // + + Attributes enterRawMode(); + + boolean echo(); + + boolean echo(boolean echo); + + Attributes getAttributes(); + + void setAttributes(Attributes attr); + + Size getSize(); + + void setSize(Size size); + + default int getWidth() { + return getSize().getWidth(); + } + + default int getHeight() { + return getSize().getHeight(); + } + + void flush(); + + // + // Infocmp capabilities + // + + String getType(); + + boolean puts(Capability capability, Object... params); + + boolean getBooleanCapability(Capability capability); + + Integer getNumericCapability(Capability capability); + + String getStringCapability(Capability capability); + +} diff --git a/src/main/java/org/jboss/aesh/terminal/api/ConsoleBuilder.java b/src/main/java/org/jboss/aesh/terminal/api/ConsoleBuilder.java new file mode 100644 index 000000000..69fb0b0c4 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/api/ConsoleBuilder.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.api; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.Charset; + +import org.jboss.aesh.terminal.impl.CygwinPty; +import org.jboss.aesh.terminal.impl.ExecPty; +import org.jboss.aesh.terminal.impl.ExternalConsole; +import org.jboss.aesh.terminal.impl.PosixSysConsole; +import org.jboss.aesh.terminal.impl.Pty; +import org.jboss.aesh.terminal.impl.WinSysConsole; +import org.jboss.aesh.terminal.utils.OSUtils; + +public final class ConsoleBuilder { + + public static Console console() throws IOException { + return builder().build(); + } + + public static ConsoleBuilder builder() { + return new ConsoleBuilder(); + } + + private String name; + private InputStream in; + private OutputStream out; + private String type; + private String encoding; + private Boolean system; + private boolean nativeSignals = true; + + private ConsoleBuilder() { + } + + public ConsoleBuilder name(String name) { + this.name = name; + return this; + } + + public ConsoleBuilder streams(InputStream in, OutputStream out) { + this.in = in; + this.out = out; + return this; + } + + public ConsoleBuilder system(boolean system) { + this.system = system; + return this; + } + + public ConsoleBuilder type(String type) { + this.type = type; + return this; + } + + public ConsoleBuilder encoding(String encoding) { + this.encoding = encoding; + return this; + } + + public Console build() throws IOException { + String name = this.name; + if (name == null) { + name = "JLine console"; + } + if ((system != null && system) + || (system == null + && (in == null || in == System.in) + && (out == null || out == System.out))) { + // + // Cygwin support + // + if (OSUtils.IS_CYGWIN) { + String type = this.type; + if (type == null) { + type = System.getenv("TERM"); + } + String encoding = this.encoding; + if (encoding == null) { + encoding = Charset.defaultCharset().name(); + } + Pty pty = CygwinPty.current(); + return new PosixSysConsole(name, type, pty, encoding, nativeSignals); + } + else if (OSUtils.IS_WINDOWS) { + return new WinSysConsole(name, nativeSignals); + } else { + String type = this.type; + if (type == null) { + type = System.getenv("TERM"); + } + String encoding = this.encoding; + if (encoding == null) { + encoding = Charset.defaultCharset().name(); + } + Pty pty = ExecPty.current(); + return new PosixSysConsole(name, type, pty, encoding, nativeSignals); + } + } else { + return new ExternalConsole(name, type, in, out, encoding); + } + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/api/Size.java b/src/main/java/org/jboss/aesh/terminal/api/Size.java new file mode 100644 index 000000000..7d03395a6 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/api/Size.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.api; + +public class Size { + + private int height; + private int width; + + public Size() { + } + + public Size(int height, int width) { + this.height = height; + this.width = width; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = (short) width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = (short) height; + } + + public void copy(Size size) { + setWidth(size.getWidth()); + setHeight(size.getHeight()); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Size size = (Size) o; + + if (height != size.height) return false; + return width == size.width; + + } + + @Override + public int hashCode() { + int result = height; + result = 31 * result + width; + return result; + } + + @Override + public String toString() { + return "Size[" + + "cols=" + width + + ", rows=" + height + + ']'; + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/AbstractConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/AbstractConsole.java new file mode 100644 index 000000000..578e665ff --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/AbstractConsole.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.IOError; +import java.io.IOException; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Attributes.ControlChar; +import org.jboss.aesh.terminal.api.Attributes.InputFlag; +import org.jboss.aesh.terminal.api.Attributes.LocalFlag; +import org.jboss.aesh.terminal.api.Console; +import org.jboss.aesh.terminal.utils.Curses; +import org.jboss.aesh.terminal.utils.InfoCmp; +import org.jboss.aesh.terminal.utils.InfoCmp.Capability; +import org.jboss.aesh.util.LoggerUtil; + +public abstract class AbstractConsole implements Console { + + protected final Logger LOGGER = LoggerUtil.getLogger(getClass().getName()); + + protected final String name; + protected final String type; + protected final Map<Signal, SignalHandler> handlers = new HashMap<>(); + protected final Set<Capability> bools = new HashSet<>(); + protected final Map<Capability, Integer> ints = new HashMap<>(); + protected final Map<Capability, String> strings = new HashMap<>(); + + public AbstractConsole(String name, String type) throws IOException { + this.name = name; + this.type = type; + for (Signal signal : Signal.values()) { + handlers.put(signal, SignalHandler.SIG_DFL); + } + } + + public SignalHandler handle(Signal signal, SignalHandler handler) { + assert signal != null; + assert handler != null; + return handlers.put(signal, handler); + } + + public void raise(Signal signal) { + assert signal != null; + SignalHandler handler = handlers.get(signal); + if (handler == SignalHandler.SIG_DFL) { + handleDefaultSignal(signal); + } else if (handler != SignalHandler.SIG_IGN) { + handler.handle(signal); + } + } + + protected void handleDefaultSignal(Signal signal) { + } + + protected void echoSignal(Signal signal) { + ControlChar cc = null; + switch (signal) { + case INT: + cc = ControlChar.VINTR; + break; + case QUIT: + cc = ControlChar.VQUIT; + break; + case TSTP: + cc = ControlChar.VSUSP; + break; + } + if (cc != null) { + int vcc = getAttributes().getControlChar(cc); + if (vcc > 0 && vcc < 32) { + writer().write(new char[]{'^', (char) (vcc + '@')}, 0, 2); + } + } + } + + public Attributes enterRawMode() { + Attributes prvAttr = getAttributes(); + Attributes newAttr = new Attributes(prvAttr); + newAttr.setLocalFlags(EnumSet.of(LocalFlag.ICANON, LocalFlag.ECHO, LocalFlag.IEXTEN), false); + newAttr.setInputFlags(EnumSet.of(InputFlag.IXON, InputFlag.ICRNL, InputFlag.INLCR), false); + newAttr.setControlChar(ControlChar.VMIN, 1); + newAttr.setControlChar(ControlChar.VTIME, 0); + setAttributes(newAttr); + return prvAttr; + } + + public boolean echo() { + return getAttributes().getLocalFlag(LocalFlag.ECHO); + } + + public boolean echo(boolean echo) { + Attributes attr = getAttributes(); + boolean prev = attr.getLocalFlag(LocalFlag.ECHO); + if (prev != echo) { + attr.setLocalFlag(LocalFlag.ECHO, echo); + setAttributes(attr); + } + return prev; + } + + public String getName() { + return name; + } + + public String getType() { + return type; + } + + public void flush() { + writer().flush(); + } + + public boolean puts(Capability capability, Object... params) { + String str = getStringCapability(capability); + if (str == null) { + return false; + } + try { + Curses.tputs(writer(), str, params); + } catch (IOException e) { + throw new IOError(e); + } + return true; + } + + public boolean getBooleanCapability(Capability capability) { + return bools.contains(capability); + } + + public Integer getNumericCapability(Capability capability) { + return ints.get(capability); + } + + public String getStringCapability(Capability capability) { + return strings.get(capability); + } + + protected void parseInfoCmp() { + String capabilities = null; + if (type != null) { + try { + capabilities = InfoCmp.getInfoCmp(type); + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Unable to retrieve infocmp for type " + type, e); + } + } + if (capabilities == null) { + capabilities = InfoCmp.ANSI_CAPS; + } + InfoCmp.parseInfoCmp(capabilities, bools, ints, strings); + } + +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/AbstractPosixConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/AbstractPosixConsole.java new file mode 100644 index 000000000..9f1447e44 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/AbstractPosixConsole.java @@ -0,0 +1,61 @@ +package org.jboss.aesh.terminal.impl; + +import java.io.IOError; +import java.io.IOException; + +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Size; + +public abstract class AbstractPosixConsole extends AbstractConsole { + + protected final Pty pty; + protected final Attributes originalAttributes; + + public AbstractPosixConsole(String name, String type, Pty pty) throws IOException { + super(name, type); + assert pty != null; + this.pty = pty; + this.originalAttributes = this.pty.getAttr(); + } + + protected Pty getPty() { + return pty; + } + + public Attributes getAttributes() { + try { + return pty.getAttr(); + } catch (IOException e) { + throw new IOError(e); + } + } + + public void setAttributes(Attributes attr) { + try { + pty.setAttr(attr); + } catch (IOException e) { + throw new IOError(e); + } + } + + public Size getSize() { + try { + return pty.getSize(); + } catch (IOException e) { + throw new IOError(e); + } + } + + public void setSize(Size size) { + try { + pty.setSize(size); + } catch (IOException e) { + throw new IOError(e); + } + } + + public void close() throws IOException { + pty.setAttr(originalAttributes); + pty.close(); + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/CygwinPty.java b/src/main/java/org/jboss/aesh/terminal/impl/CygwinPty.java new file mode 100644 index 000000000..8590142fe --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/CygwinPty.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.lang.ProcessBuilder.Redirect; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Attributes.ControlChar; +import org.jboss.aesh.terminal.api.Attributes.ControlFlag; +import org.jboss.aesh.terminal.api.Attributes.InputFlag; +import org.jboss.aesh.terminal.api.Attributes.LocalFlag; +import org.jboss.aesh.terminal.api.Attributes.OutputFlag; +import org.jboss.aesh.terminal.api.Size; +import org.jboss.aesh.terminal.utils.ExecHelper; +import org.jboss.aesh.terminal.utils.OSUtils; +import org.jboss.aesh.util.LoggerUtil; + + +public class CygwinPty implements Pty { + + private static final Logger LOGGER = LoggerUtil.getLogger(CygwinPty.class.getName()); + + private final String name; + + public static Pty current() throws IOException { + try { + Process p = new ProcessBuilder(OSUtils.TTY_COMMAND) + .redirectInput(Redirect.INHERIT) + .start(); + String result = ExecHelper.waitAndCapture(p).trim(); + if (p.exitValue() != 0) { + throw new IOException("Not a tty"); + } + return new CygwinPty(result); + } catch (InterruptedException e) { + throw (IOException) new InterruptedIOException("Command interrupted").initCause(e); + } + } + + protected CygwinPty(String name) { + this.name = name; + } + + @Override + public void close() throws IOException { + } + + public String getName() { + return name; + } + + @Override + public InputStream getMasterInput() { + throw new UnsupportedOperationException(); + } + + @Override + public OutputStream getMasterOutput() { + throw new UnsupportedOperationException(); + } + + @Override + public InputStream getSlaveInput() throws IOException { + return new FileInputStream(FileDescriptor.in); + } + + @Override + public OutputStream getSlaveOutput() throws IOException { + return new FileOutputStream(FileDescriptor.out); + } + + @Override + public Attributes getAttr() throws IOException { + String cfg = doGetConfig(); + return doGetAttr(cfg); + } + + @Override + public void setAttr(Attributes attr) throws IOException { + Attributes current = getAttr(); + List<String> commands = new ArrayList<>(); + for (InputFlag flag : InputFlag.values()) { + if (attr.getInputFlag(flag) != current.getInputFlag(flag)) { + commands.add((attr.getInputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (OutputFlag flag : OutputFlag.values()) { + if (attr.getOutputFlag(flag) != current.getOutputFlag(flag)) { + commands.add((attr.getOutputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (ControlFlag flag : ControlFlag.values()) { + if (attr.getControlFlag(flag) != current.getControlFlag(flag)) { + commands.add((attr.getControlFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (LocalFlag flag : LocalFlag.values()) { + if (attr.getLocalFlag(flag) != current.getLocalFlag(flag)) { + commands.add((attr.getLocalFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + String undef = System.getProperty("os.name").toLowerCase().startsWith("hp") ? "^-" : "undef"; + for (ControlChar cchar : ControlChar.values()) { + if (attr.getControlChar(cchar) != current.getControlChar(cchar)) { + String str = ""; + int v = attr.getControlChar(cchar); + commands.add(cchar.name().toLowerCase().substring(1)); + if (cchar == ControlChar.VMIN || cchar == ControlChar.VTIME) { + commands.add(Integer.toBinaryString(v)); + } + else if (v == 0) { + commands.add(undef); + } + else { + if (v >= 128) { + v -= 128; + str += "M-"; + } + if (v < 32 || v == 127) { + v ^= 0x40; + str += "^"; + } + str += (char) v; + commands.add(str); + } + } + } + if (!commands.isEmpty()) { + commands.add(0, OSUtils.STTY_COMMAND); + exec(commands.toArray(new String[commands.size()])); + } + } + + @Override + public Size getSize() throws IOException { + String cfg = doGetConfig(); + return doGetSize(cfg); + } + + protected String doGetConfig() throws IOException { + return exec(OSUtils.STTY_COMMAND, "-a"); + } + + static Attributes doGetAttr(String cfg) throws IOException { + Attributes attributes = new Attributes(); + for (InputFlag flag : InputFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setInputFlag(flag, value); + } + } + for (OutputFlag flag : OutputFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setOutputFlag(flag, value); + } + } + for (ControlFlag flag : ControlFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setControlFlag(flag, value); + } + } + for (LocalFlag flag : LocalFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setLocalFlag(flag, value); + } + } + for (ControlChar cchar : ControlChar.values()) { + String name = cchar.name().toLowerCase().substring(1); + if ("reprint".endsWith(name)) { + name = "(?:reprint|rprnt)"; + } + Matcher matcher = Pattern.compile("[\\s;]" + name + "\\s*=\\s*(.+?)[\\s;]").matcher(cfg); + if (matcher.find()) { + attributes.setControlChar(cchar, parseControlChar(matcher.group(1).toUpperCase())); + } + } + return attributes; + } + + private static Boolean doGetFlag(String cfg, Enum<?> flag) { + Matcher matcher = Pattern.compile("(?:^|[\\s;])(\\-?" + flag.name().toLowerCase() + ")(?:[\\s;]|$)").matcher(cfg); + return matcher.find() ? !matcher.group(1).startsWith("-") : null; + } + + static int parseControlChar(String str) { + // undef + if ("<UNDEF>".equals(str)) { + return -1; + } + // del + if ("DEL".equalsIgnoreCase(str)) { + return 127; + } + // octal + if (str.charAt(0) == '0') { + return Integer.parseInt(str, 8); + } + // decimal + if (str.charAt(0) >= '1' && str.charAt(0) <= '9') { + return Integer.parseInt(str, 10); + } + // control char + if (str.charAt(0) == '^') { + if (str.charAt(1) == '?') { + return 127; + } else { + return str.charAt(1) - 64; + } + } else if (str.charAt(0) == 'M' && str.charAt(1) == '-') { + if (str.charAt(2) == '^') { + if (str.charAt(3) == '?') { + return 127 + 128; + } else { + return str.charAt(3) - 64 + 128; + } + } else { + return str.charAt(2) + 128; + } + } else { + return str.charAt(0); + } + } + + static Size doGetSize(String cfg) throws IOException { + return new Size(doGetInt("rows", cfg), doGetInt("columns", cfg)); + } + + static int doGetInt(String name, String cfg) throws IOException { + String[] patterns = new String[] { + "\\b([0-9]+)\\s+" + name + "\\b", + "\\b" + name + "\\s+([0-9]+)\\b", + "\\b" + name + "\\s*=\\s*([0-9]+)\\b" + }; + for (String pattern : patterns) { + Matcher matcher = Pattern.compile(pattern).matcher(cfg); + if (matcher.find()) { + return Integer.parseInt(matcher.group(1)); + } + } + throw new IOException("Unable to parse " + name); + } + + @Override + public void setSize(Size size) throws IOException { + exec(OSUtils.STTY_COMMAND, + "rows", Integer.toString(size.getHeight()), + "columns", Integer.toString(size.getWidth())); + } + + private static String exec(final String... cmd) throws IOException { + assert cmd != null; + try { + LOGGER.log(Level.FINEST, "Running: ", cmd); + Process p = new ProcessBuilder(cmd).redirectInput(Redirect.INHERIT).start(); + String result = ExecHelper.waitAndCapture(p); + LOGGER.log(Level.FINEST, "Result: ", result); + if (p.exitValue() != 0) { + throw new IOException("Error executing '" + String.join(" ", cmd) + "': " + result); + } + return result; + } catch (InterruptedException e) { + throw (IOException) new InterruptedIOException("Command interrupted").initCause(e); + } + } + +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/ExecPty.java b/src/main/java/org/jboss/aesh/terminal/impl/ExecPty.java new file mode 100644 index 000000000..0f44f41e9 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/ExecPty.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.lang.ProcessBuilder.Redirect; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Attributes.ControlChar; +import org.jboss.aesh.terminal.api.Attributes.ControlFlag; +import org.jboss.aesh.terminal.api.Attributes.InputFlag; +import org.jboss.aesh.terminal.api.Attributes.LocalFlag; +import org.jboss.aesh.terminal.api.Attributes.OutputFlag; +import org.jboss.aesh.terminal.api.Size; +import org.jboss.aesh.terminal.utils.ExecHelper; +import org.jboss.aesh.terminal.utils.OSUtils; +import org.jboss.aesh.util.LoggerUtil; + + +public class ExecPty implements Pty { + + private static final Logger LOGGER = LoggerUtil.getLogger(CygwinPty.class.getName()); + + private final String name; + + public static Pty current() throws IOException { + try { + Process p = new ProcessBuilder(OSUtils.TTY_COMMAND) + .redirectInput(Redirect.INHERIT) + .start(); + String result = ExecHelper.waitAndCapture(p).trim(); + if (p.exitValue() != 0) { + throw new IOException("Not a tty"); + } + return new ExecPty(result); + } catch (InterruptedException e) { + throw (IOException) new InterruptedIOException("Command interrupted").initCause(e); + } + } + + protected ExecPty(String name) { + this.name = name; + } + + @Override + public void close() throws IOException { + } + + public String getName() { + return name; + } + + @Override + public InputStream getMasterInput() { + throw new UnsupportedOperationException(); + } + + @Override + public OutputStream getMasterOutput() { + throw new UnsupportedOperationException(); + } + + @Override + public InputStream getSlaveInput() throws IOException { + return new FileInputStream(getName()); + } + + @Override + public OutputStream getSlaveOutput() throws IOException { + return new FileOutputStream(getName()); + } + + @Override + public Attributes getAttr() throws IOException { + String cfg = doGetConfig(); + return doGetAttr(cfg); + } + + @Override + public void setAttr(Attributes attr) throws IOException { + Attributes current = getAttr(); + List<String> commands = new ArrayList<>(); + for (InputFlag flag : InputFlag.values()) { + if (attr.getInputFlag(flag) != current.getInputFlag(flag)) { + commands.add((attr.getInputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (OutputFlag flag : OutputFlag.values()) { + if (attr.getOutputFlag(flag) != current.getOutputFlag(flag)) { + commands.add((attr.getOutputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (ControlFlag flag : ControlFlag.values()) { + if (attr.getControlFlag(flag) != current.getControlFlag(flag)) { + commands.add((attr.getControlFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (LocalFlag flag : LocalFlag.values()) { + if (attr.getLocalFlag(flag) != current.getLocalFlag(flag)) { + commands.add((attr.getLocalFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + String undef = System.getProperty("os.name").toLowerCase().startsWith("hp") ? "^-" : "undef"; + for (ControlChar cchar : ControlChar.values()) { + if (attr.getControlChar(cchar) != current.getControlChar(cchar)) { + String str = ""; + int v = attr.getControlChar(cchar); + commands.add(cchar.name().toLowerCase().substring(1)); + if (cchar == ControlChar.VMIN || cchar == ControlChar.VTIME) { + commands.add(Integer.toBinaryString(v)); + } + else if (v == 0) { + commands.add(undef); + } + else { + if (v >= 128) { + v -= 128; + str += "M-"; + } + if (v < 32 || v == 127) { + v ^= 0x40; + str += "^"; + } + str += (char) v; + commands.add(str); + } + } + } + if (!commands.isEmpty()) { + commands.add(0, OSUtils.STTY_COMMAND); + commands.add(1, "-f"); + commands.add(2, getName()); + exec(commands.toArray(new String[commands.size()])); + } + } + + @Override + public Size getSize() throws IOException { + String cfg = doGetConfig(); + return doGetSize(cfg); + } + + protected String doGetConfig() throws IOException { + return exec(OSUtils.STTY_COMMAND, "-f", getName(), "-a"); + } + + static Attributes doGetAttr(String cfg) throws IOException { + Attributes attributes = new Attributes(); + for (InputFlag flag : InputFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setInputFlag(flag, value); + } + } + for (OutputFlag flag : OutputFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setOutputFlag(flag, value); + } + } + for (ControlFlag flag : ControlFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setControlFlag(flag, value); + } + } + for (LocalFlag flag : LocalFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setLocalFlag(flag, value); + } + } + for (ControlChar cchar : ControlChar.values()) { + String name = cchar.name().toLowerCase().substring(1); + if ("reprint".endsWith(name)) { + name = "(?:reprint|rprnt)"; + } + Matcher matcher = Pattern.compile("[\\s;]" + name + "\\s*=\\s*(.+?)[\\s;]").matcher(cfg); + if (matcher.find()) { + attributes.setControlChar(cchar, parseControlChar(matcher.group(1).toUpperCase())); + } + } + return attributes; + } + + private static Boolean doGetFlag(String cfg, Enum<?> flag) { + Matcher matcher = Pattern.compile("(?:^|[\\s;])(\\-?" + flag.name().toLowerCase() + ")(?:[\\s;]|$)").matcher(cfg); + return matcher.find() ? !matcher.group(1).startsWith("-") : null; + } + + static int parseControlChar(String str) { + // undef + if ("<UNDEF>".equals(str)) { + return -1; + } + // del + if ("DEL".equalsIgnoreCase(str)) { + return 127; + } + // octal + if (str.charAt(0) == '0') { + return Integer.parseInt(str, 8); + } + // decimal + if (str.charAt(0) >= '1' && str.charAt(0) <= '9') { + return Integer.parseInt(str, 10); + } + // control char + if (str.charAt(0) == '^') { + if (str.charAt(1) == '?') { + return 127; + } else { + return str.charAt(1) - 64; + } + } else if (str.charAt(0) == 'M' && str.charAt(1) == '-') { + if (str.charAt(2) == '^') { + if (str.charAt(3) == '?') { + return 127 + 128; + } else { + return str.charAt(3) - 64 + 128; + } + } else { + return str.charAt(2) + 128; + } + } else { + return str.charAt(0); + } + } + + static Size doGetSize(String cfg) throws IOException { + return new Size(doGetInt("rows", cfg), doGetInt("columns", cfg)); + } + + static int doGetInt(String name, String cfg) throws IOException { + String[] patterns = new String[] { + "\\b([0-9]+)\\s+" + name + "\\b", + "\\b" + name + "\\s+([0-9]+)\\b", + "\\b" + name + "\\s*=\\s*([0-9]+)\\b" + }; + for (String pattern : patterns) { + Matcher matcher = Pattern.compile(pattern).matcher(cfg); + if (matcher.find()) { + return Integer.parseInt(matcher.group(1)); + } + } + throw new IOException("Unable to parse " + name); + } + + @Override + public void setSize(Size size) throws IOException { + exec(OSUtils.STTY_COMMAND, + "-f", getName(), + "rows", Integer.toString(size.getHeight()), + "columns", Integer.toString(size.getWidth())); + } + + private static String exec(final String... cmd) throws IOException { + assert cmd != null; + try { + LOGGER.log(Level.FINEST, "Running: ", cmd); + Process p = new ProcessBuilder(cmd).start(); + String result = ExecHelper.waitAndCapture(p); + LOGGER.log(Level.FINEST, "Result: ", result); + if (p.exitValue() != 0) { + throw new IOException("Error executing '" + String.join(" ", cmd) + "': " + result); + } + return result; + } catch (InterruptedException e) { + throw (IOException) new InterruptedIOException("Command interrupted").initCause(e); + } + } + +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/ExternalConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/ExternalConsole.java new file mode 100644 index 000000000..c07a89b02 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/ExternalConsole.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Console implementation with embedded line disciplined. + * + * This console is well-suited for supporting incoming external + * connections, such as from the network (through telnet, ssh, + * or any kind of protocol). + * The console will start consuming the input in a separate thread + * to generate interruption events. + * + * @see LineDisciplineConsole + */ +public class ExternalConsole extends LineDisciplineConsole { + + private final AtomicBoolean closed = new AtomicBoolean(); + private final Thread pumpThread; + protected final InputStream masterInput; + + public ExternalConsole(String name, String type, + InputStream masterInput, OutputStream masterOutput, + String encoding) throws IOException { + super(name, type, masterOutput, encoding); + this.masterInput = masterInput; + this.pumpThread = new Thread(this::pump, toString() + " input pump thread"); + this.pumpThread.start(); + } + + public void close() throws IOException { + if (closed.compareAndSet(false, true)) { + pumpThread.interrupt(); + super.close(); + } + } + + public void pump() { + try { + while (true) { + int c = masterInput.read(); + if (c < 0 || closed.get()) { + break; + } + processInputByte((char) c); + } + } catch (IOException e) { + try { + close(); + } catch (Throwable t) { + e.addSuppressed(t); + } + // TODO: log + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/LineDisciplineConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/LineDisciplineConsole.java new file mode 100644 index 000000000..77d55e561 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/LineDisciplineConsole.java @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintWriter; +import java.io.Reader; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharsetDecoder; +import java.util.function.IntConsumer; + +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Attributes.ControlChar; +import org.jboss.aesh.terminal.api.Attributes.InputFlag; +import org.jboss.aesh.terminal.api.Attributes.LocalFlag; +import org.jboss.aesh.terminal.api.Attributes.OutputFlag; +import org.jboss.aesh.terminal.api.Console; +import org.jboss.aesh.terminal.api.Size; +import org.jboss.aesh.terminal.utils.InputStreamReader; + +/** + * Abstract console with support for line discipline. + * The {@link Console} interface represents the slave + * side of a PTY, but implementations derived from this class + * will handle both the slave and master side of things. + * + * In order to correctly handle line discipline, the console + * needs to read the input in advance in order to raise the + * signals as fast as possible. + * For example, when the user hits Ctrl+C, we can't wait until + * the application consumes all the read events. + * The same applies to echoing, when enabled, as the echoing + * has to happen as soon as the user hit the keyboard, and not + * only when the application running in the terminal processes + * the input. + */ +public class LineDisciplineConsole extends AbstractConsole { + + private static final int PIPE_SIZE = 1024; + + /* + * Master output stream + */ + protected final OutputStream masterOutput; + + /* + * Slave input pipe write side + */ + protected final OutputStream slaveInputPipe; + + /* + * Slave streams + */ + protected final InputStream slaveInput; + protected final Reader slaveReader; + protected final PrintWriter slaveWriter; + protected final OutputStream slaveOutput; + + /** + * Console data + */ + protected final String encoding; + protected final Attributes attributes; + protected final Size size; + + /** + * Application + */ + protected IntConsumer application; + protected CharsetDecoder decoder; + protected ByteBuffer bytes; + protected CharBuffer chars; + + public LineDisciplineConsole(String name, + String type, + OutputStream masterOutput, + String encoding) throws IOException { + super(name, type); + PipedInputStream input = new PipedInputStream(PIPE_SIZE); + this.slaveInputPipe = new PipedOutputStream(input); + // This is a hack to fix a problem in gogo where closure closes + // streams for commands if they are instances of PipedInputStream. + // So we need to get around and make sure it's not an instance of + // that class by using a dumb FilterInputStream class to wrap it. + this.slaveInput = new FilterInputStream(input) {}; + this.slaveReader = new InputStreamReader(slaveInput, encoding); + this.slaveOutput = new FilteringOutputStream(); + this.slaveWriter = new PrintWriter(new OutputStreamWriter(slaveOutput, encoding)); + this.masterOutput = masterOutput; + this.encoding = encoding; + this.attributes = new Attributes(); + this.size = new Size(50, 160); + parseInfoCmp(); + } + + public Reader reader() { + return slaveReader; + } + + public PrintWriter writer() { + return slaveWriter; + } + + @Override + public InputStream input() { + return slaveInput; + } + + @Override + public OutputStream output() { + return slaveOutput; + } + + public Attributes getAttributes() { + Attributes attr = new Attributes(); + attr.copy(attributes); + return attr; + } + + public void setAttributes(Attributes attr) { + attributes.copy(attr); + } + + public Size getSize() { + return new Size(size.getHeight(), size.getWidth()); + } + + public void setSize(Size sz) { + size.setHeight(sz.getHeight()); + size.setWidth(sz.getWidth()); + } + + @Override + public void raise(Signal signal) { + assert signal != null; + // Do not call clear() atm as this can cause + // deadlock between reading / writing threads + // TODO: any way to fix that ? + /* + if (!attributes.getLocalFlag(LocalFlag.NOFLSH)) { + try { + slaveReader.clear(); + } catch (IOException e) { + // Ignore + } + } + */ + echoSignal(signal); + super.raise(signal); + } + + /** + * Master input processing. + * All data coming to the console should be provided + * using this method. + * + * @param c the input byte + * @throws IOException + */ + public void processInputByte(int c) throws IOException { + if (attributes.getLocalFlag(LocalFlag.ISIG)) { + if (c == attributes.getControlChar(ControlChar.VINTR)) { + raise(Signal.INT); + return; + } else if (c == attributes.getControlChar(ControlChar.VQUIT)) { + raise(Signal.QUIT); + return; + } else if (c == attributes.getControlChar(ControlChar.VSUSP)) { + raise(Signal.TSTP); + return; + } else if (c == attributes.getControlChar(ControlChar.VSTATUS)) { + raise(Signal.INFO); + } + } + if (c == '\r') { + if (attributes.getInputFlag(InputFlag.IGNCR)) { + return; + } + if (attributes.getInputFlag(InputFlag.ICRNL)) { + c = '\n'; + } + } else if (c == '\n' && attributes.getInputFlag(InputFlag.INLCR)) { + c = '\r'; + } + if (attributes.getLocalFlag(LocalFlag.ECHO)) { + processOutputByte(c); + masterOutput.flush(); + } + slaveInputPipe.write(c); + slaveInputPipe.flush(); + } + + /** + * Master output processing. + * All data going to the master should be provided by this method. + * + * @param c the output byte + * @throws IOException + */ + protected void processOutputByte(int c) throws IOException { + if (attributes.getOutputFlag(OutputFlag.OPOST)) { + if (c == '\n') { + if (attributes.getOutputFlag(OutputFlag.ONLCR)) { + masterOutput.write('\r'); + masterOutput.write('\n'); + return; + } + } + } + masterOutput.write(c); + } + + public void close() throws IOException { + try { + slaveReader.close(); + } finally { + try { + slaveInputPipe.close(); + } finally { + try { + } finally { + slaveWriter.close(); + } + } + } + } + + private class FilteringOutputStream extends OutputStream { + @Override + public void write(int b) throws IOException { + processOutputByte(b); + } + + @Override + public void flush() throws IOException { + masterOutput.flush(); + } + + @Override + public void close() throws IOException { + masterOutput.close(); + } + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/NativeSignalHandler.java b/src/main/java/org/jboss/aesh/terminal/impl/NativeSignalHandler.java new file mode 100644 index 000000000..603768210 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/NativeSignalHandler.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + + +import org.jboss.aesh.terminal.api.Console.Signal; +import org.jboss.aesh.terminal.api.Console.SignalHandler; + +public final class NativeSignalHandler implements SignalHandler { + + public static final NativeSignalHandler SIG_DFL = new NativeSignalHandler(); + + public static final NativeSignalHandler SIG_IGN = new NativeSignalHandler(); + + private NativeSignalHandler() { + } + + public void handle(Signal signal) { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/PosixSysConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/PosixSysConsole.java new file mode 100644 index 000000000..fc399f9c4 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/PosixSysConsole.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Reader; +import java.util.HashMap; +import java.util.Map; + +import org.jboss.aesh.terminal.utils.InputStreamReader; +import org.jboss.aesh.terminal.utils.ShutdownHooks; +import org.jboss.aesh.terminal.utils.ShutdownHooks.Task; +import org.jboss.aesh.terminal.utils.Signals; + +public class PosixSysConsole extends AbstractPosixConsole { + + protected final InputStream input; + protected final OutputStream output; + protected final Reader reader; + protected final PrintWriter writer; + protected final Map<Signal, Object> nativeHandlers = new HashMap<>(); + protected final Task closer; + + public PosixSysConsole(String name, String type, Pty pty, String encoding, boolean nativeSignals) throws IOException { + super(name, type, pty); + assert encoding != null; + this.input = pty.getSlaveInput(); + this.output = pty.getSlaveOutput(); + this.reader = new InputStreamReader(input, encoding); + this.writer = new PrintWriter(new OutputStreamWriter(output, encoding)); + parseInfoCmp(); + if (nativeSignals) { + for (final Signal signal : Signal.values()) { + nativeHandlers.put(signal, Signals.register(signal.name(), () -> raise(signal))); + } + } + closer = PosixSysConsole.this::close; + ShutdownHooks.add(closer); + } + + public Reader reader() { + return reader; + } + + public PrintWriter writer() { + return writer; + } + + @Override + public InputStream input() { + return input; + } + + @Override + public OutputStream output() { + return output; + } + + @Override + public void close() throws IOException { + ShutdownHooks.remove(closer); + for (Map.Entry<Signal, Object> entry : nativeHandlers.entrySet()) { + Signals.unregister(entry.getKey().name(), entry.getValue()); + } + super.close(); + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/Pty.java b/src/main/java/org/jboss/aesh/terminal/impl/Pty.java new file mode 100644 index 000000000..9ed0e04d1 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/Pty.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Size; + +public interface Pty extends Closeable { + + InputStream getMasterInput() throws IOException; + + OutputStream getMasterOutput() throws IOException; + + InputStream getSlaveInput() throws IOException; + + OutputStream getSlaveOutput() throws IOException; + + Attributes getAttr() throws IOException; + + void setAttr(Attributes attr) throws IOException; + + Size getSize() throws IOException; + + void setSize(Size size) throws IOException; + +} diff --git a/src/main/java/org/jboss/aesh/terminal/impl/WinSysConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/WinSysConsole.java new file mode 100644 index 000000000..2a06e766c --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/impl/WinSysConsole.java @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.impl; + +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.IOError; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.StringWriter; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; + +import org.fusesource.jansi.WindowsAnsiOutputStream; +import org.fusesource.jansi.internal.Kernel32; +import org.fusesource.jansi.internal.Kernel32.INPUT_RECORD; +import org.fusesource.jansi.internal.Kernel32.KEY_EVENT_RECORD; +import org.fusesource.jansi.internal.WindowsSupport; +import org.jboss.aesh.terminal.api.Attributes; +import org.jboss.aesh.terminal.api.Attributes.LocalFlag; +import org.jboss.aesh.terminal.api.Size; +import org.jboss.aesh.terminal.utils.Curses; +import org.jboss.aesh.terminal.utils.InfoCmp.Capability; +import org.jboss.aesh.terminal.utils.InputStreamReader; +import org.jboss.aesh.terminal.utils.ShutdownHooks; +import org.jboss.aesh.terminal.utils.ShutdownHooks.Task; +import org.jboss.aesh.terminal.utils.Signals; + +public class WinSysConsole extends AbstractConsole { + + protected final InputStream input; + protected final OutputStream output; + protected final Reader reader; + protected final PrintWriter writer; + protected final Map<Signal, Object> nativeHandlers = new HashMap<Signal, Object>(); + protected final Task closer; + + private static final int ENABLE_PROCESSED_INPUT = 0x0001; + private static final int ENABLE_LINE_INPUT = 0x0002; + private static final int ENABLE_ECHO_INPUT = 0x0004; + private static final int ENABLE_WINDOW_INPUT = 0x0008; + private static final int ENABLE_MOUSE_INPUT = 0x0010; + private static final int ENABLE_INSERT_MODE = 0x0020; + private static final int ENABLE_QUICK_EDIT_MODE = 0x0040; + + + public WinSysConsole(String name, boolean nativeSignals) throws IOException { + super(name, "windows"); + input = new DirectInputStream(); + output = new WindowsAnsiOutputStream(new FileOutputStream(FileDescriptor.out)); + String encoding = getConsoleEncoding(); + if (encoding == null) { + encoding = Charset.defaultCharset().name(); + } + this.reader = new InputStreamReader(input, encoding); + this.writer = new PrintWriter(new OutputStreamWriter(output, encoding)); + parseInfoCmp(); + // Handle signals + if (nativeSignals) { + for (final Signal signal : Signal.values()) { + nativeHandlers.put(signal, Signals.register(signal.name(), () -> raise(signal))); + } + } + closer = this::close; + ShutdownHooks.add(closer); + } + + @SuppressWarnings("InjectedReferences") + protected static String getConsoleEncoding() { + int codepage = Kernel32.GetConsoleOutputCP(); + //http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html + String charsetMS = "ms" + codepage; + if (Charset.isSupported(charsetMS)) { + return charsetMS; + } + String charsetCP = "cp" + codepage; + if (Charset.isSupported(charsetCP)) { + return charsetCP; + } + return null; + } + + public Reader reader() { + return reader; + } + + public PrintWriter writer() { + return writer; + } + + @Override + public InputStream input() { + return input; + } + + @Override + public OutputStream output() { + return output; + } + + public Attributes getAttributes() { + int mode = WindowsSupport.getConsoleMode(); + Attributes attributes = new Attributes(); + if ((mode & ENABLE_ECHO_INPUT) != 0) { + attributes.setLocalFlag(LocalFlag.ECHO, true); + } + if ((mode & ENABLE_LINE_INPUT) != 0) { + attributes.setLocalFlag(LocalFlag.ICANON, true); + } + return attributes; + } + + public void setAttributes(Attributes attr) { + int mode = 0; + if (attr.getLocalFlag(LocalFlag.ECHO)) { + mode |= ENABLE_ECHO_INPUT; + } + if (attr.getLocalFlag(LocalFlag.ICANON)) { + mode |= ENABLE_LINE_INPUT; + } + WindowsSupport.setConsoleMode(mode); + } + + public Size getSize() { + return new Size(WindowsSupport.getWindowsTerminalHeight(), + WindowsSupport.getWindowsTerminalWidth()); + } + + public void setSize(Size size) { + throw new UnsupportedOperationException("Can not resize windows console"); + } + + public void close() throws IOException { + ShutdownHooks.remove(closer); + for (Map.Entry<Signal, Object> entry : nativeHandlers.entrySet()) { + Signals.unregister(entry.getKey().name(), entry.getValue()); + } + reader.close(); + writer.close(); + } + + private byte[] readConsoleInput() { + // XXX does how many events to read in one call matter? + INPUT_RECORD[] events = null; + try { + events = WindowsSupport.readConsoleInput(1); + } catch (IOException e) { + LOGGER.log(Level.FINE, "read Windows console input error: ", e); + } + if (events == null) { + return new byte[0]; + } + StringBuilder sb = new StringBuilder(); + for (INPUT_RECORD event : events) { + KEY_EVENT_RECORD keyEvent = event.keyEvent; + // support some C1 control sequences: ALT + [@-_] (and [a-z]?) => ESC <ascii> + // http://en.wikipedia.org/wiki/C0_and_C1_control_codes#C1_set + final int altState = KEY_EVENT_RECORD.LEFT_ALT_PRESSED | KEY_EVENT_RECORD.RIGHT_ALT_PRESSED; + // Pressing "Alt Gr" is translated to Alt-Ctrl, hence it has to be checked that Ctrl is _not_ pressed, + // otherwise inserting of "Alt Gr" codes on non-US keyboards would yield errors + final int ctrlState = KEY_EVENT_RECORD.LEFT_CTRL_PRESSED | KEY_EVENT_RECORD.RIGHT_CTRL_PRESSED; + // Compute the overall alt state + boolean isAlt = ((keyEvent.controlKeyState & altState) != 0) && ((keyEvent.controlKeyState & ctrlState) == 0); + + //Log.trace(keyEvent.keyDown? "KEY_DOWN" : "KEY_UP", "key code:", keyEvent.keyCode, "char:", (long)keyEvent.uchar); + if (keyEvent.keyDown) { + if (keyEvent.uchar > 0) { + if (isAlt) { + sb.append('\033'); + } + sb.append(keyEvent.uchar); + } + else { + // virtual keycodes: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx + // TODO: numpad keys, modifiers + String escapeSequence = null; + switch (keyEvent.keyCode) { + case 0x08: // VK_BACK BackSpace + escapeSequence = getSequence(Capability.key_backspace); + break; + case 0x21: // VK_PRIOR PageUp + escapeSequence = getSequence(Capability.key_ppage); + break; + case 0x22: // VK_NEXT PageDown + escapeSequence = getSequence(Capability.key_npage); + break; + case 0x23: // VK_END + escapeSequence = getSequence(Capability.key_end); + break; + case 0x24: // VK_HOME + escapeSequence = getSequence(Capability.key_home); + break; + case 0x25: // VK_LEFT + escapeSequence = getSequence(Capability.key_left); + break; + case 0x26: // VK_UP + escapeSequence = getSequence(Capability.key_up); + break; + case 0x27: // VK_RIGHT + escapeSequence = getSequence(Capability.key_right); + break; + case 0x28: // VK_DOWN + escapeSequence = getSequence(Capability.key_down); + break; + case 0x2D: // VK_INSERT + escapeSequence = getSequence(Capability.key_ic); + break; + case 0x2E: // VK_DELETE + escapeSequence = getSequence(Capability.key_dc); + break; + case 0x70: // VK_F1 + escapeSequence = getSequence(Capability.key_f1); + break; + case 0x71: // VK_F2 + escapeSequence = getSequence(Capability.key_f2); + break; + case 0x72: // VK_F3 + escapeSequence = getSequence(Capability.key_f3); + break; + case 0x73: // VK_F4 + escapeSequence = getSequence(Capability.key_f4); + break; + case 0x74: // VK_F5 + escapeSequence = getSequence(Capability.key_f5); + break; + case 0x75: // VK_F6 + escapeSequence = getSequence(Capability.key_f6); + break; + case 0x76: // VK_F7 + escapeSequence = getSequence(Capability.key_f7); + break; + case 0x77: // VK_F8 + escapeSequence = getSequence(Capability.key_f8); + break; + case 0x78: // VK_F9 + escapeSequence = getSequence(Capability.key_f9); + break; + case 0x79: // VK_F10 + escapeSequence = getSequence(Capability.key_f10); + break; + case 0x7A: // VK_F11 + escapeSequence = getSequence(Capability.key_f11); + break; + case 0x7B: // VK_F12 + escapeSequence = getSequence(Capability.key_f12); + break; + default: + break; + } + if (escapeSequence != null) { + for (int k = 0; k < keyEvent.repeatCount; k++) { + if (isAlt) { + sb.append('\033'); + } + sb.append(escapeSequence); + } + } + } + } else { + // key up event + // support ALT+NumPad input method + if (keyEvent.keyCode == 0x12/*VK_MENU ALT key*/ && keyEvent.uchar > 0) { + sb.append(keyEvent.uchar); + } + } + } + return sb.toString().getBytes(); + } + + private String getSequence(Capability cap) { + String str = strings.get(cap); + if (str != null) { + StringWriter sw = new StringWriter(); + try { + Curses.tputs(sw, str); + } catch (IOException e) { + throw new IOError(e); + } + return sw.toString(); + } + return null; + } + + private class DirectInputStream extends InputStream { + private byte[] buf = null; + int bufIdx = 0; + + @Override + public int read() throws IOException { + while (buf == null || bufIdx == buf.length) { + buf = readConsoleInput(); + bufIdx = 0; + } + int c = buf[bufIdx] & 0xFF; + bufIdx++; + return c; + } + + public int read(byte b[], int off, int len) throws IOException { + if (b == null) { + throw new NullPointerException(); + } else if (off < 0 || len < 0 || len > b.length - off) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return 0; + } + + int c = read(); + if (c == -1) { + return -1; + } + b[off] = (byte)c; + return 1; + } + } +} diff --git a/src/main/java/org/jboss/aesh/terminal/Curses.java b/src/main/java/org/jboss/aesh/terminal/utils/Curses.java similarity index 99% rename from src/main/java/org/jboss/aesh/terminal/Curses.java rename to src/main/java/org/jboss/aesh/terminal/utils/Curses.java index 69e8f8b34..ef0cb4578 100644 --- a/src/main/java/org/jboss/aesh/terminal/Curses.java +++ b/src/main/java/org/jboss/aesh/terminal/utils/Curses.java @@ -6,7 +6,7 @@ * * http://www.opensource.org/licenses/bsd-license.php */ -package org.jboss.aesh.terminal; +package org.jboss.aesh.terminal.utils; import java.io.IOException; import java.io.Writer; diff --git a/src/main/java/org/jboss/aesh/terminal/ExecHelper.java b/src/main/java/org/jboss/aesh/terminal/utils/ExecHelper.java similarity index 80% rename from src/main/java/org/jboss/aesh/terminal/ExecHelper.java rename to src/main/java/org/jboss/aesh/terminal/utils/ExecHelper.java index 9de83ee42..108b3d0e2 100644 --- a/src/main/java/org/jboss/aesh/terminal/ExecHelper.java +++ b/src/main/java/org/jboss/aesh/terminal/utils/ExecHelper.java @@ -6,7 +6,7 @@ * * http://www.opensource.org/licenses/bsd-license.php */ -package org.jboss.aesh.terminal; +package org.jboss.aesh.terminal.utils; import java.io.ByteArrayOutputStream; import java.io.Closeable; @@ -15,14 +15,9 @@ import java.io.OutputStream; /** - * Provides access to terminal line settings via <tt>stty</tt>. + * Helper methods for capturing an external process output. * - * @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a> - * @author <a href="mailto:[email protected]">Dale Kemp</a> - * @author <a href="mailto:[email protected]">Jason Dillon</a> - * @author <a href="mailto:[email protected]">Jean-Baptiste Onofré</a> * @author <a href="mailto:[email protected]">Guillaume Nodet</a> - * @since 2.0 */ public final class ExecHelper { diff --git a/src/main/java/org/jboss/aesh/terminal/InfoCmp.java b/src/main/java/org/jboss/aesh/terminal/utils/InfoCmp.java similarity index 99% rename from src/main/java/org/jboss/aesh/terminal/InfoCmp.java rename to src/main/java/org/jboss/aesh/terminal/utils/InfoCmp.java index 4f1dc5600..603454c74 100644 --- a/src/main/java/org/jboss/aesh/terminal/InfoCmp.java +++ b/src/main/java/org/jboss/aesh/terminal/utils/InfoCmp.java @@ -6,7 +6,7 @@ * * http://www.opensource.org/licenses/bsd-license.php */ -package org.jboss.aesh.terminal; +package org.jboss.aesh.terminal.utils; import java.io.IOException; import java.util.HashMap; diff --git a/src/main/java/org/jboss/aesh/terminal/utils/InputStreamReader.java b/src/main/java/org/jboss/aesh/terminal/utils/InputStreamReader.java new file mode 100644 index 000000000..71686b29f --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/utils/InputStreamReader.java @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.MalformedInputException; +import java.nio.charset.UnmappableCharacterException; + + +/** + * + * NOTE for JLine: the default InputStreamReader that comes from the JRE + * usually read more bytes than needed from the input stream, which + * is not usable in a character per character model used in the console. + * We thus use the harmony code which only reads the minimal number of bytes. + */ + +/** + * A class for turning a byte stream into a character stream. Data read from the + * source input stream is converted into characters by either a default or a + * provided character converter. The default encoding is taken from the + * "file.encoding" system property. {@code InputStreamReader} contains a buffer + * of bytes read from the source stream and converts these into characters as + * needed. The buffer size is 8K. + * + * @see OutputStreamWriter + */ +public class InputStreamReader extends Reader { + private InputStream in; + + private static final int BUFFER_SIZE = 4; + + private boolean endOfInput = false; + + CharsetDecoder decoder; + + ByteBuffer bytes = ByteBuffer.allocate(BUFFER_SIZE); + + char pending = (char) -1; + + /** + * Constructs a new {@code InputStreamReader} on the {@link InputStream} + * {@code in}. This constructor sets the character converter to the encoding + * specified in the "file.encoding" property and falls back to ISO 8859_1 + * (ISO-Latin-1) if the property doesn't exist. + * + * @param in + * the input stream from which to read characters. + */ + public InputStreamReader(InputStream in) { + super(in); + this.in = in; + decoder = Charset.defaultCharset().newDecoder().onMalformedInput( + CodingErrorAction.REPLACE).onUnmappableCharacter( + CodingErrorAction.REPLACE); + bytes.limit(0); + } + + /** + * Constructs a new InputStreamReader on the InputStream {@code in}. The + * character converter that is used to decode bytes into characters is + * identified by name by {@code enc}. If the encoding cannot be found, an + * UnsupportedEncodingException error is thrown. + * + * @param in + * the InputStream from which to read characters. + * @param enc + * identifies the character converter to use. + * @throws NullPointerException + * if {@code enc} is {@code null}. + * @throws UnsupportedEncodingException + * if the encoding specified by {@code enc} cannot be found. + */ + public InputStreamReader(InputStream in, final String enc) + throws UnsupportedEncodingException { + super(in); + if (enc == null) { + throw new NullPointerException(); + } + this.in = in; + try { + decoder = Charset.forName(enc).newDecoder().onMalformedInput( + CodingErrorAction.REPLACE).onUnmappableCharacter( + CodingErrorAction.REPLACE); + } catch (IllegalArgumentException e) { + throw (UnsupportedEncodingException) + new UnsupportedEncodingException(enc).initCause(e); + } + bytes.limit(0); + } + + /** + * Constructs a new InputStreamReader on the InputStream {@code in} and + * CharsetDecoder {@code dec}. + * + * @param in + * the source InputStream from which to read characters. + * @param dec + * the CharsetDecoder used by the character conversion. + */ + public InputStreamReader(InputStream in, CharsetDecoder dec) { + super(in); + dec.averageCharsPerByte(); + this.in = in; + decoder = dec; + bytes.limit(0); + } + + /** + * Constructs a new InputStreamReader on the InputStream {@code in} and + * Charset {@code charset}. + * + * @param in + * the source InputStream from which to read characters. + * @param charset + * the Charset that defines the character converter + */ + public InputStreamReader(InputStream in, Charset charset) { + super(in); + this.in = in; + decoder = charset.newDecoder().onMalformedInput( + CodingErrorAction.REPLACE).onUnmappableCharacter( + CodingErrorAction.REPLACE); + bytes.limit(0); + } + + /** + * Closes this reader. This implementation closes the source InputStream and + * releases all local storage. + * + * @throws IOException + * if an error occurs attempting to close this reader. + */ + @Override + public void close() throws IOException { + synchronized (lock) { + decoder = null; + if (in != null) { + in.close(); + in = null; + } + } + } + + /** + * Returns the name of the encoding used to convert bytes into characters. + * The value {@code null} is returned if this reader has been closed. + * + * @return the name of the character converter or {@code null} if this + * reader is closed. + */ + public String getEncoding() { + if (!isOpen()) { + return null; + } + return decoder.charset().name(); + } + + /** + * Reads a single character from this reader and returns it as an integer + * with the two higher-order bytes set to 0. Returns -1 if the end of the + * reader has been reached. The byte value is either obtained from + * converting bytes in this reader's buffer or by first filling the buffer + * from the source InputStream and then reading from the buffer. + * + * @return the character read or -1 if the end of the reader has been + * reached. + * @throws IOException + * if this reader is closed or some other I/O error occurs. + */ + @Override + public int read() throws IOException { + synchronized (lock) { + if (!isOpen()) { + throw new IOException("InputStreamReader is closed."); + } + + if (pending != (char) -1) { + char c = pending; + pending = (char) -1; + return c; + } + char buf[] = new char[2]; + int nb = read(buf, 0, 2); + if (nb == 2) { + pending = buf[1]; + } + if (nb > 0) { + return buf[0]; + } else { + return -1; + } + } + } + + /** + * Reads at most {@code length} characters from this reader and stores them + * at position {@code offset} in the character array {@code buf}. Returns + * the number of characters actually read or -1 if the end of the reader has + * been reached. The bytes are either obtained from converting bytes in this + * reader's buffer or by first filling the buffer from the source + * InputStream and then reading from the buffer. + * + * @param buf + * the array to store the characters read. + * @param offset + * the initial position in {@code buf} to store the characters + * read from this reader. + * @param length + * the maximum number of characters to read. + * @return the number of characters read or -1 if the end of the reader has + * been reached. + * @throws IndexOutOfBoundsException + * if {@code offset < 0} or {@code length < 0}, or if + * {@code offset + length} is greater than the length of + * {@code buf}. + * @throws IOException + * if this reader is closed or some other I/O error occurs. + */ + @Override + public int read(char[] buf, int offset, int length) throws IOException { + synchronized (lock) { + if (!isOpen()) { + throw new IOException("InputStreamReader is closed."); + } + if (offset < 0 || offset > buf.length - length || length < 0) { + throw new IndexOutOfBoundsException(); + } + if (length == 0) { + return 0; + } + + CharBuffer out = CharBuffer.wrap(buf, offset, length); + CoderResult result = CoderResult.UNDERFLOW; + + // bytes.remaining() indicates number of bytes in buffer + // when 1-st time entered, it'll be equal to zero + boolean needInput = !bytes.hasRemaining(); + + while (out.position() == offset) { + // fill the buffer if needed + if (needInput) { + try { + if ((in.available() == 0) + && (out.position() > offset)) { + // we could return the result without blocking read + break; + } + } catch (IOException e) { + // available didn't work so just try the read + } + + int off = bytes.arrayOffset() + bytes.limit(); + int was_red = in.read(bytes.array(), off, 1); + + if (was_red == -1) { + endOfInput = true; + break; + } else if (was_red == 0) { + break; + } + bytes.limit(bytes.limit() + was_red); + } + + // decode bytes + result = decoder.decode(bytes, out, false); + + if (result.isUnderflow()) { + // compact the buffer if no space left + if (bytes.limit() == bytes.capacity()) { + bytes.compact(); + bytes.limit(bytes.position()); + bytes.position(0); + } + needInput = true; + } else { + break; + } + } + + if (result == CoderResult.UNDERFLOW && endOfInput) { + result = decoder.decode(bytes, out, true); + decoder.flush(out); + decoder.reset(); + } + if (result.isMalformed()) { + throw new MalformedInputException(result.length()); + } else if (result.isUnmappable()) { + throw new UnmappableCharacterException(result.length()); + } + + return out.position() - offset == 0 ? -1 : out.position() - offset; + } + } + + /* + * Answer a boolean indicating whether or not this InputStreamReader is + * open. + */ + private boolean isOpen() { + return in != null; + } + + /** + * Indicates whether this reader is ready to be read without blocking. If + * the result is {@code true}, the next {@code read()} will not block. If + * the result is {@code false} then this reader may or may not block when + * {@code read()} is called. This implementation returns {@code true} if + * there are bytes available in the buffer or the source stream has bytes + * available. + * + * @return {@code true} if the receiver will not block when {@code read()} + * is called, {@code false} if unknown or blocking will occur. + * @throws IOException + * if this reader is closed or some other I/O error occurs. + */ + @Override + public boolean ready() throws IOException { + synchronized (lock) { + if (in == null) { + throw new IOException("InputStreamReader is closed."); + } + try { + return bytes.hasRemaining() || in.available() > 0; + } catch (IOException e) { + return false; + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/jboss/aesh/terminal/OSUtils.java b/src/main/java/org/jboss/aesh/terminal/utils/OSUtils.java similarity index 83% rename from src/main/java/org/jboss/aesh/terminal/OSUtils.java rename to src/main/java/org/jboss/aesh/terminal/utils/OSUtils.java index 57236e1c3..c3633a039 100644 --- a/src/main/java/org/jboss/aesh/terminal/OSUtils.java +++ b/src/main/java/org/jboss/aesh/terminal/utils/OSUtils.java @@ -1,10 +1,15 @@ -package org.jboss.aesh.terminal; +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.utils; import java.io.File; -/** - * Created by gnodet on 01/10/15. - */ public class OSUtils { public static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("win"); diff --git a/src/main/java/org/jboss/aesh/terminal/utils/ShutdownHooks.java b/src/main/java/org/jboss/aesh/terminal/utils/ShutdownHooks.java new file mode 100644 index 000000000..1920c955d --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/utils/ShutdownHooks.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.jboss.aesh.util.LoggerUtil; + +/** + * Manages the JLine shutdown-hook thread and tasks to execute on shutdown. + * + * @author <a href="mailto:[email protected]">Jason Dillon</a> + */ +public final class ShutdownHooks +{ + private static final Logger LOGGER = LoggerUtil.getLogger(ShutdownHooks.class.getName()); + + private static final List<Task> tasks = new ArrayList<Task>(); + + private static Thread hook; + + public static synchronized <T extends Task> T add(final T task) { + assert task != null; + + // Install the hook thread if needed + if (hook == null) { + hook = addHook(new Thread("JLine Shutdown Hook") + { + @Override + public void run() { + runTasks(); + } + }); + } + + // Track the task + LOGGER.log(Level.FINE, "Adding shutdown-hook task: ", task); + tasks.add(task); + + return task; + } + + private static synchronized void runTasks() { + LOGGER.log(Level.FINE, "Running all shutdown-hook tasks"); + + // Iterate through copy of tasks list + for (Task task : tasks.toArray(new Task[tasks.size()])) { + LOGGER.log(Level.FINE, "Running task: ", task); + try { + task.run(); + } + catch (Throwable e) { + LOGGER.log(Level.WARNING, "Task failed", e); + } + } + + tasks.clear(); + } + + private static Thread addHook(final Thread thread) { + LOGGER.log(Level.FINE, "Registering shutdown-hook: ", thread); + try { + Runtime.getRuntime().addShutdownHook(thread); + } + catch (AbstractMethodError e) { + // JDK 1.3+ only method. Bummer. + LOGGER.log(Level.FINE, "Failed to register shutdown-hook", e); + } + return thread; + } + + public static synchronized void remove(final Task task) { + assert task != null; + + // ignore if hook never installed + if (hook == null) { + return; + } + + // Drop the task + tasks.remove(task); + + // If there are no more tasks, then remove the hook thread + if (tasks.isEmpty()) { + removeHook(hook); + hook = null; + } + } + + private static void removeHook(final Thread thread) { + LOGGER.log(Level.FINE, "Removing shutdown-hook: ", thread); + + try { + Runtime.getRuntime().removeShutdownHook(thread); + } + catch (AbstractMethodError e) { + // JDK 1.3+ only method. Bummer. + LOGGER.log(Level.FINE, "Failed to remove shutdown-hook", e); + } + catch (IllegalStateException e) { + // The VM is shutting down, not a big deal; ignore + } + } + + /** + * Essentially a {@link Runnable} which allows running to throw an exception. + */ + public interface Task + { + void run() throws Exception; + } +} \ No newline at end of file diff --git a/src/main/java/org/jboss/aesh/terminal/utils/Signals.java b/src/main/java/org/jboss/aesh/terminal/utils/Signals.java new file mode 100644 index 000000000..39b9f87e9 --- /dev/null +++ b/src/main/java/org/jboss/aesh/terminal/utils/Signals.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2002-2015, the original author or authors. + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * http://www.opensource.org/licenses/bsd-license.php + */ +package org.jboss.aesh.terminal.utils; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * Signals helpers. + * + * @author <a href="mailto:[email protected]">Guillaume Nodet</a> + */ +public final class Signals { + + private Signals() { + } + + /** + * + * @param name the signal, CONT, STOP, etc... + * @param handler the callback to run + * + * @return an object that needs to be passed to the {@link #unregister(String, Object)} + * method to unregister the handler + */ + public static Object register(String name, Runnable handler) { + assert name != null; + assert handler != null; + return register(name, handler, handler.getClass().getClassLoader()); + } + + public static Object register(String name, final Runnable handler, ClassLoader loader) { + try { + Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler"); + // Implement signal handler + Object signalHandler = Proxy.newProxyInstance(loader, + new Class<?>[]{signalHandlerClass}, new InvocationHandler() { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + // only method we are proxying is handle() + handler.run(); + return null; + } + }); + doRegister(name, signalHandler); + } catch (Exception e) { + // Ignore this one too, if the above failed, the signal API is incompatible with what we're expecting + } + return null; + } + + public static Object registerDefault(String name) { + try { + Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler"); + doRegister(name, signalHandlerClass.getField("SIG_DFL").get(null)); + } catch (Exception e) { + // Ignore this one too, if the above failed, the signal API is incompatible with what we're expecting + } + return null; + } + + public static Object registerIgnore(String name) { + try { + Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler"); + doRegister(name, signalHandlerClass.getField("SIG_IGN").get(null)); + } catch (Exception e) { + // Ignore this one too, if the above failed, the signal API is incompatible with what we're expecting + } + return null; + } + + public static void unregister(String name, Object previous) { + try { + // We should make sure the current signal is the one we registered + if (previous != null) { + doRegister(name, previous); + } + } catch (Exception e) { + // Ignore + } + } + + private static Object doRegister(String name, Object handler) throws Exception { + Class<?> signalClass = Class.forName("sun.misc.Signal"); + Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler"); + Object signal = signalClass.getConstructor(String.class).newInstance(name); + return signalClass.getMethod("handle", signalClass, signalHandlerClass) + .invoke(null, signal, handler); + } + +} diff --git a/src/test/java/org/jboss/aesh/console/terminal/CursesTest.java b/src/test/java/org/jboss/aesh/console/terminal/utils/CursesTest.java similarity index 89% rename from src/test/java/org/jboss/aesh/console/terminal/CursesTest.java rename to src/test/java/org/jboss/aesh/console/terminal/utils/CursesTest.java index 9c928d56e..f6acf8989 100644 --- a/src/test/java/org/jboss/aesh/console/terminal/CursesTest.java +++ b/src/test/java/org/jboss/aesh/console/terminal/utils/CursesTest.java @@ -6,11 +6,11 @@ * * http://www.opensource.org/licenses/bsd-license.php */ -package org.jboss.aesh.console.terminal; +package org.jboss.aesh.console.terminal.utils; import java.io.StringWriter; -import org.jboss.aesh.terminal.Curses; +import org.jboss.aesh.terminal.utils.Curses; import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/src/test/java/org/jboss/aesh/console/terminal/InfoCmpTest.java b/src/test/java/org/jboss/aesh/console/terminal/utils/InfoCmpTest.java similarity index 87% rename from src/test/java/org/jboss/aesh/console/terminal/InfoCmpTest.java rename to src/test/java/org/jboss/aesh/console/terminal/utils/InfoCmpTest.java index 841d87ac0..0dde640f0 100644 --- a/src/test/java/org/jboss/aesh/console/terminal/InfoCmpTest.java +++ b/src/test/java/org/jboss/aesh/console/terminal/utils/InfoCmpTest.java @@ -6,15 +6,15 @@ * * http://www.opensource.org/licenses/bsd-license.php */ -package org.jboss.aesh.console.terminal; +package org.jboss.aesh.console.terminal.utils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.jboss.aesh.terminal.InfoCmp; -import org.jboss.aesh.terminal.InfoCmp.Capability; +import org.jboss.aesh.terminal.utils.InfoCmp; +import org.jboss.aesh.terminal.utils.InfoCmp.Capability; import org.junit.Test; import static org.junit.Assert.assertEquals;
6a3f2b45ebe4cb529b9a209105168c81252201bb
Delta Spike
fix documentation for custom ProjectStages
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStage.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStage.java index 375c57ee1..4a837cb60 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStage.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStage.java @@ -65,8 +65,8 @@ * members into a registered {@link ProjectStageHolder} as shown in the following * sample:</p> * <pre> - * package org.apache.myfaces.extensions.cdi.test.api.projectstage; - * public class MyProjectStages implements ProjectStageHolder { + * package org.apache.deltaspike.test.core.api.projectstage; + * public class TestProjectStages implements ProjectStageHolder { * public static final class MyOwnProjectStage extends ProjectStage {}; * public static final MyOwnProjectStage MyOwnProjectStage = new MyOwnProjectStage(); * @@ -74,15 +74,15 @@ * public static final MyOtherProjectStage MyOtherProjectStage = new MyOtherProjectStage(); * } * </pre> - * <p>For activating those projectstages, you have to register this ProjectStageHolder class + * <p>For activating those ProjectStages, you have to register this ProjectStageHolder class * to get picked up via the java.util.ServiceLoader mechanism. Simply create a file * <pre> - * META-INF/services/org.apache.myfaces.extensions.cdi.core.api.projectstage.ProjectStageHolder + * META-INF/services/org.apache.deltaspike.core.api.projectstage.ProjectStageHolder * </pre> * which contains the fully qualified class name of custom ProjectStageHolder implementation: * <pre> * # this class now gets picked up by java.util.ServiceLoader - * org.apache.myfaces.extensions.cdi.core.test.api.projectstage.MyProjectStages + * org.apache.deltaspike.test.core.api.projectstage.TestProjectStages * </pre> * </p> * <p>You can use your own ProjectStages exactly the same way as all the ones provided
a6cbe8419351fcd8d26f1660dd4b112a7cd64e0b
camel
removed the generics from the Process interface- so that it must take an Exchange parameter to avoid ClassCastException when- sending any old Exchange into an Endpoint<FooExchange>--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@534145 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/CamelClient.java b/camel-core/src/main/java/org/apache/camel/CamelClient.java index 7a31a33ec893c..95e67ce1011a3 100644 --- a/camel-core/src/main/java/org/apache/camel/CamelClient.java +++ b/camel-core/src/main/java/org/apache/camel/CamelClient.java @@ -58,7 +58,7 @@ public E send(String endpointUri, E exchange) { * @param endpointUri the endpoint URI to send the exchange to * @param processor the transformer used to populate the new exchange */ - public E send(String endpointUri, Processor<E> processor) { + public E send(String endpointUri, Processor processor) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, processor); } @@ -70,7 +70,8 @@ public E send(String endpointUri, Processor<E> processor) { * @param exchange the exchange to send */ public E send(Endpoint<E> endpoint, E exchange) { - producerCache.send(endpoint, exchange); + E convertedExchange = endpoint.toExchangeType(exchange); + producerCache.send(endpoint, convertedExchange); return exchange; } @@ -80,7 +81,7 @@ public E send(Endpoint<E> endpoint, E exchange) { * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange */ - public E send(Endpoint<E> endpoint, Processor<E> processor) { + public E send(Endpoint<E> endpoint, Processor processor) { return producerCache.send(endpoint, processor); } diff --git a/camel-core/src/main/java/org/apache/camel/Endpoint.java b/camel-core/src/main/java/org/apache/camel/Endpoint.java index d70cc7bba86e1..39de94562359c 100644 --- a/camel-core/src/main/java/org/apache/camel/Endpoint.java +++ b/camel-core/src/main/java/org/apache/camel/Endpoint.java @@ -48,7 +48,12 @@ public interface Endpoint<E extends Exchange> { * Creates a new exchange for communicating with this exchange using the given exchange to pre-populate the values * of the headers and messages */ - E createExchange(E exchange); + E createExchange(Exchange exchange); + + /** + * Converts the given exchange to this endpoints required type + */ + E toExchangeType(Exchange exchange); /** * Returns the context which created the endpoint @@ -69,6 +74,5 @@ public interface Endpoint<E extends Exchange> { * * @return a newly created consumer */ - Consumer<E> createConsumer(Processor<E> processor) throws Exception; - + Consumer<E> createConsumer(Processor processor) throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/Processor.java b/camel-core/src/main/java/org/apache/camel/Processor.java index 86a00a255cf8b..6ac8080758236 100644 --- a/camel-core/src/main/java/org/apache/camel/Processor.java +++ b/camel-core/src/main/java/org/apache/camel/Processor.java @@ -25,12 +25,12 @@ * * @version $Revision$ */ -public interface Processor<E> { +public interface Processor { /** * Processes the message exchange * * @throws Exception if an internal processing error has occurred. */ - void process(E exchange) throws Exception; + void process(Exchange exchange) throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/Producer.java b/camel-core/src/main/java/org/apache/camel/Producer.java index 9f679156dc5ba..2aad603173d58 100644 --- a/camel-core/src/main/java/org/apache/camel/Producer.java +++ b/camel-core/src/main/java/org/apache/camel/Producer.java @@ -22,7 +22,8 @@ * * @version $Revision$ */ -public interface Producer<E extends Exchange> extends Processor<E>, Service { +public interface Producer<E extends Exchange> extends Processor, Service { + Endpoint<E> getEndpoint(); /** diff --git a/camel-core/src/main/java/org/apache/camel/Route.java b/camel-core/src/main/java/org/apache/camel/Route.java index 2c30f968dcaca..6745d2102b92b 100644 --- a/camel-core/src/main/java/org/apache/camel/Route.java +++ b/camel-core/src/main/java/org/apache/camel/Route.java @@ -31,9 +31,9 @@ public class Route<E extends Exchange> { private final Map<String, Object> properties = new HashMap<String, Object>(16); private Endpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; - public Route(Endpoint<E> endpoint, Processor<E> processor) { + public Route(Endpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } @@ -51,11 +51,11 @@ public void setEndpoint(Endpoint<E> endpoint) { this.endpoint = endpoint; } - public Processor<E> getProcessor() { + public Processor getProcessor() { return processor; } - public void setProcessor(Processor<E> processor) { + public void setProcessor(Processor processor) { this.processor = processor; } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java index 8626c07cd7be1..fb93f87c8d797 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java @@ -23,14 +23,14 @@ /** * @version $Revision$ */ -public class ConstantProcessorBuilder<E extends Exchange> implements ProcessorFactory<E> { - private Processor<E> processor; +public class ConstantProcessorBuilder implements ProcessorFactory { + private Processor processor; - public ConstantProcessorBuilder(Processor<E> processor) { + public ConstantProcessorBuilder(Processor processor) { this.processor = processor; } - public Processor<E> createProcessor() { + public Processor createProcessor() { return processor; } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java index b2ae7f9657563..1bd98add66662 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java @@ -33,64 +33,64 @@ * * @version $Revision$ */ -public class DeadLetterChannelBuilder<E extends Exchange> implements ErrorHandlerBuilder<E> { +public class DeadLetterChannelBuilder implements ErrorHandlerBuilder { private RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); - private ProcessorFactory<E> deadLetterFactory; - private Processor<E> defaultDeadLetterEndpoint; - private Expression<E> defaultDeadLetterEndpointExpression; + private ProcessorFactory deadLetterFactory; + private Processor defaultDeadLetterEndpoint; + private Expression defaultDeadLetterEndpointExpression; private String defaultDeadLetterEndpointUri = "log:org.apache.camel.DeadLetterChannel:error"; - private Logger<E> logger = DeadLetterChannel.createDefaultLogger(); + private Logger logger = DeadLetterChannel.createDefaultLogger(); public DeadLetterChannelBuilder() { } - public DeadLetterChannelBuilder(Processor<E> processor) { - this(new ConstantProcessorBuilder<E>(processor)); + public DeadLetterChannelBuilder(Processor processor) { + this(new ConstantProcessorBuilder(processor)); } - public DeadLetterChannelBuilder(ProcessorFactory<E> deadLetterFactory) { + public DeadLetterChannelBuilder(ProcessorFactory deadLetterFactory) { this.deadLetterFactory = deadLetterFactory; } - public ErrorHandlerBuilder<E> copy() { - DeadLetterChannelBuilder<E> answer = new DeadLetterChannelBuilder<E>(deadLetterFactory); + public ErrorHandlerBuilder copy() { + DeadLetterChannelBuilder answer = new DeadLetterChannelBuilder(deadLetterFactory); answer.setRedeliveryPolicy(getRedeliveryPolicy().copy()); return answer; } - public Processor<E> createErrorHandler(Processor<E> processor) throws Exception { - Processor<E> deadLetter = getDeadLetterFactory().createProcessor(); - return new DeadLetterChannel<E>(processor, deadLetter, getRedeliveryPolicy(), getLogger()); + public Processor createErrorHandler(Processor processor) throws Exception { + Processor deadLetter = getDeadLetterFactory().createProcessor(); + return new DeadLetterChannel(processor, deadLetter, getRedeliveryPolicy(), getLogger()); } // Builder methods //------------------------------------------------------------------------- - public DeadLetterChannelBuilder<E> backOffMultiplier(double backOffMultiplier) { + public DeadLetterChannelBuilder backOffMultiplier(double backOffMultiplier) { getRedeliveryPolicy().backOffMultiplier(backOffMultiplier); return this; } - public DeadLetterChannelBuilder<E> collisionAvoidancePercent(short collisionAvoidancePercent) { + public DeadLetterChannelBuilder collisionAvoidancePercent(short collisionAvoidancePercent) { getRedeliveryPolicy().collisionAvoidancePercent(collisionAvoidancePercent); return this; } - public DeadLetterChannelBuilder<E> initialRedeliveryDelay(long initialRedeliveryDelay) { + public DeadLetterChannelBuilder initialRedeliveryDelay(long initialRedeliveryDelay) { getRedeliveryPolicy().initialRedeliveryDelay(initialRedeliveryDelay); return this; } - public DeadLetterChannelBuilder<E> maximumRedeliveries(int maximumRedeliveries) { + public DeadLetterChannelBuilder maximumRedeliveries(int maximumRedeliveries) { getRedeliveryPolicy().maximumRedeliveries(maximumRedeliveries); return this; } - public DeadLetterChannelBuilder<E> useCollisionAvoidance() { + public DeadLetterChannelBuilder useCollisionAvoidance() { getRedeliveryPolicy().useCollisionAvoidance(); return this; } - public DeadLetterChannelBuilder<E> useExponentialBackOff() { + public DeadLetterChannelBuilder useExponentialBackOff() { getRedeliveryPolicy().useExponentialBackOff(); return this; } @@ -98,7 +98,7 @@ public DeadLetterChannelBuilder<E> useExponentialBackOff() { /** * Sets the logger used for caught exceptions */ - public DeadLetterChannelBuilder<E> logger(Logger<E> logger) { + public DeadLetterChannelBuilder logger(Logger logger) { setLogger(logger); return this; } @@ -106,7 +106,7 @@ public DeadLetterChannelBuilder<E> logger(Logger<E> logger) { /** * Sets the logging level of exceptions caught */ - public DeadLetterChannelBuilder<E> loggingLevel(LoggingLevel level) { + public DeadLetterChannelBuilder loggingLevel(LoggingLevel level) { getLogger().setLevel(level); return this; } @@ -114,7 +114,7 @@ public DeadLetterChannelBuilder<E> loggingLevel(LoggingLevel level) { /** * Sets the log used for caught exceptions */ - public DeadLetterChannelBuilder<E> log(Log log) { + public DeadLetterChannelBuilder log(Log log) { getLogger().setLog(log); return this; } @@ -122,14 +122,14 @@ public DeadLetterChannelBuilder<E> log(Log log) { /** * Sets the log used for caught exceptions */ - public DeadLetterChannelBuilder<E> log(String log) { + public DeadLetterChannelBuilder log(String log) { return log(LogFactory.getLog(log)); } /** * Sets the log used for caught exceptions */ - public DeadLetterChannelBuilder<E> log(Class log) { + public DeadLetterChannelBuilder log(Class log) { return log(LogFactory.getLog(log)); } @@ -146,10 +146,10 @@ public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) { this.redeliveryPolicy = redeliveryPolicy; } - public ProcessorFactory<E> getDeadLetterFactory() { + public ProcessorFactory getDeadLetterFactory() { if (deadLetterFactory == null) { - deadLetterFactory = new ProcessorFactory<E>() { - public Processor<E> createProcessor() { + deadLetterFactory = new ProcessorFactory() { + public Processor createProcessor() { return getDefaultDeadLetterEndpoint(); } }; @@ -160,13 +160,13 @@ public Processor<E> createProcessor() { /** * Sets the default dead letter queue factory */ - public void setDeadLetterFactory(ProcessorFactory<E> deadLetterFactory) { + public void setDeadLetterFactory(ProcessorFactory deadLetterFactory) { this.deadLetterFactory = deadLetterFactory; } - public Processor<E> getDefaultDeadLetterEndpoint() { + public Processor getDefaultDeadLetterEndpoint() { if (defaultDeadLetterEndpoint == null) { - defaultDeadLetterEndpoint = new RecipientList<E>(getDefaultDeadLetterEndpointExpression()); + defaultDeadLetterEndpoint = new RecipientList(getDefaultDeadLetterEndpointExpression()); } return defaultDeadLetterEndpoint; } @@ -174,11 +174,11 @@ public Processor<E> getDefaultDeadLetterEndpoint() { /** * Sets the default dead letter endpoint used */ - public void setDefaultDeadLetterEndpoint(Processor<E> defaultDeadLetterEndpoint) { + public void setDefaultDeadLetterEndpoint(Processor defaultDeadLetterEndpoint) { this.defaultDeadLetterEndpoint = defaultDeadLetterEndpoint; } - public Expression<E> getDefaultDeadLetterEndpointExpression() { + public Expression getDefaultDeadLetterEndpointExpression() { if (defaultDeadLetterEndpointExpression == null) { defaultDeadLetterEndpointExpression = ExpressionBuilder.constantExpression(getDefaultDeadLetterEndpointUri()); } @@ -189,7 +189,7 @@ public Expression<E> getDefaultDeadLetterEndpointExpression() { * Sets the expression used to decide the dead letter channel endpoint for an exchange * if no factory is provided via {@link #setDeadLetterFactory(ProcessorFactory)} */ - public void setDefaultDeadLetterEndpointExpression(Expression<E> defaultDeadLetterEndpointExpression) { + public void setDefaultDeadLetterEndpointExpression(Expression defaultDeadLetterEndpointExpression) { this.defaultDeadLetterEndpointExpression = defaultDeadLetterEndpointExpression; } @@ -207,11 +207,11 @@ public void setDefaultDeadLetterEndpointUri(String defaultDeadLetterEndpointUri) this.defaultDeadLetterEndpointUri = defaultDeadLetterEndpointUri; } - public Logger<E> getLogger() { + public Logger getLogger() { return logger; } - public void setLogger(Logger<E> logger) { + public void setLogger(Logger logger) { this.logger = logger; } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java index 3d9432e7ec5a1..ffbe3ea244e3c 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java @@ -32,5 +32,5 @@ public interface ErrorHandlerBuilder<E extends Exchange> { /** * Creates the error handler interceptor */ - Processor<E> createErrorHandler(Processor<E> processor) throws Exception; + Processor createErrorHandler(Processor processor) throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java index 814a567583941..9578afce5c95f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java @@ -24,10 +24,10 @@ /** * @version $Revision$ */ -public class FilterBuilder<E extends Exchange> extends FromBuilder<E> { - private Predicate<E> predicate; +public class FilterBuilder extends FromBuilder { + private Predicate predicate; - public FilterBuilder(FromBuilder<E> builder, Predicate<E> predicate) { + public FilterBuilder(FromBuilder builder, Predicate predicate) { super(builder); this.predicate = predicate; } @@ -35,7 +35,7 @@ public FilterBuilder(FromBuilder<E> builder, Predicate<E> predicate) { /** * Adds another predicate using a logical AND */ - public FilterBuilder<E> and(Predicate<E> predicate) { + public FilterBuilder and(Predicate predicate) { this.predicate = PredicateBuilder.and(this.predicate, predicate); return this; } @@ -43,19 +43,19 @@ public FilterBuilder<E> and(Predicate<E> predicate) { /** * Adds another predicate using a logical OR */ - public FilterBuilder<E> or(Predicate<E> predicate) { + public FilterBuilder or(Predicate predicate) { this.predicate = PredicateBuilder.or(this.predicate, predicate); return this; } - public Predicate<E> getPredicate() { + public Predicate getPredicate() { return predicate; } - public FilterProcessor<E> createProcessor() throws Exception { + public FilterProcessor createProcessor() throws Exception { // lets create a single processor for all child predicates - Processor<E> childProcessor = super.createProcessor(); - return new FilterProcessor<E>(predicate, childProcessor); + Processor childProcessor = super.createProcessor(); + return new FilterProcessor(predicate, childProcessor); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java index 9965827b6c0eb..98cc2de5e995f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java @@ -39,7 +39,7 @@ /** * @version $Revision$ */ -public class FromBuilder<E extends Exchange> extends BuilderSupport implements ProcessorFactory<E> { +public class FromBuilder extends BuilderSupport implements ProcessorFactory { public static final String DEFAULT_TRACE_CATEGORY = "org.apache.camel.TRACE"; @@ -264,7 +264,7 @@ public FromBuilder trace() { @Fluent public FromBuilder trace(@FluentArg("category")String category) { final Log log = LogFactory.getLog(category); - return intercept(new DelegateProcessor<Exchange>(){ + return intercept(new DelegateProcessor(){ @Override public void process(Exchange exchange) throws Exception { log.trace(exchange); diff --git a/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java index 3a24e0b0b16e8..c70b13d3c5738 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java @@ -28,8 +28,8 @@ * * @version $Revision: 1.1 $ */ -public class IdempotentConsumerBuilder<E extends Exchange> extends FromBuilder<E> implements ProcessorFactory<E> { - private final Expression<E> messageIdExpression; +public class IdempotentConsumerBuilder extends FromBuilder implements ProcessorFactory { + private final Expression messageIdExpression; private final MessageIdRepository messageIdRegistry; public IdempotentConsumerBuilder(FromBuilder fromBuilder, Expression messageIdExpression, MessageIdRepository messageIdRegistry) { diff --git a/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java index b21b9f9fc52f0..f081eb924b85e 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java @@ -28,37 +28,37 @@ /** * @version $Revision: 519943 $ */ -public class InterceptorBuilder<E extends Exchange> implements ProcessorFactory<E> { - private final List<DelegateProcessor<E>> intercepts = new ArrayList<DelegateProcessor<E>>(); - private final FromBuilder<E> parent; - private FromBuilder<E> target; +public class InterceptorBuilder implements ProcessorFactory { + private final List<DelegateProcessor> intercepts = new ArrayList<DelegateProcessor>(); + private final FromBuilder parent; + private FromBuilder target; - public InterceptorBuilder(FromBuilder<E> parent) { + public InterceptorBuilder(FromBuilder parent) { this.parent = parent; } @Fluent("interceptor") - public InterceptorBuilder<E> add(@FluentArg("ref") DelegateProcessor<E> interceptor) { + public InterceptorBuilder add(@FluentArg("ref") DelegateProcessor interceptor) { intercepts.add(interceptor); return this; } @Fluent(callOnElementEnd=true) - public FromBuilder<E> target() { - this.target = new FromBuilder<E>(parent); + public FromBuilder target() { + this.target = new FromBuilder(parent); return target; } - public Processor<E> createProcessor() throws Exception { + public Processor createProcessor() throws Exception { // The target is required. if( target == null ) throw new RuntimeCamelException("target provided."); // Interceptors are optional - DelegateProcessor<E> first=null; - DelegateProcessor<E> last=null; - for (DelegateProcessor<E> p : intercepts) { + DelegateProcessor first=null; + DelegateProcessor last=null; + for (DelegateProcessor p : intercepts) { if( first == null ) { first = p; } @@ -68,7 +68,7 @@ public Processor<E> createProcessor() throws Exception { last = p; } - Processor<E> p = target.createProcessor(); + Processor p = target.createProcessor(); if( last != null ) { last.setNext(p); } diff --git a/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java index 06fbfa3fcd4cf..a5c36579bab42 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java @@ -30,7 +30,7 @@ * * @version $Revision$ */ -public class LoggingErrorHandlerBuilder<E extends Exchange> implements ErrorHandlerBuilder<E> { +public class LoggingErrorHandlerBuilder implements ErrorHandlerBuilder { private Log log = LogFactory.getLog(Logger.class); private LoggingLevel level = LoggingLevel.INFO; @@ -46,15 +46,15 @@ public LoggingErrorHandlerBuilder(Log log, LoggingLevel level) { this.level = level; } - public ErrorHandlerBuilder<E> copy() { - LoggingErrorHandlerBuilder<E> answer = new LoggingErrorHandlerBuilder<E>(); + public ErrorHandlerBuilder copy() { + LoggingErrorHandlerBuilder answer = new LoggingErrorHandlerBuilder(); answer.setLog(getLog()); answer.setLevel(getLevel()); return answer; } - public Processor<E> createErrorHandler(Processor<E> processor) { - return new LoggingErrorHandler<E>(processor, log, level); + public Processor createErrorHandler(Processor processor) { + return new LoggingErrorHandler(processor, log, level); } public LoggingLevel getLevel() { diff --git a/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java index f8c749be8a946..5cc77be8ee8d1 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java @@ -29,16 +29,16 @@ * * @version $Revision$ */ -public class MulticastBuilder<E extends Exchange> extends FromBuilder<E> { - private final Collection<Endpoint<E>> endpoints; +public class MulticastBuilder extends FromBuilder { + private final Collection<Endpoint> endpoints; - public MulticastBuilder(FromBuilder<E> parent, Collection<Endpoint<E>> endpoints) { + public MulticastBuilder(FromBuilder parent, Collection<Endpoint> endpoints) { super(parent); this.endpoints = endpoints; } @Override - public Processor<E> createProcessor() throws Exception { - return new MulticastProcessor<E>(endpoints); + public Processor createProcessor() throws Exception { + return new MulticastProcessor(endpoints); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java index c99692ae081ba..f602231720c1f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java @@ -34,7 +34,7 @@ public ErrorHandlerBuilder<E> copy() { return this; } - public Processor<E> createErrorHandler(Processor<E> processor) { + public Processor createErrorHandler(Processor processor) { return processor; } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java index 6737f9bd112bd..355d4d6a74577 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java @@ -29,16 +29,16 @@ * * @version $Revision$ */ -public class PipelineBuilder<E extends Exchange> extends FromBuilder<E> { - private final Collection<Endpoint<E>> endpoints; +public class PipelineBuilder extends FromBuilder { + private final Collection<Endpoint> endpoints; - public PipelineBuilder(FromBuilder<E> parent, Collection<Endpoint<E>> endpoints) { + public PipelineBuilder(FromBuilder parent, Collection<Endpoint> endpoints) { super(parent); this.endpoints = endpoints; } @Override - public Processor<E> createProcessor() throws Exception { - return new Pipeline<E>(endpoints); + public Processor createProcessor() throws Exception { + return new Pipeline(endpoints); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java index c309f6b599b9f..cd7772cf617b2 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java @@ -28,36 +28,36 @@ /** * @version $Revision: 519943 $ */ -public class PolicyBuilder<E extends Exchange> implements ProcessorFactory<E> { - private final ArrayList<Policy<E>> policies = new ArrayList<Policy<E>>(); - private final FromBuilder<E> parent; - private FromBuilder<E> target; +public class PolicyBuilder implements ProcessorFactory { + private final ArrayList<Policy> policies = new ArrayList<Policy>(); + private final FromBuilder parent; + private FromBuilder target; - public PolicyBuilder(FromBuilder<E> parent) { + public PolicyBuilder(FromBuilder parent) { this.parent = parent; } @Fluent("policy") - public PolicyBuilder<E> add(@FluentArg("ref") Policy<E> interceptor) { + public PolicyBuilder add(@FluentArg("ref") Policy interceptor) { policies.add(interceptor); return this; } @Fluent(callOnElementEnd=true) - public FromBuilder<E> target() { - this.target = new FromBuilder<E>(parent); + public FromBuilder target() { + this.target = new FromBuilder(parent); return target; } - public Processor<E> createProcessor() throws Exception { + public Processor createProcessor() throws Exception { // The target is required. if( target == null ) throw new RuntimeCamelException("target not provided."); - Processor<E> last = target.createProcessor(); + Processor last = target.createProcessor(); Collections.reverse(policies); - for (Policy<E> p : policies) { + for (Policy p : policies) { last = p.wrap(last); } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java index 3b210e02e3801..828dba56a36aa 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java @@ -31,9 +31,9 @@ public class ProcessorBuilder { /** * Creates a processor which sets the body of the IN message to the value of the expression */ - public static <E extends Exchange> Processor<E> setBody(final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setBody(final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object newBody = expression.evaluate(exchange); exchange.getIn().setBody(newBody); } @@ -48,9 +48,9 @@ public String toString() { /** * Creates a processor which sets the body of the IN message to the value of the expression */ - public static <E extends Exchange> Processor<E> setOutBody(final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setOutBody(final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object newBody = expression.evaluate(exchange); exchange.getOut().setBody(newBody); } @@ -65,9 +65,9 @@ public String toString() { /** * Sets the header on the IN message */ - public static <E extends Exchange> Processor<E> setHeader(final String name, final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setHeader(final String name, final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object value = expression.evaluate(exchange); exchange.getIn().setHeader(name, value); } @@ -82,9 +82,9 @@ public String toString() { /** * Sets the header on the OUT message */ - public static <E extends Exchange> Processor<E> setOutHeader(final String name, final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setOutHeader(final String name, final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object value = expression.evaluate(exchange); exchange.getOut().setHeader(name, value); } @@ -99,9 +99,9 @@ public String toString() { /** * Sets the property on the exchange */ - public static <E extends Exchange> Processor<E> setProperty(final String name, final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setProperty(final String name, final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object value = expression.evaluate(exchange); exchange.setProperty(name, value); } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java b/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java index 7d56582e85cc6..2cd2fb8decd9f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java @@ -24,8 +24,8 @@ * * @version $Revision$ */ -public interface ProcessorFactory<E extends Exchange> { +public interface ProcessorFactory { - public Processor<E> createProcessor() throws Exception; + public Processor createProcessor() throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java index e4c220f5afe72..21ea333391e13 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java @@ -28,17 +28,17 @@ * @version $Revision$ */ -public class SplitterBuilder<E extends Exchange> extends FromBuilder<E> { - private final Expression<E> expression; +public class SplitterBuilder extends FromBuilder { + private final Expression expression; - public SplitterBuilder(FromBuilder<E> parent, Expression<E> expression) { + public SplitterBuilder(FromBuilder parent, Expression expression) { super(parent); this.expression = expression; } - public Processor<E> createProcessor() throws Exception { + public Processor createProcessor() throws Exception { // lets create a single processor for all child predicates - Processor<E> destination = super.createProcessor(); - return new Splitter<E>(destination, expression); + Processor destination = super.createProcessor(); + return new Splitter(destination, expression); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java index d2a35e8b10be0..ad7ab46fce754 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java @@ -25,16 +25,16 @@ /** * @version $Revision$ */ -public class ToBuilder<E extends Exchange> extends FromBuilder<E> { - private Endpoint<E> destination; +public class ToBuilder<E extends Exchange> extends FromBuilder { + private Endpoint destination; - public ToBuilder(FromBuilder<E> parent, Endpoint<E> endpoint) { + public ToBuilder(FromBuilder parent, Endpoint endpoint) { super(parent); this.destination = endpoint; } @Override - public Processor<E> createProcessor() { - return new SendProcessor<E>(destination); + public Processor createProcessor() { + return new SendProcessor(destination); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java index 555243c7c9e21..79b181baf2b4a 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java @@ -45,7 +45,7 @@ * * @version $Revision: 531854 $ */ -public class XsltBuilder<E extends Exchange> implements Processor<E> { +public class XsltBuilder implements Processor { private Map<String, Object> parameters = new HashMap<String, Object>(); private XmlConverter converter = new XmlConverter(); private Transformer transformer; @@ -64,7 +64,7 @@ public String toString() { return "XSLT[" + transformer + "]"; } - public synchronized void process(E exchange) throws Exception { + public synchronized void process(Exchange exchange) throws Exception { Transformer transformer = getTransformer(); if (transformer == null) { throw new IllegalArgumentException("No transformer configured!"); @@ -82,16 +82,16 @@ public synchronized void process(E exchange) throws Exception { /** * Creates an XSLT processor using the given transformer instance */ - public static <E extends Exchange> XsltBuilder<E> xslt(Transformer transformer) { - return new XsltBuilder<E>(transformer); + public static XsltBuilder xslt(Transformer transformer) { + return new XsltBuilder(transformer); } /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(Source xslt) throws TransformerConfigurationException { + public static XsltBuilder xslt(Source xslt) throws TransformerConfigurationException { notNull(xslt, "xslt"); - XsltBuilder<E> answer = new XsltBuilder<E>(); + XsltBuilder answer = new XsltBuilder(); answer.setTransformerSource(xslt); return answer; } @@ -99,7 +99,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(Source xslt) throws Trans /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(File xslt) throws TransformerConfigurationException { + public static XsltBuilder xslt(File xslt) throws TransformerConfigurationException { notNull(xslt, "xslt"); return xslt(new StreamSource(xslt)); } @@ -107,7 +107,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(File xslt) throws Transfo /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(URL xslt) throws TransformerConfigurationException, IOException { + public static XsltBuilder xslt(URL xslt) throws TransformerConfigurationException, IOException { notNull(xslt, "xslt"); return xslt(xslt.openStream()); } @@ -115,7 +115,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(URL xslt) throws Transfor /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(InputStream xslt) throws TransformerConfigurationException, IOException { + public static XsltBuilder xslt(InputStream xslt) throws TransformerConfigurationException, IOException { notNull(xslt, "xslt"); return xslt(new StreamSource(xslt)); } @@ -123,7 +123,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(InputStream xslt) throws /** * Sets the output as being a byte[] */ - public XsltBuilder<E> outputBytes() { + public XsltBuilder outputBytes() { setResultHandler(new StreamResultHandler()); return this; } @@ -131,7 +131,7 @@ public XsltBuilder<E> outputBytes() { /** * Sets the output as being a String */ - public XsltBuilder<E> outputString() { + public XsltBuilder outputString() { setResultHandler(new StringResultHandler()); return this; } @@ -139,12 +139,12 @@ public XsltBuilder<E> outputString() { /** * Sets the output as being a DOM */ - public XsltBuilder<E> outputDOM() { + public XsltBuilder outputDOM() { setResultHandler(new DomResultHandler()); return this; } - public XsltBuilder<E> parameter(String name, Object value) { + public XsltBuilder parameter(String name, Object value) { parameters.put(name, value); return this; } @@ -194,7 +194,7 @@ public void setTransformerSource(Source source) throws TransformerConfigurationE /** * Converts the inbound body to a {@link Source} */ - protected Source getSource(E exchange) { + protected Source getSource(Exchange exchange) { Message in = exchange.getIn(); Source source = in.getBody(Source.class); if (source == null) { diff --git a/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java index 29f0a43da4be2..2bca9272c7980 100644 --- a/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java @@ -44,21 +44,21 @@ public DirectEndpoint(String uri, DirectComponent<E> component) { super(uri, component); } - public Producer<E> createProducer() throws Exception { - return startService(new DefaultProducer<E>(this) { - public void process(E exchange) throws Exception { + public Producer createProducer() throws Exception { + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) throws Exception { DirectEndpoint.this.process(exchange); } }); } - protected void process(E exchange) throws Exception { + protected void process(Exchange exchange) throws Exception { for (DefaultConsumer<E> consumer : consumers) { consumer.getProcessor().process(exchange); } } - public Consumer<E> createConsumer(Processor<E> processor) throws Exception { + public Consumer<E> createConsumer(Processor processor) throws Exception { DefaultConsumer<E> consumer = new DefaultConsumer<E>(this, processor) { @Override public void start() throws Exception { diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java index 60dc89d0bef7b..ff3ad28b0e875 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java @@ -38,7 +38,7 @@ public class FileConsumer extends PollingConsumer<FileExchange> { private String regexPattern = ""; private long lastPollTime = 0l; - public FileConsumer(final FileEndpoint endpoint, Processor<FileExchange> processor) { + public FileConsumer(final FileEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java index ffba01b66e55e..3a965508e1148 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java @@ -53,7 +53,7 @@ public Producer<FileExchange> createProducer() throws Exception { * @throws Exception * @see org.apache.camel.Endpoint#createConsumer(org.apache.camel.Processor) */ - public Consumer<FileExchange> createConsumer(Processor<FileExchange> file) throws Exception { + public Consumer<FileExchange> createConsumer(Processor file) throws Exception { Consumer<FileExchange> result = new FileConsumer(this, file); configureConsumer(result); return startService(result); diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java b/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java index 5e4e6a556477c..8738ea465abb9 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java @@ -1,63 +1,70 @@ /** - * + * * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ - package org.apache.camel.component.file; -import java.io.File; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; +import org.apache.camel.Exchange; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultProducer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import java.io.File; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; + /** * A {@link Producer} implementation for File - * + * * @version $Revision: 523016 $ */ -public class FileProducer extends DefaultProducer<FileExchange>{ - - private static final transient Log log=LogFactory.getLog(FileProducer.class); +public class FileProducer extends DefaultProducer { + private static final transient Log log = LogFactory.getLog(FileProducer.class); private final FileEndpoint endpoint; - public FileProducer(FileEndpoint endpoint){ + public FileProducer(FileEndpoint endpoint) { super(endpoint); - this.endpoint=endpoint; + this.endpoint = endpoint; } /** * @param exchange - * @see org.apache.camel.Processor#process(java.lang.Object) + * @see org.apache.camel.Processor#process(Exchange) */ - public void process(FileExchange exchange){ - ByteBuffer payload=exchange.getIn().getBody(ByteBuffer.class); + public void process(Exchange exchange) { + process(endpoint.toExchangeType(exchange)); + } + + public void process(FileExchange exchange) { + ByteBuffer payload = exchange.getIn().getBody(ByteBuffer.class); payload.flip(); - File file=null; - if(endpoint.getFile()!=null&&endpoint.getFile().isDirectory()){ - file=new File(endpoint.getFile(),exchange.getFile().getName()); - }else{ - file=exchange.getFile(); + File file = null; + + if (endpoint.getFile() != null && endpoint.getFile().isDirectory()) { + file = new File(endpoint.getFile(), exchange.getFile().getName()); } - try{ - FileChannel fc=new RandomAccessFile(file,"rw").getChannel(); + else { + file = exchange.getFile(); + } + try { + FileChannel fc = new RandomAccessFile(file, "rw").getChannel(); fc.position(fc.size()); fc.write(payload); fc.close(); - }catch(Throwable e){ - log.error("Failed to write to File: "+file,e); + } + catch (Throwable e) { + log.error("Failed to write to File: " + file, e); } } } diff --git a/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java index 4409b331aaabf..cbacca7086007 100644 --- a/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java @@ -45,7 +45,7 @@ public class MockEndpoint extends DefaultEndpoint<Exchange> { private static final transient Log log = LogFactory.getLog(MockEndpoint.class); private int expectedCount = -1; - private Map<Integer, Processor<Exchange>> processors = new HashMap<Integer, Processor<Exchange>>(); + private Map<Integer, Processor> processors = new HashMap<Integer, Processor>(); private List<Exchange> receivedExchanges = new ArrayList<Exchange>(); private List<Throwable> failures = new ArrayList<Throwable>(); private List<Runnable> tests = new ArrayList<Runnable>(); @@ -93,7 +93,7 @@ public Exchange createExchange() { return new DefaultExchange(getContext()); } - public Consumer<Exchange> createConsumer(Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("You cannot consume from this endpoint"); } @@ -309,7 +309,7 @@ protected synchronized void onExchange(Exchange exchange) { receivedExchanges.add(exchange); - Processor<Exchange> processor = processors.get(getReceivedCounter()); + Processor processor = processors.get(getReceivedCounter()); if (processor != null) { processor.process(exchange); } diff --git a/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java index 8c11efbdc0c6a..2ea513607165c 100644 --- a/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java @@ -22,6 +22,7 @@ import org.apache.camel.NoSuchEndpointException; import org.apache.camel.Processor; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.impl.DefaultProducer; @@ -46,14 +47,14 @@ public Producer<PojoExchange> createProducer() throws Exception { if( pojo == null ) throw new NoSuchEndpointException(getEndpointUri()); - return startService(new DefaultProducer<PojoExchange>(this) { - public void process(PojoExchange exchange) { - invoke(pojo, exchange); + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) { + invoke(pojo, toExchangeType(exchange)); } }); } - public Consumer<PojoExchange> createConsumer(Processor<PojoExchange> processor) throws Exception { + public Consumer<PojoExchange> createConsumer(Processor processor) throws Exception { throw new Exception("You cannot consume from pojo endpoints."); } diff --git a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java index 471fde08eb702..285a09b635b07 100644 --- a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java @@ -38,7 +38,7 @@ public class TimerConsumer extends DefaultConsumer<PojoExchange> implements Invo private Timer timer; - public TimerConsumer(TimerEndpoint endpoint, Processor<PojoExchange> processor) { + public TimerConsumer(TimerEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java index 63a5f1c5e624e..886ab2c41b9e5 100644 --- a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java @@ -62,7 +62,7 @@ public Producer<PojoExchange> createProducer() throws Exception { throw new RuntimeCamelException("Cannot produce to a TimerEndpoint: "+getEndpointUri()); } - public Consumer<PojoExchange> createConsumer(Processor<PojoExchange> processor) throws Exception { + public Consumer<PojoExchange> createConsumer(Processor processor) throws Exception { TimerConsumer consumer = new TimerConsumer(this, processor); return startService(consumer); } diff --git a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java index c1c974b834136..9de17bfc7d01a 100644 --- a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java @@ -34,10 +34,10 @@ * @version $Revision: 1.1 $ */ public class ProcessorEndpoint extends DefaultEndpoint<Exchange> { - private final Processor<Exchange> processor; - private final LoadBalancer<Exchange> loadBalancer; + private final Processor processor; + private final LoadBalancer loadBalancer; - protected ProcessorEndpoint(String endpointUri, Component component, Processor<Exchange> processor, LoadBalancer<Exchange> loadBalancer) { + protected ProcessorEndpoint(String endpointUri, Component component, Processor processor, LoadBalancer loadBalancer) { super(endpointUri, component); this.processor = processor; this.loadBalancer = loadBalancer; @@ -55,15 +55,15 @@ public void process(Exchange exchange) throws Exception { }); } - public Consumer<Exchange> createConsumer(Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(Processor processor) throws Exception { return startService(new ProcessorEndpointConsumer(this, processor)); } - public Processor<Exchange> getProcessor() { + public Processor getProcessor() { return processor; } - public LoadBalancer<Exchange> getLoadBalancer() { + public LoadBalancer getLoadBalancer() { return loadBalancer; } diff --git a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java index 71b68839741e9..3f7116f3c540f 100644 --- a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java @@ -27,7 +27,7 @@ public class ProcessorEndpointConsumer extends DefaultConsumer<Exchange> { private final ProcessorEndpoint endpoint; - public ProcessorEndpointConsumer(ProcessorEndpoint endpoint, Processor<Exchange> processor) { + public ProcessorEndpointConsumer(ProcessorEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java index a4ada27cd7308..0f881ae7b5f12 100644 --- a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java @@ -42,14 +42,14 @@ public QueueEndpoint(String uri, QueueComponent<E> component) { } public Producer<E> createProducer() throws Exception { - return startService(new DefaultProducer<E>(this) { - public void process(E exchange) { - queue.add(exchange); + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) { + queue.add(toExchangeType(exchange)); } }); } - public Consumer<E> createConsumer(Processor<E> processor) throws Exception { + public Consumer<E> createConsumer(Processor processor) throws Exception { return startService(new QueueEndpointConsumer<E>(this, processor)); } diff --git a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java index a19779a7c3ed0..122a7c6cbf2db 100644 --- a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java @@ -29,10 +29,10 @@ */ public class QueueEndpointConsumer<E extends Exchange> extends ServiceSupport implements Consumer<E>, Runnable { private QueueEndpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; private Thread thread; - public QueueEndpointConsumer(QueueEndpoint<E> endpoint, Processor<E> processor) { + public QueueEndpointConsumer(QueueEndpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 9605ab1ee2042..471ab0119f323 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -295,7 +295,7 @@ protected void doStart() throws Exception { if (routes != null) { for (Route<Exchange> route : routes) { - Processor<Exchange> processor = route.getProcessor(); + Processor processor = route.getProcessor(); Consumer<Exchange> consumer = route.getEndpoint().createConsumer(processor); if (consumer != null) { consumer.start(); diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java index bdbabce80ec32..0680a143c72e4 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java @@ -29,10 +29,10 @@ */ public class DefaultConsumer<E extends Exchange> extends ServiceSupport implements Consumer<E> { private Endpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; private ExceptionHandler exceptionHandler; - public DefaultConsumer(Endpoint<E> endpoint, Processor<E> processor) { + public DefaultConsumer(Endpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } @@ -41,7 +41,7 @@ public Endpoint<E> getEndpoint() { return endpoint; } - public Processor<E> getProcessor() { + public Processor getProcessor() { return processor; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java index 08e89218ae912..477404960b728 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java @@ -109,12 +109,17 @@ public E convertTo(Class<E> type, Exchange exchange) { return getContext().getExchangeConverter().convertTo(type, exchange); } - public E createExchange(E exchange) { + public E createExchange(Exchange exchange) { E answer = createExchange(); answer.copyFrom(exchange); return answer; } + public E toExchangeType(Exchange exchange) { + // TODO avoid cloning exchanges if E == Exchange! + return createExchange(exchange); + } + /** * A helper method to reduce the clutter of implementors of {@link #createProducer()} and {@link #createConsumer(Processor)} */ diff --git a/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java b/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java index d631d3ffdaffa..0740573bbb8cb 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java +++ b/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java @@ -27,7 +27,7 @@ */ public class NoPolicy<E> implements Policy<E> { - public Processor<E> wrap(Processor<E> processor) { + public Processor wrap(Processor processor) { return processor; } } diff --git a/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java b/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java index 12aa5ae3db8c8..8992027281164 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java @@ -42,11 +42,11 @@ public abstract class PollingConsumer<E extends Exchange> extends DefaultConsume private boolean useFixedDelay; private ScheduledFuture<?> future; - public PollingConsumer(DefaultEndpoint<E> endpoint, Processor<E> processor) { + public PollingConsumer(DefaultEndpoint<E> endpoint, Processor processor) { this(endpoint, processor, endpoint.getExecutorService()); } - public PollingConsumer(Endpoint<E> endpoint, Processor<E> processor, ScheduledExecutorService executor) { + public PollingConsumer(Endpoint<E> endpoint, Processor processor, ScheduledExecutorService executor) { super(endpoint, processor); this.executor = executor; if (executor == null) { diff --git a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java index 4fa1d4f3d11c3..d46adf107ffd4 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java @@ -19,6 +19,7 @@ import org.apache.camel.Predicate; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.util.ServiceHelper; import org.apache.camel.impl.ServiceSupport; @@ -31,18 +32,18 @@ * * @version $Revision$ */ -public class ChoiceProcessor<E> extends ServiceSupport implements Processor<E> { - private List<FilterProcessor<E>> filters = new ArrayList<FilterProcessor<E>>(); - private Processor<E> otherwise; +public class ChoiceProcessor extends ServiceSupport implements Processor { + private List<FilterProcessor> filters = new ArrayList<FilterProcessor>(); + private Processor otherwise; - public ChoiceProcessor(List<FilterProcessor<E>> filters, Processor<E> otherwise) { + public ChoiceProcessor(List<FilterProcessor> filters, Processor otherwise) { this.filters = filters; this.otherwise = otherwise; } - public void process(E exchange) throws Exception { - for (FilterProcessor<E> filterProcessor : filters) { - Predicate<E> predicate = filterProcessor.getPredicate(); + public void process(Exchange exchange) throws Exception { + for (FilterProcessor filterProcessor : filters) { + Predicate<Exchange> predicate = filterProcessor.getPredicate(); if (predicate != null && predicate.matches(exchange)) { filterProcessor.getProcessor().process(exchange); return; @@ -57,7 +58,7 @@ public void process(E exchange) throws Exception { public String toString() { StringBuilder builder = new StringBuilder("choice{"); boolean first = true; - for (FilterProcessor<E> processor : filters) { + for (FilterProcessor processor : filters) { if (first) { first = false; } @@ -77,11 +78,11 @@ public String toString() { return builder.toString(); } - public List<FilterProcessor<E>> getFilters() { + public List<FilterProcessor> getFilters() { return filters; } - public Processor<E> getOtherwise() { + public Processor getOtherwise() { return otherwise; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java index 685c4f8c86f2f..862ac703cc487 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java @@ -18,6 +18,7 @@ package org.apache.camel.processor; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ServiceHelper; @@ -28,15 +29,15 @@ * * @version $Revision$ */ -public class CompositeProcessor<E> extends ServiceSupport implements Processor<E> { - private final Collection<Processor<E>> processors; +public class CompositeProcessor extends ServiceSupport implements Processor { + private final Collection<Processor> processors; - public CompositeProcessor(Collection<Processor<E>> processors) { + public CompositeProcessor(Collection<Processor> processors) { this.processors = processors; } - public void process(E exchange) throws Exception { - for (Processor<E> processor : processors) { + public void process(Exchange exchange) throws Exception { + for (Processor processor : processors) { processor.process(exchange); } } @@ -45,7 +46,7 @@ public void process(E exchange) throws Exception { public String toString() { StringBuilder builder = new StringBuilder("[ "); boolean first = true; - for (Processor<E> processor : processors) { + for (Processor processor : processors) { if (first) { first = false; } @@ -58,7 +59,7 @@ public String toString() { return builder.toString(); } - public Collection<Processor<E>> getProcessors() { + public Collection<Processor> getProcessors() { return processors; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java b/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java index a80cebb3f72fc..f9768e6d215df 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java +++ b/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java @@ -32,25 +32,25 @@ * * @version $Revision$ */ -public class DeadLetterChannel<E extends Exchange> extends ServiceSupport implements ErrorHandler<E> { +public class DeadLetterChannel extends ServiceSupport implements ErrorHandler { public static final String REDELIVERY_COUNTER = "org.apache.camel.RedeliveryCounter"; public static final String REDELIVERED = "org.apache.camel.Redelivered"; private static final transient Log log = LogFactory.getLog(DeadLetterChannel.class); - private Processor<E> output; - private Processor<E> deadLetter; + private Processor output; + private Processor deadLetter; private RedeliveryPolicy redeliveryPolicy; - private Logger<E> logger; + private Logger logger; - public static <E extends Exchange> Logger<E> createDefaultLogger() { - return new Logger<E>(log, LoggingLevel.ERROR); + public static <E extends Exchange> Logger createDefaultLogger() { + return new Logger(log, LoggingLevel.ERROR); } - public DeadLetterChannel(Processor<E> output, Processor<E> deadLetter) { - this(output, deadLetter, new RedeliveryPolicy(), DeadLetterChannel.<E>createDefaultLogger()); + public DeadLetterChannel(Processor output, Processor deadLetter) { + this(output, deadLetter, new RedeliveryPolicy(), DeadLetterChannel.createDefaultLogger()); } - public DeadLetterChannel(Processor<E> output, Processor<E> deadLetter, RedeliveryPolicy redeliveryPolicy, Logger<E> logger) { + public DeadLetterChannel(Processor output, Processor deadLetter, RedeliveryPolicy redeliveryPolicy, Logger logger) { this.deadLetter = deadLetter; this.output = output; this.redeliveryPolicy = redeliveryPolicy; @@ -62,7 +62,7 @@ public String toString() { return "DeadLetterChannel[" + output + ", " + deadLetter + ", " + redeliveryPolicy + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { int redeliveryCounter = 0; long redeliveryDelay = 0; @@ -94,14 +94,14 @@ public void process(E exchange) throws Exception { /** * Returns the output processor */ - public Processor<E> getOutput() { + public Processor getOutput() { return output; } /** * Returns the dead letter that message exchanges will be sent to if the redelivery attempts fail */ - public Processor<E> getDeadLetter() { + public Processor getDeadLetter() { return deadLetter; } @@ -116,14 +116,14 @@ public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) { this.redeliveryPolicy = redeliveryPolicy; } - public Logger<E> getLogger() { + public Logger getLogger() { return logger; } /** * Sets the logger strategy; which {@link Log} to use and which {@link LoggingLevel} to use */ - public void setLogger(Logger<E> logger) { + public void setLogger(Logger logger) { this.logger = logger; } @@ -133,7 +133,7 @@ public void setLogger(Logger<E> logger) { /** * Increments the redelivery counter and adds the redelivered flag if the message has been redelivered */ - protected int incrementRedeliveryCounter(E exchange) { + protected int incrementRedeliveryCounter(Exchange exchange) { Message in = exchange.getIn(); Integer counter = in.getHeader(REDELIVERY_COUNTER, Integer.class); int next = 1; diff --git a/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java index 3289e5ad7f9c4..fc764ff2b1937 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java @@ -18,6 +18,7 @@ package org.apache.camel.processor; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.spi.Policy; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ServiceHelper; @@ -28,21 +29,21 @@ * * @version $Revision: 519941 $ */ -public class DelegateProcessor<E> extends ServiceSupport implements Processor<E> { - protected Processor<E> next; +public class DelegateProcessor extends ServiceSupport implements Processor { + protected Processor next; public DelegateProcessor() { } - public DelegateProcessor(Processor<E> next) { + public DelegateProcessor(Processor next) { this.next = next; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { processNext(exchange); } - protected void processNext(E exchange) throws Exception { + protected void processNext(Exchange exchange) throws Exception { if (next != null) { next.process(exchange); } @@ -53,11 +54,11 @@ public String toString() { return "delegate(" + next + ")"; } - public Processor<E> getNext() { + public Processor getNext() { return next; } - public void setNext(Processor<E> next) { + public void setNext(Processor next) { this.next = next; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java b/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java index c00b0e211e788..d9e568b634039 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java @@ -25,5 +25,5 @@ * * @version $Revision$ */ -public interface ErrorHandler<E extends Exchange> extends Processor<E> { +public interface ErrorHandler extends Processor { } diff --git a/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java index 10aa29b85eda2..7d13e0d9bb3a3 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java @@ -19,22 +19,23 @@ import org.apache.camel.Predicate; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ServiceHelper; /** * @version $Revision$ */ -public class FilterProcessor<E> extends ServiceSupport implements Processor<E> { - private Predicate<E> predicate; - private Processor<E> processor; +public class FilterProcessor extends ServiceSupport implements Processor { + private Predicate<Exchange> predicate; + private Processor processor; - public FilterProcessor(Predicate<E> predicate, Processor<E> processor) { + public FilterProcessor(Predicate<Exchange> predicate, Processor processor) { this.predicate = predicate; this.processor = processor; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { if (predicate.matches(exchange)) { processor.process(exchange); } @@ -45,11 +46,11 @@ public String toString() { return "if (" + predicate + ") " + processor; } - public Predicate<E> getPredicate() { + public Predicate<Exchange> getPredicate() { return predicate; } - public Processor<E> getProcessor() { + public Processor getProcessor() { return processor; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Logger.java b/camel-core/src/main/java/org/apache/camel/processor/Logger.java index 16826954161e5..57a961b3e9ef7 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Logger.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Logger.java @@ -28,7 +28,7 @@ * * @version $Revision$ */ -public class Logger<E extends Exchange> implements Processor<E> { +public class Logger implements Processor { private Log log; private LoggingLevel level; @@ -50,7 +50,7 @@ public String toString() { return "Logger[" + log + "]"; } - public void process(E exchange) { + public void process(Exchange exchange) { switch (level) { case DEBUG: if (log.isDebugEnabled()) { @@ -161,7 +161,7 @@ public void log(String message, Throwable exception) { } } - protected Object logMessage(E exchange) { + protected Object logMessage(Exchange exchange) { return exchange; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java b/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java index 20af96816165b..80c1d223bc9b4 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java @@ -29,16 +29,16 @@ * * @version $Revision$ */ -public class LoggingErrorHandler<E extends Exchange> extends ServiceSupport implements ErrorHandler<E> { - private Processor<E> output; +public class LoggingErrorHandler extends ServiceSupport implements ErrorHandler { + private Processor output; private Log log; private LoggingLevel level; - public LoggingErrorHandler(Processor<E> output) { + public LoggingErrorHandler(Processor output) { this(output, LogFactory.getLog(LoggingErrorHandler.class), LoggingLevel.INFO); } - public LoggingErrorHandler(Processor<E> output, Log log, LoggingLevel level) { + public LoggingErrorHandler(Processor output, Log log, LoggingLevel level) { this.output = output; this.log = log; this.level = level; @@ -49,7 +49,7 @@ public String toString() { return "LoggingErrorHandler[" + output + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { try { output.process(exchange); } @@ -64,7 +64,7 @@ public void process(E exchange) throws Exception { /** * Returns the output processor */ - public Processor<E> getOutput() { + public Processor getOutput() { return output; } @@ -86,7 +86,7 @@ public void setLog(Log log) { // Implementation methods //------------------------------------------------------------------------- - protected void logError(E exchange, RuntimeException e) { + protected void logError(Exchange exchange, RuntimeException e) { switch (level) { case DEBUG: if (log.isDebugEnabled()) { @@ -123,7 +123,7 @@ protected void logError(E exchange, RuntimeException e) { } } - protected Object logMessage(E exchange, RuntimeException e) { + protected Object logMessage(Exchange exchange, RuntimeException e) { return e + " while processing exchange: " + exchange; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index 7c4940321dc85..cb5f09c6ef98b 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -32,21 +32,21 @@ * * @version $Revision$ */ -public class MulticastProcessor<E extends Exchange> extends ServiceSupport implements Processor<E> { - private Collection<Producer<E>> producers; +public class MulticastProcessor extends ServiceSupport implements Processor { + private Collection<Producer> producers; /** * A helper method to convert a list of endpoints into a list of processors */ - public static <E extends Exchange> Collection<Producer<E>> toProducers(Collection<Endpoint<E>> endpoints) throws Exception { - Collection<Producer<E>> answer = new ArrayList<Producer<E>>(); - for (Endpoint<E> endpoint : endpoints) { + public static <E extends Exchange> Collection<Producer> toProducers(Collection<Endpoint> endpoints) throws Exception { + Collection<Producer> answer = new ArrayList<Producer>(); + for (Endpoint endpoint : endpoints) { answer.add(endpoint.createProducer()); } return answer; } - public MulticastProcessor(Collection<Endpoint<E>> endpoints) throws Exception { + public MulticastProcessor(Collection<Endpoint> endpoints) throws Exception { this.producers = toProducers(endpoints); } @@ -55,21 +55,21 @@ public String toString() { return "Multicast" + getEndpoints(); } - public void process(E exchange) throws Exception { - for (Producer<E> producer : producers) { - E copy = copyExchangeStrategy(producer, exchange); + public void process(Exchange exchange) throws Exception { + for (Producer producer : producers) { + Exchange copy = copyExchangeStrategy(producer, exchange); producer.process(copy); } } protected void doStop() throws Exception { - for (Producer<E> producer : producers) { + for (Producer producer : producers) { producer.stop(); } } protected void doStart() throws Exception { - for (Producer<E> producer : producers) { + for (Producer producer : producers) { producer.start(); } } @@ -77,16 +77,16 @@ protected void doStart() throws Exception { /** * Returns the producers to multicast to */ - public Collection<Producer<E>> getProducers() { + public Collection<Producer> getProducers() { return producers; } /** * Returns the list of endpoints */ - public Collection<Endpoint<E>> getEndpoints() { - Collection<Endpoint<E>> answer = new ArrayList<Endpoint<E>>(); - for (Producer<E> producer : producers) { + public Collection<Endpoint> getEndpoints() { + Collection<Endpoint> answer = new ArrayList<Endpoint>(); + for (Producer producer : producers) { answer.add(producer.getEndpoint()); } return answer; @@ -99,7 +99,7 @@ public Collection<Endpoint<E>> getEndpoints() { * @param producer the producer that will send the exchange * @param exchange @return the current exchange if no copying is required such as for a pipeline otherwise a new copy of the exchange is returned. */ - protected E copyExchangeStrategy(Producer<E> producer, E exchange) { + protected Exchange copyExchangeStrategy(Producer producer, Exchange exchange) { return producer.createExchange(exchange); } } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java b/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java index 5505504bf42be..9aed0cc93fe16 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java @@ -30,15 +30,15 @@ * * @version $Revision$ */ -public class Pipeline<E extends Exchange> extends MulticastProcessor<E> implements Processor<E> { - public Pipeline(Collection<Endpoint<E>> endpoints) throws Exception { +public class Pipeline extends MulticastProcessor implements Processor { + public Pipeline(Collection<Endpoint> endpoints) throws Exception { super(endpoints); } - public void process(E exchange) throws Exception { - E nextExchange = exchange; + public void process(Exchange exchange) throws Exception { + Exchange nextExchange = exchange; boolean first = true; - for (Producer<E> producer : getProducers()) { + for (Producer producer : getProducers()) { if (first) { first = false; } @@ -56,8 +56,8 @@ public void process(E exchange) throws Exception { * @param previousExchange the previous exchange * @return a new exchange */ - protected E createNextExchange(Producer<E> producer, E previousExchange) { - E answer = producer.createExchange(previousExchange); + protected Exchange createNextExchange(Producer producer, Exchange previousExchange) { + Exchange answer = producer.createExchange(previousExchange); // now lets set the input of the next exchange to the output of the previous message if it is not null Object output = previousExchange.getOut().getBody(); @@ -74,8 +74,8 @@ protected E createNextExchange(Producer<E> producer, E previousExchange) { * @param exchange * @return the current exchange if no copying is required such as for a pipeline otherwise a new copy of the exchange is returned. */ - protected E copyExchangeStrategy(E exchange) { - return (E) exchange.copy(); + protected Exchange copyExchangeStrategy(Exchange exchange) { + return exchange.copy(); } @Override diff --git a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java index 34cb10bdf2cbd..c3d609014bd5b 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java @@ -35,11 +35,11 @@ * * @version $Revision$ */ -public class RecipientList<E extends Exchange> extends ServiceSupport implements Processor<E> { - private final Expression<E> expression; - private ProducerCache<E> producerCache = new ProducerCache<E>(); +public class RecipientList extends ServiceSupport implements Processor { + private final Expression<Exchange> expression; + private ProducerCache<Exchange> producerCache = new ProducerCache<Exchange>(); - public RecipientList(Expression<E> expression) { + public RecipientList(Expression<Exchange> expression) { notNull(expression, "expression"); this.expression = expression; } @@ -49,17 +49,17 @@ public String toString() { return "RecipientList[" + expression + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { Object receipientList = expression.evaluate(exchange); Iterator iter = ObjectConverter.iterator(receipientList); while (iter.hasNext()) { Object recipient = iter.next(); - Endpoint<E> endpoint = resolveEndpoint(exchange, recipient); + Endpoint<Exchange> endpoint = resolveEndpoint(exchange, recipient); producerCache.getProducer(endpoint).process(exchange); } } - protected Endpoint<E> resolveEndpoint(E exchange, Object recipient) { + protected Endpoint<Exchange> resolveEndpoint(Exchange exchange, Object recipient) { return ExchangeHelper.resolveEndpoint(exchange, recipient); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java index 6ec3d4556ea9a..1cb1ca0dc628e 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java @@ -27,11 +27,11 @@ /** * @version $Revision$ */ -public class SendProcessor<E extends Exchange> extends ServiceSupport implements Processor<E>, Service { - private Endpoint<E> destination; - private Producer<E> producer; +public class SendProcessor extends ServiceSupport implements Processor, Service { + private Endpoint destination; + private Producer producer; - public SendProcessor(Endpoint<E> destination) { + public SendProcessor(Endpoint destination) { this.destination = destination; } @@ -50,14 +50,14 @@ protected void doStart() throws Exception { this.producer = destination.createProducer(); } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { if (producer == null) { throw new IllegalStateException("No producer, this processor has not been started!"); } producer.process(exchange); } - public Endpoint<E> getDestination() { + public Endpoint getDestination() { return destination; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index a0e54632c50c4..4d33dc2125836 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -33,11 +33,11 @@ * * @version $Revision$ */ -public class Splitter<E extends Exchange> extends ServiceSupport implements Processor<E> { - private final Processor<E> processor; - private final Expression<E> expression; +public class Splitter extends ServiceSupport implements Processor { + private final Processor processor; + private final Expression expression; - public Splitter(Processor<E> destination, Expression<E> expression) { + public Splitter(Processor destination, Expression expression) { this.processor = destination; this.expression = expression; notNull(destination, "destination"); @@ -49,12 +49,12 @@ public String toString() { return "Splitter[on: " + expression + " to: " + processor + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { Object value = expression.evaluate(exchange); Iterator iter = ObjectConverter.iterator(value); while (iter.hasNext()) { Object part = iter.next(); - E newExchange = (E) exchange.copy(); + Exchange newExchange = exchange.copy(); newExchange.getIn().setBody(part); processor.process(newExchange); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java index 9188c05d74934..2ae777915cee2 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java @@ -32,13 +32,13 @@ * * @version $Revision: 1.1 $ */ -public class IdempotentConsumer<E extends Exchange> extends ServiceSupport implements Processor<E> { +public class IdempotentConsumer extends ServiceSupport implements Processor { private static final transient Log log = LogFactory.getLog(IdempotentConsumer.class); - private Expression<E> messageIdExpression; - private Processor<E> nextProcessor; + private Expression<Exchange> messageIdExpression; + private Processor nextProcessor; private MessageIdRepository messageIdRepository; - public IdempotentConsumer(Expression<E> messageIdExpression, MessageIdRepository messageIdRepository, Processor<E> nextProcessor) { + public IdempotentConsumer(Expression<Exchange> messageIdExpression, MessageIdRepository messageIdRepository, Processor nextProcessor) { this.messageIdExpression = messageIdExpression; this.messageIdRepository = messageIdRepository; this.nextProcessor = nextProcessor; @@ -49,7 +49,7 @@ public String toString() { return "IdempotentConsumer[expression=" + messageIdExpression + ", repository=" + messageIdRepository + ", processor=" + nextProcessor + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { String messageId = ExpressionHelper.evaluateAsString(messageIdExpression, exchange); if (messageId == null) { throw new NoMessageIdException(exchange, messageIdExpression); @@ -64,7 +64,7 @@ public void process(E exchange) throws Exception { // Properties //------------------------------------------------------------------------- - public Expression<E> getMessageIdExpression() { + public Expression<Exchange> getMessageIdExpression() { return messageIdExpression; } @@ -72,7 +72,7 @@ public MessageIdRepository getMessageIdRepository() { return messageIdRepository; } - public Processor<E> getNextProcessor() { + public Processor getNextProcessor() { return nextProcessor; } @@ -94,7 +94,7 @@ protected void doStop() throws Exception { * @param exchange the exchange * @param messageId the message ID of this exchange */ - protected void onDuplicateMessage(E exchange, String messageId) { + protected void onDuplicateMessage(Exchange exchange, String messageId) { if (log.isDebugEnabled()) { log.debug("Ignoring duplicate message with id: " + messageId + " for exchange: " + exchange); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java index 3592ec41df417..4bd4d3f748393 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java @@ -26,18 +26,18 @@ * * @version $Revision: 1.1 $ */ -public interface LoadBalancer<E extends Exchange> extends Processor<E> { +public interface LoadBalancer extends Processor { /** * Adds a new processor to the load balancer * * @param processor the processor to be added to the load balancer */ - void addProcessor(Processor<E> processor); + void addProcessor(Processor processor); /** * Removes the given processor from the load balancer * * @param processor the processor to be removed from the load balancer */ - void removeProcessor(Processor<E> processor); + void removeProcessor(Processor processor); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java index 2facdc99a82a3..525e60c00adf0 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java @@ -28,14 +28,14 @@ * * @version $Revision: 1.1 $ */ -public abstract class LoadBalancerSupport<E extends Exchange> implements LoadBalancer<E> { - private List<Processor<E>> processors = new CopyOnWriteArrayList<Processor<E>>(); +public abstract class LoadBalancerSupport implements LoadBalancer { + private List<Processor> processors = new CopyOnWriteArrayList<Processor>(); - public void addProcessor(Processor<E> processor) { + public void addProcessor(Processor processor) { processors.add(processor); } - public void removeProcessor(Processor<E> processor) { + public void removeProcessor(Processor processor) { processors.remove(processor); } @@ -44,7 +44,7 @@ public void removeProcessor(Processor<E> processor) { * * @return the processors available */ - public List<Processor<E>> getProcessors() { + public List<Processor> getProcessors() { return processors; } } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java index f6f81001ee3e9..4bef53263e700 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java @@ -28,14 +28,14 @@ * * @version $Revision: 1.1 $ */ -public abstract class QueueLoadBalancer<E extends Exchange> extends LoadBalancerSupport<E> { +public abstract class QueueLoadBalancer extends LoadBalancerSupport { - public void process(E exchange) throws Exception { - List<Processor<E>> list = getProcessors(); + public void process(Exchange exchange) throws Exception { + List<Processor> list = getProcessors(); if (list.isEmpty()) { throw new IllegalStateException("No processors available to process " + exchange); } - Processor<E> processor = chooseProcessor(list, exchange); + Processor processor = chooseProcessor(list, exchange); if (processor == null) { throw new IllegalStateException("No processors could be chosen to process " + exchange); } @@ -44,5 +44,5 @@ public void process(E exchange) throws Exception { } } - protected abstract Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange); + protected abstract Processor chooseProcessor(List<Processor> processors, Exchange exchange); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java index 5e29cb1766e65..b79f23cd169f6 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java @@ -27,9 +27,9 @@ * * @version $Revision: 1.1 $ */ -public class RandomLoadBalancer<E extends Exchange> extends QueueLoadBalancer<E> { +public class RandomLoadBalancer extends QueueLoadBalancer { - protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange) { + protected synchronized Processor chooseProcessor(List<Processor> processors, Exchange exchange) { int size = processors.size(); while (true) { int index = (int) Math.round(Math.random() * size); diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java index 3f5d0cc1d577f..edb6c85dce7f7 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java @@ -27,10 +27,10 @@ * * @version $Revision: 1.1 $ */ -public class RoundRobinLoadBalancer<E extends Exchange> extends QueueLoadBalancer<E> { +public class RoundRobinLoadBalancer extends QueueLoadBalancer { private int counter = -1; - protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange) { + protected synchronized Processor chooseProcessor(List<Processor> processors, Exchange exchange) { int size = processors.size(); if (++counter >= size) { counter = 0; diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java index 4861581b9d5d6..fe9b07f8f5f2b 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java @@ -34,26 +34,26 @@ * * @version $Revision: 1.1 $ */ -public class StickyLoadBalancer<E extends Exchange> extends QueueLoadBalancer<E> { - private Expression<E> correlationExpression; +public class StickyLoadBalancer extends QueueLoadBalancer { + private Expression<Exchange> correlationExpression; private QueueLoadBalancer loadBalancer; private int numberOfHashGroups = 64 * 1024; - private Map<Object, Processor<E>> stickyMap = new HashMap<Object, Processor<E>>(); + private Map<Object, Processor> stickyMap = new HashMap<Object, Processor>(); - public StickyLoadBalancer(Expression<E> correlationExpression) { + public StickyLoadBalancer(Expression<Exchange> correlationExpression) { this(correlationExpression, new RoundRobinLoadBalancer()); } - public StickyLoadBalancer(Expression<E> correlationExpression, QueueLoadBalancer loadBalancer) { + public StickyLoadBalancer(Expression<Exchange> correlationExpression, QueueLoadBalancer loadBalancer) { this.correlationExpression = correlationExpression; this.loadBalancer = loadBalancer; } - protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange) { + protected synchronized Processor chooseProcessor(List<Processor> processors, Exchange exchange) { Object value = correlationExpression.evaluate(exchange); Object key = getStickyKey(value); - Processor<E> processor; + Processor processor; synchronized (stickyMap) { processor = stickyMap.get(key); if (processor == null) { @@ -65,11 +65,11 @@ protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processor } @Override - public void removeProcessor(Processor<E> processor) { + public void removeProcessor(Processor processor) { synchronized (stickyMap) { - Iterator<Map.Entry<Object,Processor<E>>> iter = stickyMap.entrySet().iterator(); + Iterator<Map.Entry<Object,Processor>> iter = stickyMap.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry<Object, Processor<E>> entry = iter.next(); + Map.Entry<Object, Processor> entry = iter.next(); if (processor.equals(entry.getValue())) { iter.remove(); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java index c7243871044b7..af544b6fe33e1 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java @@ -28,11 +28,11 @@ * * @version $Revision: 1.1 $ */ -public class TopicLoadBalancer<E extends Exchange> extends LoadBalancerSupport<E> { - public void process(E exchange) throws Exception { - List<Processor<E>> list = getProcessors(); - for (Processor<E> processor : list) { - E copy = copyExchangeStrategy(processor, exchange); +public class TopicLoadBalancer extends LoadBalancerSupport { + public void process(Exchange exchange) throws Exception { + List<Processor> list = getProcessors(); + for (Processor processor : list) { + Exchange copy = copyExchangeStrategy(processor, exchange); processor.process(copy); } } @@ -44,7 +44,7 @@ public void process(E exchange) throws Exception { * @param processor the processor that will send the exchange * @param exchange @return the current exchange if no copying is required such as for a pipeline otherwise a new copy of the exchange is returned. */ - protected E copyExchangeStrategy(Processor<E> processor, E exchange) { - return (E) exchange.copy(); + protected Exchange copyExchangeStrategy(Processor processor, Exchange exchange) { + return exchange.copy(); } } diff --git a/camel-core/src/main/java/org/apache/camel/spi/Policy.java b/camel-core/src/main/java/org/apache/camel/spi/Policy.java index f9187da22b217..c240bece2fbf0 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/Policy.java +++ b/camel-core/src/main/java/org/apache/camel/spi/Policy.java @@ -33,5 +33,5 @@ public interface Policy<E> { * @param processor the processor to be intercepted * @return either the original processor or a processor wrapped in one or more interceptors */ - Processor<E> wrap(Processor<E> processor); + Processor wrap(Processor processor); } diff --git a/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java b/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java index 5df403ae2847c..eb6bcfbfebf51 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java +++ b/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java @@ -72,7 +72,7 @@ public void send(Endpoint<E> endpoint, E exchange) { * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange */ - public E send(Endpoint<E> endpoint, Processor<E> processor) { + public E send(Endpoint<E> endpoint, Processor processor) { try { Producer<E> producer = getProducer(endpoint); E exchange = producer.createExchange(); diff --git a/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java b/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java index 540d9dfa65336..5746cb8ecb753 100644 --- a/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java +++ b/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java @@ -70,7 +70,7 @@ protected Endpoint resolveMandatoryEndpoint(String uri) { * @param body the body for the message */ protected void send(String endpointUri, final Object body) { - client.send(endpointUri, new Processor<Exchange>() { + client.send(endpointUri, new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(body); diff --git a/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java b/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java index 76fb3848cd6bd..0bcb3844d3a7e 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java @@ -45,10 +45,10 @@ public void configure() { }; // END SNIPPET: e1 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 1, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); assertEquals("From endpoint", "queue:a", key.getEndpointUri()); Processor processor = route.getValue(); @@ -70,12 +70,12 @@ public void configure() { }; // END SNIPPET: e2 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); log.info(routeMap); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 2, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); String endpointUri = key.getEndpointUri(); Processor processor = route.getValue(); @@ -108,10 +108,10 @@ public void configure() { }; // END SNIPPET: e3 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 1, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); assertEquals("From endpoint", "queue:a", key.getEndpointUri()); Processor processor = route.getValue(); @@ -134,10 +134,10 @@ public void configure() { }; // END SNIPPET: e4 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 1, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); assertEquals("From endpoint", "queue:a", key.getEndpointUri()); Processor processor = route.getValue(); diff --git a/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java b/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java index ab2e9e23281d2..a04bb23e47792 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java @@ -41,7 +41,7 @@ public void testRouteWithInterceptor() throws Exception { CamelContext container = new DefaultCamelContext(); final ArrayList<String> order = new ArrayList<String>(); - final DelegateProcessor<Exchange> interceptor1 = new DelegateProcessor<Exchange>() { + final DelegateProcessor interceptor1 = new DelegateProcessor() { @Override public void process(Exchange exchange) throws Exception { order.add("START:1"); @@ -49,7 +49,7 @@ public void process(Exchange exchange) throws Exception { order.add("END:1"); } }; - final DelegateProcessor<Exchange> interceptor2 = new DelegateProcessor<Exchange>() { + final DelegateProcessor interceptor2 = new DelegateProcessor() { @Override public void process(Exchange exchange) throws Exception { order.add("START:2"); diff --git a/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java b/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java index 549bcfb6ac530..59b28da1e9594 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java +++ b/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java @@ -6,7 +6,7 @@ import org.apache.camel.Exchange; import org.apache.camel.processor.DelegateProcessor; -public class MyInterceptorProcessor extends DelegateProcessor<Exchange> { +public class MyInterceptorProcessor extends DelegateProcessor { public void process(Exchange exchange) throws Exception { System.out.println("START of onExchange: "+exchange); next.process(exchange); diff --git a/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java b/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java index d2c74b5931c09..c74a1fd7e59ec 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java +++ b/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java @@ -19,7 +19,7 @@ import org.apache.camel.Exchange; import org.apache.camel.Processor; -public class MyProcessor implements Processor<Exchange> { +public class MyProcessor implements Processor { public void process(Exchange exchange) { System.out.println("Called with exchange: " + exchange); } diff --git a/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java b/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java index cdbd9771776ff..3a2880025cf4f 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java @@ -41,9 +41,9 @@ * @version $Revision$ */ public class RouteBuilderTest extends TestSupport { - protected Processor<Exchange> myProcessor = new MyProcessor(); - protected DelegateProcessor<Exchange> interceptor1; - protected DelegateProcessor<Exchange> interceptor2; + protected Processor myProcessor = new MyProcessor(); + protected DelegateProcessor interceptor1; + protected DelegateProcessor interceptor2; protected RouteBuilder buildSimpleRoute() { // START SNIPPET: e1 @@ -142,7 +142,7 @@ public void testSimpleRouteWithChoice() throws Exception { protected RouteBuilder buildCustomProcessor() { // START SNIPPET: e4 - myProcessor = new Processor<Exchange>() { + myProcessor = new Processor() { public void process(Exchange exchange) { System.out.println("Called with exchange: " + exchange); } diff --git a/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java b/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java index fb6db3f71d052..34cbc7fa91665 100644 --- a/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java +++ b/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java @@ -44,7 +44,7 @@ public void testSedaQueue() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("direct:test.a").to("direct:test.b"); - from("direct:test.b").process(new Processor<Exchange>() { + from("direct:test.b").process(new Processor() { public void process(Exchange e) { invoked.set(true); } diff --git a/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java b/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java index fdb5124bd0b9d..7346cf11000c6 100644 --- a/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java +++ b/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java @@ -25,6 +25,7 @@ import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; import org.apache.commons.logging.Log; @@ -37,7 +38,7 @@ public class FileRouteTest extends TestCase { private static final transient Log log = LogFactory.getLog(FileRouteTest.class); protected CamelContext container = new DefaultCamelContext(); protected CountDownLatch latch = new CountDownLatch(1); - protected FileExchange receivedExchange; + protected Exchange receivedExchange; protected String uri = "file://foo.txt"; protected Producer<FileExchange> producer; @@ -77,8 +78,8 @@ protected void tearDown() throws Exception { protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { - from(uri).process(new Processor<FileExchange>() { - public void process(FileExchange e) { + from(uri).process(new Processor() { + public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); receivedExchange = e; latch.countDown(); diff --git a/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java b/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java index 7968fc69ef12c..1b1724ebdfdd0 100644 --- a/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java +++ b/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java @@ -45,7 +45,7 @@ public void testSedaQueue() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("queue:test.a").to("queue:test.b"); - from("queue:test.b").process(new Processor<Exchange>() { + from("queue:test.b").process(new Processor() { public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); latch.countDown(); @@ -82,7 +82,7 @@ public void xtestThatShowsEndpointResolutionIsNotConsistent() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("queue:test.a").to("queue:test.b"); - from("queue:test.b").process(new Processor<Exchange>() { + from("queue:test.b").process(new Processor() { public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); latch.countDown(); diff --git a/camel-core/src/test/java/org/apache/camel/impl/MyExchange.java b/camel-core/src/test/java/org/apache/camel/impl/MyExchange.java new file mode 100644 index 0000000000000..ac63167a0f8f4 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/impl/MyExchange.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.camel.impl; + +import org.apache.camel.CamelContext; + +/** + * @version $Revision: 1.1 $ + */ +public class MyExchange extends DefaultExchange { + + public MyExchange(CamelContext context) { + super(context); + } +} diff --git a/camel-core/src/test/java/org/apache/camel/impl/ProducerTest.java b/camel-core/src/test/java/org/apache/camel/impl/ProducerTest.java new file mode 100644 index 0000000000000..f3a985b198e7b --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/impl/ProducerTest.java @@ -0,0 +1,64 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.impl; + +import junit.framework.TestCase; +import org.apache.camel.TestSupport; +import org.apache.camel.Endpoint; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.Exchange; +import org.apache.camel.CamelContext; + +/** + * @version $Revision: 1.1 $ + */ +public class ProducerTest extends TestSupport { + private CamelContext context = new DefaultCamelContext(); + + public void testUsingADerivedExchange() throws Exception { + Endpoint<MyExchange> endpoint = new DefaultEndpoint<MyExchange>("foo", new DefaultComponent()) { + public Consumer<MyExchange> createConsumer(Processor processor) throws Exception { + return null; + } + + public MyExchange createExchange() { + return new MyExchange(getContext()); + } + + public Producer<MyExchange> createProducer() throws Exception { + return null; + } + + public boolean isSingleton() { + return false; + } + }; + + DefaultProducer producer = new DefaultProducer(endpoint) { + public void process(Exchange exchange) throws Exception { + log.info("Received: " + exchange); + } + }; + + // now lets try send in a normal exchange + Exchange exchange = new DefaultExchange(context); + producer.process(exchange); + } +} diff --git a/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java b/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java index 0c968bc6565a6..2fcdbed134c1c 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java @@ -62,7 +62,7 @@ public void testSendToOtherwiseClause() throws Exception { } protected void sendMessage(final Object headerValue, final Object body) throws Exception { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java b/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java index 9d99075e845fd..a7b22da775856 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java @@ -70,7 +70,7 @@ protected void setUp() throws Exception { } protected RouteBuilder createRouteBuilder() { - final Processor<Exchange> processor = new Processor<Exchange>() { + final Processor processor = new Processor() { public void process(Exchange exchange) { Integer counter = exchange.getIn().getHeader(DeadLetterChannel.REDELIVERY_COUNTER, Integer.class); int attempt = (counter == null) ? 1 : counter + 1; diff --git a/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java b/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java index e985b7986f5fb..94d8b480f8547 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java @@ -65,7 +65,7 @@ public void configure() { } protected void sendMessage(final Object headerValue, final Object body) throws Exception { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java b/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java index 3bdc047264b94..bef4b88aa1340 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java @@ -48,7 +48,7 @@ public void testDuplicateMessagesAreFilteredOut() throws Exception { } protected void sendMessage(final Object messageId, final Object body) { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java b/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java index 3136c11396d2f..063a3975ace83 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java @@ -42,7 +42,7 @@ public void testMessagesThroughDifferentRoutes() throws Exception { } protected void sendMessage(final Object headerValue, final Object body) throws Exception { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java b/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java index 6d3eb941781ee..52867cfdfd1a2 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java @@ -38,7 +38,7 @@ public void testSendingAMessageUsingMulticastReceivesItsOwnExchange() throws Exc y.expectedBodiesReceived("input+output"); z.expectedBodiesReceived("input+output"); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody("input"); @@ -59,7 +59,7 @@ protected void setUp() throws Exception { } protected RouteBuilder createRouteBuilder() { - final Processor<Exchange> processor = new Processor<Exchange>() { + final Processor processor = new Processor() { public void process(Exchange exchange) { // lets transform the IN message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java b/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java index 21d78657f3a9d..81069f259d22c 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java @@ -33,7 +33,7 @@ public class PipelineTest extends ContextTestSupport { public void testSendMessageThroughAPipeline() throws Exception { resultEndpoint.expectedBodiesReceived(4); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); @@ -53,7 +53,7 @@ protected void setUp() throws Exception { } protected RouteBuilder createRouteBuilder() { - final Processor<Exchange> processor = new Processor<Exchange>() { + final Processor processor = new Processor() { public void process(Exchange exchange) { Integer number = exchange.getIn().getBody(Integer.class); if (number == null) { diff --git a/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java b/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java index 029cd72539f69..0f6d31744261f 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java @@ -35,7 +35,7 @@ public void testSendingAMessageUsingMulticastReceivesItsOwnExchange() throws Exc y.expectedBodiesReceived("answer"); z.expectedBodiesReceived("answer"); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody("answer"); diff --git a/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java b/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java index 15c8668ec8246..5b4f45a821485 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java @@ -35,7 +35,7 @@ public class SplitterTest extends ContextTestSupport { public void testSendingAMessageUsingMulticastReceivesItsOwnExchange() throws Exception { resultEndpoint.expectedBodiesReceived("James", "Guillaume", "Hiram", "Rob"); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody("James,Guillaume,Hiram,Rob"); diff --git a/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java b/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java index 7e9be48c859a0..1db0f4ce4cdf9 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java @@ -49,7 +49,7 @@ protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: example - from("direct:start").process(new Processor<Exchange>() { + from("direct:start").process(new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(in.getBody(String.class) + " World!"); diff --git a/camel-cxf/pom.xml b/camel-cxf/pom.xml index f5fabc11b366f..2deaa7d2f57ea 100644 --- a/camel-cxf/pom.xml +++ b/camel-cxf/pom.xml @@ -167,6 +167,7 @@ </includes> <excludes> <!-- TODO re-enable ASAP! --> + <exclude>**/CxfInvokeTest.*</exclude> <exclude>**/CxfTest.*</exclude> <exclude>**/transport/*Test.*</exclude> </excludes> diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java index de882ddf06ce6..11e3640011009 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java @@ -34,7 +34,7 @@ public class CxfConsumer extends DefaultConsumer<CxfExchange> { private final LocalTransportFactory transportFactory; private Destination destination; - public CxfConsumer(CxfEndpoint endpoint, Processor<CxfExchange> processor, LocalTransportFactory transportFactory) { + public CxfConsumer(CxfEndpoint endpoint, Processor processor, LocalTransportFactory transportFactory) { super(endpoint, processor); this.endpoint = endpoint; this.transportFactory = transportFactory; diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java index 533a4ee306196..663fc9e06583e 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java @@ -47,7 +47,7 @@ public Producer<CxfExchange> createProducer() throws Exception { return startService(new CxfProducer(this, getLocalTransportFactory())); } - public Consumer<CxfExchange> createConsumer(Processor<CxfExchange> processor) throws Exception { + public Consumer<CxfExchange> createConsumer(Processor processor) throws Exception { return startService(new CxfConsumer(this, processor, getLocalTransportFactory())); } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java index ffbd2609442e1..aeea514ca4049 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java @@ -32,7 +32,7 @@ public class CxfInvokeConsumer extends DefaultConsumer<CxfExchange> { protected CxfInvokeEndpoint cxfEndpoint; private ServerImpl server; - public CxfInvokeConsumer(CxfInvokeEndpoint endpoint, Processor<CxfExchange> processor) { + public CxfInvokeConsumer(CxfInvokeEndpoint endpoint, Processor processor) { super(endpoint, processor); this.cxfEndpoint = endpoint; } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java index d06e91ff78af2..d767a05e78bd3 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java @@ -47,7 +47,7 @@ public Producer<CxfExchange> createProducer() throws Exception { return startService(new CxfInvokeProducer(this)); } - public Consumer<CxfExchange> createConsumer(Processor<CxfExchange> processor) throws Exception { + public Consumer<CxfExchange> createConsumer(Processor processor) throws Exception { return startService(new CxfInvokeConsumer(this, processor)); } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java index cfd73dbcf038b..7dfb4e80aa1b8 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.cxf; import org.apache.camel.RuntimeCamelException; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultProducer; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientFactoryBean; @@ -29,26 +30,31 @@ * * @version $Revision$ */ -public class CxfInvokeProducer extends DefaultProducer<CxfExchange> { - private CxfInvokeEndpoint cxfEndpoint; +public class CxfInvokeProducer extends DefaultProducer { + private CxfInvokeEndpoint endpoint; private Client client; public CxfInvokeProducer(CxfInvokeEndpoint endpoint) { super(endpoint); - cxfEndpoint = endpoint; + this.endpoint = endpoint; + } + + public void process(Exchange exchange) { + CxfExchange cxfExchange = endpoint.toExchangeType(exchange); + process(cxfExchange); } public void process(CxfExchange exchange) { List params = exchange.getIn().getBody(List.class); Object[] response = null; try { - response = client.invoke(cxfEndpoint.getProperty(CxfConstants.METHOD), params.toArray()); + response = client.invoke(endpoint.getProperty(CxfConstants.METHOD), params.toArray()); } catch (Exception e) { throw new RuntimeCamelException(e); } - CxfBinding binding = cxfEndpoint.getBinding(); + CxfBinding binding = endpoint.getBinding(); binding.storeCxfResponse(exchange, response); } @@ -61,8 +67,8 @@ protected void doStart() throws Exception { if (client == null) { ClientFactoryBean cfBean = new ClientFactoryBean(); cfBean.setAddress(getEndpoint().getEndpointUri()); - cfBean.setBus(cxfEndpoint.getBus()); - cfBean.setServiceClass(Class.forName(cxfEndpoint.getProperty(CxfConstants.SEI))); + cfBean.setBus(endpoint.getBus()); + cfBean.setServiceClass(Class.forName(endpoint.getProperty(CxfConstants.SEI))); client = cfBean.create(); } } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java index 89a1378681e36..5dd4beb8edf26 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.cxf; import org.apache.camel.RuntimeCamelException; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultProducer; import org.apache.cxf.message.ExchangeImpl; import org.apache.cxf.message.Message; @@ -37,7 +38,7 @@ * * @version $Revision$ */ -public class CxfProducer extends DefaultProducer<CxfExchange> { +public class CxfProducer extends DefaultProducer { private CxfEndpoint endpoint; private final LocalTransportFactory transportFactory; private Destination destination; @@ -50,6 +51,11 @@ public CxfProducer(CxfEndpoint endpoint, LocalTransportFactory transportFactory) this.transportFactory = transportFactory; } + public void process(Exchange exchange) { + CxfExchange cxfExchange = endpoint.toExchangeType(exchange); + process(cxfExchange); + } + public void process(CxfExchange exchange) { try { CxfBinding binding = endpoint.getBinding(); diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java index c244716c30bed..03c3f677fd486 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java @@ -142,7 +142,7 @@ protected void onWrite() throws IOException { } private void commitOutputMessage() { - base.client.send(targetCamelEndpointUri, new Processor<org.apache.camel.Exchange>() { + base.client.send(targetCamelEndpointUri, new Processor() { public void process(org.apache.camel.Exchange reply) { Object request = null; diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java index 90a9a7581dc32..ee6d3e4f60634 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java @@ -135,7 +135,7 @@ private void initConfig() { */ } - protected class ConsumerProcessor implements Processor<Exchange> { + protected class ConsumerProcessor implements Processor { public void process(Exchange exchange) { try { incoming(exchange); @@ -201,7 +201,7 @@ private void commitOutputMessage() throws IOException { //setup the reply message final String replyToUri = getReplyToDestination(inMessage); - base.client.send(replyToUri, new Processor<Exchange>() { + base.client.send(replyToUri, new Processor() { public void process(Exchange reply) { base.marshal(currentStream.toString(), replyToUri, reply); diff --git a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java index 79b5536813cba..fc020c4a73f22 100644 --- a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java +++ b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java @@ -23,6 +23,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Processor; import org.apache.camel.CamelClient; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultCamelContext; import org.apache.cxf.endpoint.ServerImpl; import org.apache.cxf.frontend.ServerFactoryBean; @@ -68,8 +69,8 @@ public void testInvokeOfServer() throws Exception { CxfExchange exchange = client.send(getUri(), - new Processor<CxfExchange>() { - public void process(final CxfExchange exchange) { + new Processor() { + public void process(final Exchange exchange) { final List<String> params = new ArrayList<String>(); params.add(testMessage); exchange.getIn().setBody(params); diff --git a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java index f6516053d9e60..78f83c6d0190a 100644 --- a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java +++ b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java @@ -85,8 +85,8 @@ public void testInvokeOfServer() throws Exception { CxfExchange exchange = (CxfExchange) client.send(getUri(), - new Processor<CxfExchange>() { - public void process(final CxfExchange exchange) { + new Processor() { + public void process(final Exchange exchange) { final List<String> params = new ArrayList<String>(); params.add(testMessage); exchange.getIn().setBody(params); diff --git a/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java b/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java index a2373e1309c87..da74634a71e33 100644 --- a/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java +++ b/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java @@ -23,6 +23,7 @@ import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.Consumer; +import org.apache.camel.Exchange; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -41,14 +42,14 @@ protected HttpEndpoint(String uri, HttpComponent component) { } public Producer<HttpExchange> createProducer() throws Exception { - return startService(new DefaultProducer<HttpExchange>(this) { - public void process(HttpExchange exchange) { + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) { /** TODO */ } }); } - public Consumer<HttpExchange> createConsumer(Processor<HttpExchange> processor) throws Exception { + public Consumer<HttpExchange> createConsumer(Processor processor) throws Exception { // TODO return startService(new DefaultConsumer<HttpExchange>(this, processor) {}); } diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java index 4234f6bcd0928..e341ad9ac0502 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java @@ -101,7 +101,7 @@ public CamelJbiEndpoint createEndpoint(ServiceEndpoint ep) throws URISyntaxExcep Map map = URISupport.parseQuery(uri.getQuery()); String camelUri = uri.getSchemeSpecificPart(); Endpoint camelEndpoint = getCamelContext().getEndpoint(camelUri); - Processor<Exchange> processor = null; + Processor processor = null; try { processor = camelEndpoint.createProducer(); } @@ -147,7 +147,7 @@ public ScheduledExecutorService getExecutorService() { /** * Returns a JBI endpoint created for the given Camel endpoint */ - public CamelJbiEndpoint activateJbiEndpoint(JbiEndpoint camelEndpoint, Processor<Exchange> processor) throws Exception { + public CamelJbiEndpoint activateJbiEndpoint(JbiEndpoint camelEndpoint, Processor processor) throws Exception { CamelJbiEndpoint jbiEndpoint; String endpointUri = camelEndpoint.getEndpointUri(); if (endpointUri.startsWith("endpoint:")) { diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java index e4db90b21710b..574da3c68f6f0 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java @@ -34,16 +34,16 @@ public class CamelJbiEndpoint extends ProviderEndpoint { private static final QName SERVICE_NAME = new QName("http://camel.apache.org/service", "CamelEndpointComponent"); private Endpoint camelEndpoint; private JbiBinding binding; - private Processor<Exchange> processor; + private Processor processor; - public CamelJbiEndpoint(ServiceUnit serviceUnit, QName service, String endpoint, Endpoint camelEndpoint, JbiBinding binding, Processor<Exchange> processor) { + public CamelJbiEndpoint(ServiceUnit serviceUnit, QName service, String endpoint, Endpoint camelEndpoint, JbiBinding binding, Processor processor) { super(serviceUnit, service, endpoint); this.processor = processor; this.camelEndpoint = camelEndpoint; this.binding = binding; } - public CamelJbiEndpoint(ServiceUnit serviceUnit, Endpoint camelEndpoint, JbiBinding binding, Processor<Exchange> processor) { + public CamelJbiEndpoint(ServiceUnit serviceUnit, Endpoint camelEndpoint, JbiBinding binding, Processor processor) { this(serviceUnit, SERVICE_NAME, camelEndpoint.getEndpointUri(), camelEndpoint, binding, processor); } diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java index de24d0c4b06b9..c28bd4bdb21b5 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java @@ -30,9 +30,9 @@ public class FromJbiProcessor implements MessageExchangeListener { private CamelContext context; private JbiBinding binding; - private Processor<JbiExchange> processor; + private Processor processor; - public FromJbiProcessor(CamelContext context, JbiBinding binding, Processor<JbiExchange> processor) { + public FromJbiProcessor(CamelContext context, JbiBinding binding, Processor processor) { this.context = context; this.binding = binding; this.processor = processor; diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java index c13d433874573..96ec222ad4130 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java @@ -32,7 +32,7 @@ * @version $Revision$ */ public class JbiEndpoint extends DefaultEndpoint<Exchange> { - private Processor<Exchange> toJbiProcessor; + private Processor toJbiProcessor; private final CamelJbiComponent jbiComponent; public JbiEndpoint(CamelJbiComponent jbiComponent, String uri) { @@ -49,7 +49,7 @@ public void process(Exchange exchange) throws Exception { }); } - public Consumer<Exchange> createConsumer(final Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(final Processor processor) throws Exception { return startService(new DefaultConsumer<Exchange>(this, processor) { CamelJbiEndpoint jbiEndpoint; diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java index 753a2156275f5..d7ed9bf10b7a0 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java @@ -32,7 +32,7 @@ * * @version $Revision$ */ -public class ToJbiProcessor implements Processor<Exchange> { +public class ToJbiProcessor implements Processor { private JbiBinding binding; private ComponentContext componentContext; private String destinationUri; diff --git a/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java b/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java index f0cad00366a9d..3fe66d2e4e41a 100644 --- a/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java +++ b/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java @@ -51,7 +51,7 @@ public abstract class JbiTestSupport extends TestSupport { * Sends an exchange to the endpoint */ protected void sendExchange(final Object expectedBody) { - client.send(endpoint, new Processor<Exchange>() { + client.send(endpoint, new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(expectedBody); diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java b/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java index 7aa16cd43d2f1..7a6c3b15d5518 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java @@ -35,10 +35,10 @@ public class EndpointMessageListener<E extends Exchange> implements MessageListener { private static final transient Log log = LogFactory.getLog(EndpointMessageListener.class); private Endpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; private JmsBinding binding; - public EndpointMessageListener(Endpoint<E> endpoint, Processor<E> processor) { + public EndpointMessageListener(Endpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java index dc847ad6140ed..5fe6f2d8b09e9 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java @@ -17,6 +17,8 @@ */ package org.apache.camel.component.jms; +import org.apache.camel.Exchange; + import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.MapMessage; @@ -77,33 +79,33 @@ else if (message instanceof BytesMessage || message instanceof StreamMessage) { * @return a newly created JMS Message instance containing the * @throws JMSException if the message could not be created */ - public Message makeJmsMessage(JmsMessage message, Session session) throws JMSException { - Message answer = createJmsMessage(message, session); - appendJmsProperties(answer, message, session); + public Message makeJmsMessage(Exchange exchange, Session session) throws JMSException { + Message answer = createJmsMessage(exchange.getIn().getBody(), session); + appendJmsProperties(answer, exchange, session); return answer; } /** * Appends the JMS headers from the Camel {@link JmsMessage} */ - protected void appendJmsProperties(Message jmsMessage, JmsMessage camelMessage, Session session) throws JMSException { - Set<Map.Entry<String, Object>> entries = camelMessage.getHeaders().entrySet(); + protected void appendJmsProperties(Message jmsMessage, Exchange exchange, Session session) throws JMSException { + org.apache.camel.Message in = exchange.getIn(); + Set<Map.Entry<String, Object>> entries = in.getHeaders().entrySet(); for (Map.Entry<String, Object> entry : entries) { String headerName = entry.getKey(); Object headerValue = entry.getValue(); - if (shouldOutputHeader(camelMessage, headerName, headerValue)) { + if (shouldOutputHeader(in, headerName, headerValue)) { jmsMessage.setObjectProperty(headerName, headerValue); } } } - protected Message createJmsMessage(JmsMessage message, Session session) throws JMSException { - Object value = message.getBody(); - if (value instanceof String) { - return session.createTextMessage((String) value); + protected Message createJmsMessage(Object body, Session session) throws JMSException { + if (body instanceof String) { + return session.createTextMessage((String) body); } - else if (value instanceof Serializable) { - return session.createObjectMessage((Serializable) value); + else if (body instanceof Serializable) { + return session.createObjectMessage((Serializable) body); } else { return session.createMessage(); @@ -127,7 +129,7 @@ public Map<String, Object> createMapFromMapMessage(MapMessage message) throws JM /** * Strategy to allow filtering of headers which are put on the JMS message */ - protected boolean shouldOutputHeader(JmsMessage camelMessage, String headerName, Object headerValue) { + protected boolean shouldOutputHeader(org.apache.camel.Message camelMessage, String headerName, Object headerValue) { return true; } } diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java index 4a3e9580496fd..340b3b6c34b2a 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java @@ -32,7 +32,7 @@ public class JmsConsumer extends DefaultConsumer<JmsExchange> { private final AbstractMessageListenerContainer listenerContainer; - public JmsConsumer(JmsEndpoint endpoint, Processor<JmsExchange> processor, AbstractMessageListenerContainer listenerContainer) { + public JmsConsumer(JmsEndpoint endpoint, Processor processor, AbstractMessageListenerContainer listenerContainer) { super(endpoint, processor); this.listenerContainer = listenerContainer; @@ -40,7 +40,7 @@ public JmsConsumer(JmsEndpoint endpoint, Processor<JmsExchange> processor, Abstr this.listenerContainer.setMessageListener(messageListener); } - protected MessageListener createMessageListener(JmsEndpoint endpoint, Processor<JmsExchange> processor) { + protected MessageListener createMessageListener(JmsEndpoint endpoint, Processor processor) { EndpointMessageListener<JmsExchange> messageListener = new EndpointMessageListener<JmsExchange>(endpoint, processor); messageListener.setBinding(endpoint.getBinding()); return messageListener; diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java index e76b0b638a744..ace0f81a619cc 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java @@ -60,7 +60,7 @@ public Producer<JmsExchange> createProducer(JmsOperations template) throws Excep return startService(new JmsProducer(this, template)); } - public Consumer<JmsExchange> createConsumer(Processor<JmsExchange> processor) throws Exception { + public Consumer<JmsExchange> createConsumer(Processor processor) throws Exception { AbstractMessageListenerContainer listenerContainer = configuration.createMessageListenerContainer(); return createConsumer(processor, listenerContainer); } @@ -73,7 +73,7 @@ public Consumer<JmsExchange> createConsumer(Processor<JmsExchange> processor) th * @return a newly created consumer * @throws Exception if the consumer cannot be created */ - public Consumer<JmsExchange> createConsumer(Processor<JmsExchange> processor, AbstractMessageListenerContainer listenerContainer) throws Exception { + public Consumer<JmsExchange> createConsumer(Processor processor, AbstractMessageListenerContainer listenerContainer) throws Exception { listenerContainer.setDestinationName(destination); listenerContainer.setPubSubDomain(pubSubDomain); if (selector != null) { diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java index 4bbdbfb262a76..2d4d7b54f2c25 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java @@ -31,7 +31,7 @@ /** * @version $Revision$ */ -public class JmsProducer extends DefaultProducer<JmsExchange> { +public class JmsProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(JmsProducer.class); private final JmsEndpoint endpoint; private final JmsOperations template; @@ -42,10 +42,10 @@ public JmsProducer(JmsEndpoint endpoint, JmsOperations template) { this.template = template; } - public void process(final JmsExchange exchange) { + public void process(final Exchange exchange) { template.send(endpoint.getDestination(), new MessageCreator() { public Message createMessage(Session session) throws JMSException { - Message message = endpoint.getBinding().makeJmsMessage(exchange.getIn(), session); + Message message = endpoint.getBinding().makeJmsMessage(exchange, session); if (log.isDebugEnabled()) { log.debug(endpoint + " sending JMS message: " + message); } diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java b/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java index 2ac2afff13436..5843fe951d83d 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java @@ -32,9 +32,9 @@ */ public class MessageListenerProcessor implements MessageListener { private final JmsEndpoint endpoint; - private final Processor<Exchange> processor; + private final Processor processor; - public MessageListenerProcessor(JmsEndpoint endpoint, Processor<Exchange> processor) { + public MessageListenerProcessor(JmsEndpoint endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } diff --git a/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java b/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java index d40b12761bc6d..9eaf26bc80996 100644 --- a/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java +++ b/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java @@ -22,6 +22,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; import org.apache.camel.impl.DefaultCamelContext; @@ -65,12 +66,11 @@ public void testJmsRouteWithObjectMessage() throws Exception { } protected void sendExchange(final Object expectedBody) { - client.send(endpoint, new Processor<JmsExchange>() { - public void process(JmsExchange exchange) { + client.send(endpoint, new Processor() { + public void process(Exchange exchange) { // now lets fire in a message - JmsMessage in = exchange.getIn(); - in.setBody(expectedBody); - in.setHeader("cheese", 123); + exchange.getIn().setBody(expectedBody); + exchange.getIn().setHeader("cheese", 123); } }); } @@ -103,10 +103,10 @@ protected void setUp() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("activemq:queue:test.a").to("activemq:queue:test.b"); - from("activemq:queue:test.b").process(new Processor<JmsExchange>() { - public void process(JmsExchange e) { + from("activemq:queue:test.b").process(new Processor() { + public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); - receivedExchange = e; + receivedExchange = (JmsExchange) e; latch.countDown(); } }); diff --git a/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java b/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java index f02104294f47f..78e6a98784582 100644 --- a/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java +++ b/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java @@ -28,6 +28,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.ContextTestSupport; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.processor.DelegateProcessor; @@ -66,7 +67,7 @@ public void configure() { public Processor wrap(Processor processor) { return new DelegateProcessor(processor) { @Override - public void process(Object exchange) throws Exception { + public void process(Exchange exchange) throws Exception { processNext(exchange); throw new RuntimeException("rollback"); } @@ -83,7 +84,7 @@ public String toString() { public Processor wrap(Processor processor) { return new DelegateProcessor(processor) { @Override - public void process(Object exchange) { + public void process(Exchange exchange) { try { processNext(exchange); } catch ( Throwable e ) { diff --git a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java index ae81dc2f7837c..824211564d940 100644 --- a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java +++ b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java @@ -47,7 +47,7 @@ public class JpaConsumer extends PollingConsumer<Exchange> { private String namedQuery; private String nativeQuery; - public JpaConsumer(JpaEndpoint endpoint, Processor<Exchange> processor) { + public JpaConsumer(JpaEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; this.template = endpoint.createTransactionStrategy(); diff --git a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java index cbd7b175730be..68cb4680954ab 100644 --- a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java +++ b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java @@ -60,7 +60,7 @@ public Producer<Exchange> createProducer() throws Exception { return startService(new JpaProducer(this, getProducerExpression())); } - public Consumer<Exchange> createConsumer(Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(Processor processor) throws Exception { JpaConsumer consumer = new JpaConsumer(this, processor); configureConsumer(consumer); return startService(consumer); diff --git a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java index 3e410c61e3f16..351cb334c143c 100644 --- a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java +++ b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java @@ -68,7 +68,7 @@ public Object doInJpa(EntityManager entityManager) throws PersistenceException { assertEquals("Should have no results: " + results, 0, results.size()); // lets produce some objects - client.send(endpoint, new Processor<Exchange>() { + client.send(endpoint, new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody(new SendEmail("[email protected]")); } @@ -81,7 +81,7 @@ public void process(Exchange exchange) { assertEquals("address property", "[email protected]", mail.getAddress()); // now lets create a consumer to consume it - consumer = endpoint.createConsumer(new Processor<Exchange>() { + consumer = endpoint.createConsumer(new Processor() { public void process(Exchange e) { log.info("Received exchange: " + e.getIn()); receivedExchange = e; diff --git a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java index f951d4f222be2..459d1c2f72199 100644 --- a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java +++ b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java @@ -72,7 +72,7 @@ public Object doInJpa(EntityManager entityManager) throws PersistenceException { assertEquals("Should have no results: " + results, 0, results.size()); // lets produce some objects - client.send(endpoint, new Processor<Exchange>() { + client.send(endpoint, new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody(new MultiSteps("[email protected]")); } @@ -85,7 +85,7 @@ public void process(Exchange exchange) { assertEquals("address property", "[email protected]", mail.getAddress()); // now lets create a consumer to consume it - consumer = endpoint.createConsumer(new Processor<Exchange>() { + consumer = endpoint.createConsumer(new Processor() { public void process(Exchange e) { log.info("Received exchange: " + e.getIn()); receivedExchange = e; diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java index c2b110a264aa0..96ab82165d8bf 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java @@ -17,6 +17,8 @@ */ package org.apache.camel.component.mail; +import org.apache.camel.Exchange; + import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Address; @@ -32,7 +34,7 @@ * @version $Revision: 521240 $ */ public class MailBinding { - public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, MailExchange exchange) { + public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, Exchange exchange) { try { appendMailHeaders(mimeMessage, exchange.getIn()); @@ -75,7 +77,7 @@ public Object extractBodyFromMail(MailExchange exchange, Message message) { /** * Appends the Mail headers from the Camel {@link MailMessage} */ - protected void appendMailHeaders(MimeMessage mimeMessage, MailMessage camelMessage) throws MessagingException { + protected void appendMailHeaders(MimeMessage mimeMessage, org.apache.camel.Message camelMessage) throws MessagingException { Set<Map.Entry<String, Object>> entries = camelMessage.getHeaders().entrySet(); for (Map.Entry<String, Object> entry : entries) { String headerName = entry.getKey(); @@ -91,7 +93,7 @@ protected void appendMailHeaders(MimeMessage mimeMessage, MailMessage camelMessa /** * Strategy to allow filtering of headers which are put on the Mail message */ - protected boolean shouldOutputHeader(MailMessage camelMessage, String headerName, Object headerValue) { + protected boolean shouldOutputHeader(org.apache.camel.Message camelMessage, String headerName, Object headerValue) { return true; } } diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java index 76f773a51d445..b7dcbdfe4f97c 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java @@ -42,7 +42,7 @@ public class MailConsumer extends PollingConsumer<MailExchange> implements Messa private final MailEndpoint endpoint; private final Folder folder; - public MailConsumer(MailEndpoint endpoint, Processor<MailExchange> processor, Folder folder) { + public MailConsumer(MailEndpoint endpoint, Processor processor, Folder folder) { super(endpoint, processor); this.endpoint = endpoint; this.folder = folder; diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java index a63eb93fdb20f..5e7a4caaa7b18 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java @@ -51,7 +51,7 @@ public Producer<MailExchange> createProducer(JavaMailSender sender) throws Excep return startService(new MailProducer(this, sender)); } - public Consumer<MailExchange> createConsumer(Processor<MailExchange> processor) throws Exception { + public Consumer<MailExchange> createConsumer(Processor processor) throws Exception { JavaMailConnection connection = configuration.createJavaMailConnection(this); String protocol = getConfiguration().getProtocol(); if (protocol.equals("smtp")) { @@ -73,7 +73,7 @@ public Consumer<MailExchange> createConsumer(Processor<MailExchange> processor) * @return a newly created consumer * @throws Exception if the consumer cannot be created */ - public Consumer<MailExchange> createConsumer(Processor<MailExchange> processor, Folder folder) throws Exception { + public Consumer<MailExchange> createConsumer(Processor processor, Folder folder) throws Exception { MailConsumer answer = new MailConsumer(this, processor, folder); configureConsumer(answer); return startService(answer); diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java index d87bb7791e30c..a4041de14c546 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.mail; import org.apache.camel.impl.DefaultProducer; +import org.apache.camel.Exchange; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.mail.javamail.JavaMailSender; @@ -40,7 +41,7 @@ public MailProducer(MailEndpoint endpoint, JavaMailSender sender) { } - public void process(final MailExchange exchange) { + public void process(final Exchange exchange) { sender.send(new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { endpoint.getBinding().populateMailMessage(endpoint, mimeMessage, exchange); diff --git a/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java b/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java index dd24dc914f238..f228de184a1b0 100644 --- a/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java +++ b/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java @@ -41,7 +41,7 @@ public void testSendAndReceiveMails() throws Exception { resultEndpoint = (MockEndpoint) resolveMandatoryEndpoint("mock:result"); resultEndpoint.expectedBodiesReceived("hello world!"); - client.send("smtp://james@localhost", new Processor<Exchange>() { + client.send("smtp://james@localhost", new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("hello world!"); } diff --git a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java index 4b1787f175aee..0add4f5dffb5f 100644 --- a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java +++ b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java @@ -40,7 +40,7 @@ public class MinaConsumer extends DefaultConsumer<MinaExchange> { private final SocketAddress address; private final IoAcceptor acceptor; - public MinaConsumer(final MinaEndpoint endpoint, Processor<MinaExchange> processor) { + public MinaConsumer(final MinaEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; address = endpoint.getAddress(); diff --git a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java index aed1262ac63e0..a81d540cad95c 100644 --- a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java +++ b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java @@ -53,7 +53,7 @@ public Producer<MinaExchange> createProducer() throws Exception { return startService(new MinaProducer(this)); } - public Consumer<MinaExchange> createConsumer(Processor<MinaExchange> processor) throws Exception { + public Consumer<MinaExchange> createConsumer(Processor processor) throws Exception { return startService(new MinaConsumer(this, processor)); } diff --git a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java index edbd27540db26..a356241f1d3b1 100644 --- a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java +++ b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.mina; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultProducer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -34,7 +35,7 @@ * * @version $Revision$ */ -public class MinaProducer extends DefaultProducer<MinaExchange> { +public class MinaProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(MinaProducer.class); private IoSession session; private MinaEndpoint endpoint; @@ -44,7 +45,7 @@ public MinaProducer(MinaEndpoint endpoint) { this.endpoint = endpoint; } - public void process(MinaExchange exchange) { + public void process(Exchange exchange) { if (session == null) { throw new IllegalStateException("Not started yet!"); } diff --git a/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java b/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java index 36d7d298e8c2c..f1bc92e836b63 100644 --- a/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java +++ b/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java @@ -23,6 +23,7 @@ import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; @@ -35,7 +36,7 @@ public class MinaVmTest extends TestCase { protected CamelContext container = new DefaultCamelContext(); protected CountDownLatch latch = new CountDownLatch(1); - protected MinaExchange receivedExchange; + protected Exchange receivedExchange; protected String uri = "mina:vm://localhost:8080"; protected Producer<MinaExchange> producer; @@ -74,8 +75,8 @@ protected void tearDown() throws Exception { protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { - from(uri).process(new Processor<MinaExchange>() { - public void process(MinaExchange e) { + from(uri).process(new Processor() { + public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); receivedExchange = e; latch.countDown(); diff --git a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java index 6a67589784660..dd5760b074c05 100644 --- a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java +++ b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java @@ -42,7 +42,7 @@ public class RmiConsumer extends DefaultConsumer<PojoExchange> implements Invoca private Remote stub; private Remote proxy; - public RmiConsumer(RmiEndpoint endpoint, Processor<PojoExchange> processor) { + public RmiConsumer(RmiEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; diff --git a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java index e39c1d3bdeb0b..df9065b3610ff 100644 --- a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java +++ b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java @@ -54,7 +54,7 @@ public PojoExchange createExchange() { return new PojoExchange(getContext()); } - public Consumer<PojoExchange> createConsumer(Processor<PojoExchange> processor) throws Exception { + public Consumer<PojoExchange> createConsumer(Processor processor) throws Exception { if( remoteInterfaces == null || remoteInterfaces.size()==0 ) throw new RuntimeCamelException("To create an RMI consumer, the RMI endpoint's remoteInterfaces property must be be configured."); return new RmiConsumer(this, processor); diff --git a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java index 7c045b66e82e9..fad7d954d96ef 100644 --- a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java +++ b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java @@ -26,11 +26,12 @@ import org.apache.camel.component.pojo.PojoEndpoint; import org.apache.camel.component.pojo.PojoExchange; import org.apache.camel.impl.DefaultProducer; +import org.apache.camel.Exchange; /** * @version $Revision: 533076 $ */ -public class RmiProducer extends DefaultProducer<PojoExchange> { +public class RmiProducer extends DefaultProducer { private final RmiEndpoint endpoint; private Remote remote; @@ -40,9 +41,9 @@ public RmiProducer(RmiEndpoint endpoint) throws AccessException, RemoteException this.endpoint = endpoint; } - public void process(PojoExchange exchange) throws AccessException, RemoteException, NotBoundException { - - PojoEndpoint.invoke(getRemote(), exchange); + public void process(Exchange exchange) throws AccessException, RemoteException, NotBoundException { + PojoExchange pojoExchange = endpoint.toExchangeType(exchange); + PojoEndpoint.invoke(getRemote(), pojoExchange); } public Remote getRemote() throws AccessException, RemoteException, NotBoundException { diff --git a/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java b/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java index 9a08f62c0d7dc..c42511168a1e1 100644 --- a/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java +++ b/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java @@ -43,7 +43,7 @@ * * @version $Revision$ */ -public class ScriptBuilder<E extends Exchange> implements Expression<E>, Predicate<E>, Processor<E> { +public class ScriptBuilder<E extends Exchange> implements Expression<E>, Predicate<E>, Processor { private String scriptEngineName; private Resource scriptResource; private String scriptText; @@ -81,7 +81,7 @@ public void assertMatches(String text, E exchange) throws AssertionError { } } - public void process(E exchange) { + public void process(Exchange exchange) { evaluateScript(exchange); } diff --git a/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java b/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java index 90e12f4e8649c..9c79aeebc55f5 100644 --- a/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java +++ b/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java @@ -19,6 +19,7 @@ import org.apache.camel.Processor; import org.apache.camel.RuntimeCamelException; +import org.apache.camel.Exchange; import org.apache.camel.processor.DelegateProcessor; import org.apache.camel.spi.Policy; import org.apache.commons.logging.Log; @@ -45,16 +46,16 @@ public SpringTransactionPolicy(TransactionTemplate template) { this.template = template; } - public Processor<E> wrap(Processor<E> processor) { + public Processor wrap(Processor processor) { final TransactionTemplate transactionTemplate = getTemplate(); if (transactionTemplate == null) { log.warn("No TransactionTemplate available so transactions will not be enabled!"); return processor; } - return new DelegateProcessor<E>(processor) { + return new DelegateProcessor(processor) { - public void process(final E exchange) { + public void process(final Exchange exchange) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { diff --git a/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java b/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java index c17b6fb39dd78..87d09af197854 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java @@ -44,7 +44,7 @@ public void testXMLRouteLoading() throws Exception { // now lets send a message CamelClient<Exchange> client = new CamelClient<Exchange>(context); - client.send("direct:start", new Processor<Exchange>() { + client.send("direct:start", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setHeader("name", "James"); diff --git a/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java b/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java index f702073b2f9fe..771395d19bdea 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java @@ -47,7 +47,7 @@ public void testXMLRouteLoading() throws Exception { // now lets send a message CamelClient<Exchange> client = new CamelClient<Exchange>(context); - client.send("queue:start", new Processor<Exchange>() { + client.send("queue:start", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setHeader("name", "James"); diff --git a/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java b/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java index 4e472e85e4dbd..16c4e3d9637ab 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java @@ -26,7 +26,7 @@ /** * @version $Revision: 1.1 $ */ -public class MyProcessor implements Processor<Exchange> { +public class MyProcessor implements Processor { private static List exchanges = new CopyOnWriteArrayList(); private String name = "James"; diff --git a/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java b/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java index f7ec8dcf3efb5..b3332507f3c05 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java @@ -54,7 +54,7 @@ protected RouteBuilder buildSimpleRoute() { @Override protected RouteBuilder buildCustomProcessor() { - myProcessor = (Processor<Exchange>) ctx.getBean("myProcessor"); + myProcessor = (Processor) ctx.getBean("myProcessor"); RouteBuilder builder = (RouteBuilder) ctx.getBean("buildCustomProcessor"); assertNotNull(builder); return builder; @@ -62,7 +62,7 @@ protected RouteBuilder buildCustomProcessor() { @Override protected RouteBuilder buildCustomProcessorWithFilter() { - myProcessor = (Processor<Exchange>) ctx.getBean("myProcessor"); + myProcessor = (Processor) ctx.getBean("myProcessor"); RouteBuilder builder = (RouteBuilder) ctx.getBean("buildCustomProcessorWithFilter"); assertNotNull(builder); return builder; @@ -70,8 +70,8 @@ protected RouteBuilder buildCustomProcessorWithFilter() { @Override protected RouteBuilder buildRouteWithInterceptor() { - interceptor1 = (DelegateProcessor<Exchange>) ctx.getBean("interceptor1"); - interceptor2 = (DelegateProcessor<Exchange>) ctx.getBean("interceptor2"); + interceptor1 = (DelegateProcessor) ctx.getBean("interceptor1"); + interceptor2 = (DelegateProcessor) ctx.getBean("interceptor2"); RouteBuilder builder = (RouteBuilder) ctx.getBean("buildRouteWithInterceptor"); assertNotNull(builder); return builder; diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java index 10388b0bb58c2..256c1c86e3be7 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java @@ -18,6 +18,7 @@ package org.apache.camel.component.xmpp; import org.jivesoftware.smack.packet.Message; +import org.apache.camel.Exchange; import java.util.Map; import java.util.Set; @@ -32,7 +33,7 @@ public class XmppBinding { /** * Populates the given XMPP message from the inbound exchange */ - public void populateXmppMessage(Message message, XmppExchange exchange) { + public void populateXmppMessage(Message message, Exchange exchange) { message.setBody(exchange.getIn().getBody(String.class)); Set<Map.Entry<String, Object>> entries = exchange.getIn().getHeaders().entrySet(); @@ -62,7 +63,7 @@ public Object extractBodyFromXmpp(XmppExchange exchange, Message message) { /** * Strategy to allow filtering of headers which are put on the XMPP message */ - protected boolean shouldOutputHeader(XmppExchange exchange, String headerName, Object headerValue) { + protected boolean shouldOutputHeader(Exchange exchange, String headerName, Object headerValue) { return true; } } diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java index 0d8e0595474e9..b64ab4d07305e 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java @@ -38,7 +38,7 @@ public class XmppConsumer extends DefaultConsumer<XmppExchange> implements Packe private static final transient Log log = LogFactory.getLog(XmppConsumer.class); private final XmppEndpoint endpoint; - public XmppConsumer(XmppEndpoint endpoint, Processor<XmppExchange> processor) { + public XmppConsumer(XmppEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java index a9b764d11f824..0addf3b1ff5c7 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java @@ -75,7 +75,7 @@ public Producer<XmppExchange> createPrivateChatProducer(String participant) thro return startService(new XmppPrivateChatProducer(this, participant)); } - public Consumer<XmppExchange> createConsumer(Processor<XmppExchange> processor) throws Exception { + public Consumer<XmppExchange> createConsumer(Processor processor) throws Exception { return startService(new XmppConsumer(this, processor)); } diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java index 705e950e1043e..604a38c146b02 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java @@ -28,7 +28,7 @@ /** * @version $Revision$ */ -public class XmppGroupChatProducer extends DefaultProducer<XmppExchange> { +public class XmppGroupChatProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(XmppGroupChatProducer.class); private final XmppEndpoint endpoint; private final String room; @@ -43,13 +43,7 @@ public XmppGroupChatProducer(XmppEndpoint endpoint, String room) { } } - public void onExchange(Exchange exchange) { - // lets convert to the type of an exchange - XmppExchange xmppExchange = endpoint.convertTo(XmppExchange.class, exchange); - process(xmppExchange); - } - - public void process(XmppExchange exchange) { + public void process(Exchange exchange) { // TODO it would be nice if we could reuse the message from the exchange Message message = chat.createMessage(); message.setTo(room); diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java index 0e4a60a094a7a..f4377fb3e9f9c 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java @@ -28,7 +28,7 @@ /** * @version $Revision$ */ -public class XmppPrivateChatProducer extends DefaultProducer<XmppExchange> { +public class XmppPrivateChatProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(XmppPrivateChatProducer.class); private final XmppEndpoint endpoint; private final String participant; @@ -43,13 +43,7 @@ public XmppPrivateChatProducer(XmppEndpoint endpoint, String participant) { } } - public void onExchange(Exchange exchange) { - // lets convert to the type of an exchange - XmppExchange xmppExchange = endpoint.convertTo(XmppExchange.class, exchange); - process(xmppExchange); - } - - public void process(XmppExchange exchange) { + public void process(Exchange exchange) { // TODO it would be nice if we could reuse the message from the exchange Message message = chat.createMessage(); message.setTo(participant); diff --git a/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java b/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java index 9cc085e0cc2d6..71a06d21bbc53 100644 --- a/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java +++ b/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java @@ -23,6 +23,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.converter.ObjectConverter; import org.apache.camel.impl.DefaultCamelContext; @@ -80,12 +81,11 @@ protected static boolean isXmppServerPresent() { } protected void sendExchange(final Object expectedBody) { - client.send(endpoint, new Processor<XmppExchange>() { - public void process(XmppExchange exchange) { + client.send(endpoint, new Processor() { + public void process(Exchange exchange) { // now lets fire in a message - XmppMessage in = exchange.getIn(); - in.setBody(expectedBody); - in.setHeader("cheese", 123); + exchange.getIn().setBody(expectedBody); + exchange.getIn().setHeader("cheese", 123); } }); } @@ -120,10 +120,10 @@ protected void setUp() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from(uri1).to(uri2); - from(uri2).process(new Processor<XmppExchange>() { - public void process(XmppExchange e) { + from(uri2).process(new Processor() { + public void process(Exchange e) { log.info("Received exchange: " + e); - receivedExchange = e; + receivedExchange = (XmppExchange) e; latch.countDown(); } });
36f77aa32cbf76057b0f55be6e31711efb418412
camel
CAMEL-3114: Fixed rss component bug with uri- encoding.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@998608 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/components/camel-rss/src/main/java/org/apache/camel/component/rss/RssComponent.java b/components/camel-rss/src/main/java/org/apache/camel/component/rss/RssComponent.java index 3f4c2a6a1626c..fbd870091ce85 100644 --- a/components/camel-rss/src/main/java/org/apache/camel/component/rss/RssComponent.java +++ b/components/camel-rss/src/main/java/org/apache/camel/component/rss/RssComponent.java @@ -16,13 +16,12 @@ */ package org.apache.camel.component.rss; -import java.net.URI; +import java.util.LinkedHashMap; import java.util.Map; import org.apache.camel.Endpoint; import org.apache.camel.component.feed.FeedComponent; import org.apache.camel.component.feed.FeedEndpoint; -import org.apache.camel.util.CastUtils; import org.apache.camel.util.URISupport; /** @@ -48,8 +47,9 @@ protected void afterConfiguration(String uri, String remaining, Endpoint endpoin // for the http feed String feedUri; if (!parameters.isEmpty()) { - URI remainingUri = URISupport.createRemainingURI(new URI(remaining), CastUtils.cast(parameters)); - feedUri = remainingUri.toString(); + Map<Object, Object> options = new LinkedHashMap<Object, Object>(parameters); + String query = URISupport.createQueryString(options); + feedUri = remaining + "?" + query; } else { feedUri = remaining; } diff --git a/components/camel-rss/src/test/java/org/apache/camel/component/rss/RssUriEncodingIssueTest.java b/components/camel-rss/src/test/java/org/apache/camel/component/rss/RssUriEncodingIssueTest.java new file mode 100644 index 0000000000000..2351a148b1775 --- /dev/null +++ b/components/camel-rss/src/test/java/org/apache/camel/component/rss/RssUriEncodingIssueTest.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.camel.component.rss; + +import org.apache.camel.Exchange; +import org.apache.camel.PollingConsumer; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Ignore; +import org.junit.Test; + +/** + * @version $Revision$ + */ +@Ignore("Must be online") +public class RssUriEncodingIssueTest extends CamelTestSupport { + + @Test + public void testUriIssue() throws Exception { + String uri = "rss:http://api.flickr.com/services/feeds/photos_public.gne?id=23353282@N05&tags=lowlands&lang=en-us&format=rss_200"; + + PollingConsumer consumer = context.getEndpoint(uri).createPollingConsumer(); + consumer.start(); + Exchange exchange = consumer.receive(); + log.info("Receive " + exchange); + assertNotNull(exchange); + assertNotNull(exchange.getIn().getBody()); + consumer.stop(); + } + +}
a6fa02a07fe374204e9e02914ccf1cc9812aa5ba
restlet-framework-java
- Initial code for new default HTTP connector and- SIP connector.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java index 8631b810ca..a0b89ae9c7 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java @@ -1037,10 +1037,12 @@ public void writeMessages() { } } - writeMessage(message); + if (message != null) { + writeMessage(message); - if (getState() == ConnectionState.CLOSING) { - close(true); + if (getState() == ConnectionState.CLOSING) { + close(true); + } } } } catch (Exception e) {
265e2fb8bcfede045d213568f157873abcf445b4
elasticsearch
zen disco: support for a node to act as a client- (and not become master) using discovery.zen.master setting (default to true).- It will automatically be set to false when node.client is set to true.--
a
https://github.com/elastic/elasticsearch
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java index 0b3aef49fb16c..7f4bfb676c59f 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java @@ -20,21 +20,45 @@ package org.elasticsearch.cluster.node; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; import org.apache.lucene.util.StringHelper; import org.elasticsearch.util.io.stream.StreamInput; import org.elasticsearch.util.io.stream.StreamOutput; import org.elasticsearch.util.io.stream.Streamable; +import org.elasticsearch.util.settings.Settings; import org.elasticsearch.util.transport.TransportAddress; import org.elasticsearch.util.transport.TransportAddressSerializers; import java.io.IOException; import java.io.Serializable; +import java.util.Map; + +import static org.elasticsearch.util.transport.TransportAddressSerializers.*; /** - * @author kimchy (Shay Banon) + * @author kimchy (shay.banon) */ public class DiscoveryNode implements Streamable, Serializable { + public static Map<String, String> buildCommonNodesAttributes(Settings settings) { + Map<String, String> attributes = Maps.newHashMap(settings.getByPrefix("node.").getAsMap()); + if (attributes.containsKey("client")) { + if (attributes.get("client").equals("false")) { + attributes.remove("client"); // this is the default + } else { + // if we are client node, don't store data ... + attributes.put("data", "false"); + } + } + if (attributes.containsKey("data")) { + if (attributes.get("data").equals("true")) { + attributes.remove("data"); + } + } + return attributes; + } + public static final ImmutableList<DiscoveryNode> EMPTY_LIST = ImmutableList.of(); private String nodeName = StringHelper.intern(""); @@ -43,22 +67,26 @@ public class DiscoveryNode implements Streamable, Serializable { private TransportAddress address; - private boolean dataNode = true; + private ImmutableMap<String, String> attributes; private DiscoveryNode() { } public DiscoveryNode(String nodeId, TransportAddress address) { - this("", true, nodeId, address); + this("", nodeId, address, ImmutableMap.<String, String>of()); } - public DiscoveryNode(String nodeName, boolean dataNode, String nodeId, TransportAddress address) { + public DiscoveryNode(String nodeName, String nodeId, TransportAddress address, Map<String, String> attributes) { if (nodeName == null) { this.nodeName = StringHelper.intern(""); } else { this.nodeName = StringHelper.intern(nodeName); } - this.dataNode = dataNode; + ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); + for (Map.Entry<String, String> entry : attributes.entrySet()) { + builder.put(StringHelper.intern(entry.getKey()), StringHelper.intern(entry.getValue())); + } + this.attributes = builder.build(); this.nodeId = StringHelper.intern(nodeId); this.address = address; } @@ -105,11 +133,26 @@ public String getName() { return name(); } + /** + * The node attributes. + */ + public ImmutableMap<String, String> attributes() { + return this.attributes; + } + + /** + * The node attributes. + */ + public ImmutableMap<String, String> getAttributes() { + return attributes(); + } + /** * Should this node hold data (shards) or not. */ public boolean dataNode() { - return dataNode; + String data = attributes.get("data"); + return data == null || data.equals("true"); } /** @@ -119,6 +162,18 @@ public boolean isDataNode() { return dataNode(); } + /** + * Is the node a client node or not. + */ + public boolean clientNode() { + String client = attributes.get("client"); + return client != null && client.equals("true"); + } + + public boolean isClientNode() { + return clientNode(); + } + public static DiscoveryNode readNode(StreamInput in) throws IOException { DiscoveryNode node = new DiscoveryNode(); node.readFrom(in); @@ -127,16 +182,25 @@ public static DiscoveryNode readNode(StreamInput in) throws IOException { @Override public void readFrom(StreamInput in) throws IOException { nodeName = StringHelper.intern(in.readUTF()); - dataNode = in.readBoolean(); nodeId = StringHelper.intern(in.readUTF()); address = TransportAddressSerializers.addressFromStream(in); + int size = in.readVInt(); + ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); + for (int i = 0; i < size; i++) { + builder.put(StringHelper.intern(in.readUTF()), StringHelper.intern(in.readUTF())); + } + attributes = builder.build(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeUTF(nodeName); - out.writeBoolean(dataNode); out.writeUTF(nodeId); - TransportAddressSerializers.addressToStream(out, address); + addressToStream(out, address); + out.writeVInt(attributes.size()); + for (Map.Entry<String, String> entry : attributes.entrySet()) { + out.writeUTF(entry.getKey()); + out.writeUTF(entry.getValue()); + } } @Override public boolean equals(Object obj) { @@ -159,12 +223,12 @@ public static DiscoveryNode readNode(StreamInput in) throws IOException { if (nodeId != null) { sb.append('[').append(nodeId).append(']'); } - if (dataNode) { - sb.append("[data]"); - } if (address != null) { sb.append('[').append(address).append(']'); } + if (!attributes.isEmpty()) { + sb.append(attributes); + } return sb.toString(); } } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java index c8b18942a5846..13d5f458c6d88 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java @@ -50,6 +50,7 @@ import static com.google.common.collect.Maps.*; import static com.google.common.collect.Sets.*; import static org.elasticsearch.cluster.ClusterState.*; +import static org.elasticsearch.cluster.node.DiscoveryNode.*; /** * @author kimchy (Shay Banon) @@ -142,11 +143,11 @@ public class JgroupsDiscovery extends AbstractLifecycleComponent<Discovery> impl channel.connect(clusterName.value()); channel.setReceiver(this); logger.debug("Connected to cluster [{}], address [{}]", channel.getClusterName(), channel.getAddress()); - this.localNode = new DiscoveryNode(settings.get("name"), settings.getAsBoolean("node.data", !settings.getAsBoolean("node.client", false)), channel.getAddress().toString(), transportService.boundAddress().publishAddress()); + this.localNode = new DiscoveryNode(settings.get("name"), channel.getAddress().toString(), transportService.boundAddress().publishAddress(), buildCommonNodesAttributes(settings)); if (isMaster()) { firstMaster = true; - clusterService.submitStateUpdateTask("jgroups-disco-initialconnect(master)", new ProcessedClusterStateUpdateTask() { + clusterService.submitStateUpdateTask("jgroups-disco-initial_connect(master)", new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder() .localNodeId(localNode.id()) diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java index 3da929a2a634d..aebc1d8cc8e23 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java @@ -42,6 +42,7 @@ import static com.google.common.collect.Sets.*; import static org.elasticsearch.cluster.ClusterState.*; +import static org.elasticsearch.cluster.node.DiscoveryNode.*; /** * @author kimchy (Shay Banon) @@ -84,14 +85,14 @@ public class LocalDiscovery extends AbstractLifecycleComponent<Discovery> implem clusterGroups.put(clusterName, clusterGroup); } logger.debug("Connected to cluster [{}]", clusterName); - this.localNode = new DiscoveryNode(settings.get("name"), settings.getAsBoolean("node.data", !settings.getAsBoolean("node.client", false)), Long.toString(nodeIdGenerator.incrementAndGet()), transportService.boundAddress().publishAddress()); + this.localNode = new DiscoveryNode(settings.get("name"), Long.toString(nodeIdGenerator.incrementAndGet()), transportService.boundAddress().publishAddress(), buildCommonNodesAttributes(settings)); clusterGroup.members().add(this); if (clusterGroup.members().size() == 1) { // we are the first master (and the master) master = true; firstMaster = true; - clusterService.submitStateUpdateTask("local-disco-initialconnect(master)", new ProcessedClusterStateUpdateTask() { + clusterService.submitStateUpdateTask("local-disco-initial_connect(master)", new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder() .localNodeId(localNode.id()) diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java index 68a60a333a7b3..c89613444d969 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java @@ -42,11 +42,13 @@ import org.elasticsearch.util.settings.Settings; import java.util.List; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import static com.google.common.collect.Lists.*; import static org.elasticsearch.cluster.ClusterState.*; +import static org.elasticsearch.cluster.node.DiscoveryNode.*; import static org.elasticsearch.cluster.node.DiscoveryNodes.*; import static org.elasticsearch.util.TimeValue.*; @@ -55,6 +57,8 @@ */ public class ZenDiscovery extends AbstractLifecycleComponent<Discovery> implements Discovery, DiscoveryNodesProvider { + private final ThreadPool threadPool; + private final TransportService transportService; private final ClusterService clusterService; @@ -94,6 +98,7 @@ public class ZenDiscovery extends AbstractLifecycleComponent<Discovery> implemen ZenPingService pingService) { super(settings); this.clusterName = clusterName; + this.threadPool = threadPool; this.clusterService = clusterService; this.transportService = transportService; this.pingService = pingService; @@ -114,57 +119,29 @@ public class ZenDiscovery extends AbstractLifecycleComponent<Discovery> implemen } @Override protected void doStart() throws ElasticSearchException { - localNode = new DiscoveryNode(settings.get("name"), settings.getAsBoolean("node.data", !settings.getAsBoolean("node.client", false)), UUID.randomUUID().toString(), transportService.boundAddress().publishAddress()); + Map<String, String> nodeAttributes = buildCommonNodesAttributes(settings); + Boolean zenMaster = componentSettings.getAsBoolean("master", null); + if (zenMaster != null) { + if (zenMaster.equals(Boolean.FALSE)) { + nodeAttributes.put("zen.master", "false"); + } + } else if (nodeAttributes.containsKey("client")) { + if (nodeAttributes.get("client").equals("true")) { + nodeAttributes.put("zen.master", "false"); + } + } + localNode = new DiscoveryNode(settings.get("name"), UUID.randomUUID().toString(), transportService.boundAddress().publishAddress(), nodeAttributes); pingService.start(); - boolean retry = true; - while (retry) { - retry = false; - DiscoveryNode masterNode = broadBingTillMasterResolved(); - if (localNode.equals(masterNode)) { - // we are the master (first) - this.firstMaster = true; - this.master = true; - nodesFD.start(); // start the nodes FD - clusterService.submitStateUpdateTask("zen-disco-initial_connect(master)", new ProcessedClusterStateUpdateTask() { - @Override public ClusterState execute(ClusterState currentState) { - DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder() - .localNodeId(localNode.id()) - .masterNodeId(localNode.id()) - // put our local node - .put(localNode); - // update the fact that we are the master... - latestDiscoNodes = builder.build(); - return newClusterStateBuilder().state(currentState).nodes(builder).build(); - } - - @Override public void clusterStateProcessed(ClusterState clusterState) { - sendInitialStateEventIfNeeded(); - } - }); - } else { - this.firstMaster = false; - this.master = false; - try { - // first, make sure we can connect to the master - transportService.connectToNode(masterNode); - } catch (Exception e) { - logger.warn("Failed to connect to master [{}], retrying...", e, masterNode); - retry = true; - continue; - } - // send join request - try { - membership.sendJoinRequestBlocking(masterNode, localNode, initialPingTimeout); - } catch (Exception e) { - logger.warn("Failed to send join request to master [{}], retrying...", e, masterNode); - // failed to send the join request, retry - retry = true; - continue; + if (nodeAttributes.containsKey("zen.master") && nodeAttributes.get("zen.master").equals("false")) { + // do the join on a different thread + threadPool.execute(new Runnable() { + @Override public void run() { + initialJoin(); } - // cool, we found a master, start an FD on it - masterFD.start(masterNode); - } + }); + } else { + initialJoin(); } } @@ -239,6 +216,63 @@ public class ZenDiscovery extends AbstractLifecycleComponent<Discovery> implemen publishClusterState.publish(clusterState); } + private void initialJoin() { + boolean retry = true; + while (retry) { + retry = false; + DiscoveryNode masterNode = broadPingTillMasterResolved(); + if (localNode.equals(masterNode)) { + // we are the master (first) + this.firstMaster = true; + this.master = true; + nodesFD.start(); // start the nodes FD + clusterService.submitStateUpdateTask("zen-disco-initial_connect(master)", new ProcessedClusterStateUpdateTask() { + @Override public ClusterState execute(ClusterState currentState) { + DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder() + .localNodeId(localNode.id()) + .masterNodeId(localNode.id()) + // put our local node + .put(localNode); + // update the fact that we are the master... + latestDiscoNodes = builder.build(); + return newClusterStateBuilder().state(currentState).nodes(builder).build(); + } + + @Override public void clusterStateProcessed(ClusterState clusterState) { + sendInitialStateEventIfNeeded(); + } + }); + } else { + this.firstMaster = false; + this.master = false; + try { + // first, make sure we can connect to the master + transportService.connectToNode(masterNode); + } catch (Exception e) { + logger.warn("Failed to connect to master [{}], retrying...", e, masterNode); + retry = true; + continue; + } + // send join request + try { + membership.sendJoinRequestBlocking(masterNode, localNode, initialPingTimeout); + } catch (Exception e) { + logger.warn("Failed to send join request to master [{}], retrying...", e, masterNode); + // failed to send the join request, retry + retry = true; + continue; + } + // cool, we found a master, start an FD on it + masterFD.start(masterNode); + } + if (retry) { + if (!lifecycle.started()) { + return; + } + } + } + } + private void handleNodeFailure(final DiscoveryNode node) { if (!master) { // nothing to do here... @@ -365,7 +399,7 @@ private void handleJoinRequest(final DiscoveryNode node) { } } - private DiscoveryNode broadBingTillMasterResolved() { + private DiscoveryNode broadPingTillMasterResolved() { while (true) { ZenPing.PingResponse[] pingResponses = pingService.pingAndWait(initialPingTimeout); List<DiscoveryNode> pingMasters = newArrayList(); diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/elect/ElectMasterService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/elect/ElectMasterService.java index aa18dce53e2ff..d8067301e9aa9 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/elect/ElectMasterService.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/zen/elect/ElectMasterService.java @@ -26,6 +26,7 @@ import java.util.Collections; import java.util.Comparator; +import java.util.Iterator; import java.util.List; import static com.google.common.collect.Lists.*; @@ -45,7 +46,7 @@ public ElectMasterService(Settings settings) { * Returns a list of the next possible masters. */ public DiscoveryNode[] nextPossibleMasters(Iterable<DiscoveryNode> nodes, int numberOfPossibleMasters) { - List<DiscoveryNode> sortedNodes = sortedNodes(nodes); + List<DiscoveryNode> sortedNodes = sortedMasterNodes(nodes); if (sortedNodes == null) { return new DiscoveryNode[0]; } @@ -65,18 +66,27 @@ public DiscoveryNode[] nextPossibleMasters(Iterable<DiscoveryNode> nodes, int nu * if no master has been elected. */ public DiscoveryNode electMaster(Iterable<DiscoveryNode> nodes) { - List<DiscoveryNode> sortedNodes = sortedNodes(nodes); - if (sortedNodes == null) { + List<DiscoveryNode> sortedNodes = sortedMasterNodes(nodes); + if (sortedNodes == null || sortedNodes.isEmpty()) { return null; } return sortedNodes.get(0); } - private List<DiscoveryNode> sortedNodes(Iterable<DiscoveryNode> nodes) { + private List<DiscoveryNode> sortedMasterNodes(Iterable<DiscoveryNode> nodes) { List<DiscoveryNode> possibleNodes = Lists.newArrayList(nodes); if (possibleNodes.isEmpty()) { return null; } + // clean non master nodes + for (Iterator<DiscoveryNode> it = possibleNodes.iterator(); it.hasNext();) { + DiscoveryNode node = it.next(); + if (node.attributes().containsKey("zen.master")) { + if (node.attributes().get("zen.master").equals("false")) { + it.remove(); + } + } + } Collections.sort(possibleNodes, nodeComparator); return possibleNodes; } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java index 7319703f73e7f..9af8c720e6ce6 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java @@ -64,7 +64,12 @@ public class RestNodesInfoAction extends BaseRestHandler { builder.field("name", nodeInfo.node().name()); builder.field("transport_address", nodeInfo.node().address().toString()); - builder.field("data_node", nodeInfo.node().dataNode()); + + builder.startArray("attributes"); + for (Map.Entry<String, String> attr : nodeInfo.node().attributes().entrySet()) { + builder.field(attr.getKey(), attr.getValue()); + } + builder.endArray(); for (Map.Entry<String, String> nodeAttribute : nodeInfo.attributes().entrySet()) { builder.field(nodeAttribute.getKey(), nodeAttribute.getValue()); diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/ImmutableSettings.java b/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/ImmutableSettings.java index 2a7679d9ef05d..773ec2518e215 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/ImmutableSettings.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/ImmutableSettings.java @@ -83,15 +83,19 @@ private ImmutableSettings(Map<String, String> settings, Settings globalSettings, throw new SettingsException("Component [" + type + "] does not start with prefix [" + prefix + "]"); } String settingPrefix = type.substring(prefix.length() + 1); // 1 for the '.' - settingPrefix = settingPrefix.substring(0, settingPrefix.length() - component.getSimpleName().length() - 1); // remove the simple class name + settingPrefix = settingPrefix.substring(0, settingPrefix.length() - component.getSimpleName().length()); // remove the simple class name (keep the dot) + return getByPrefix(settingPrefix); + } + + @Override public Settings getByPrefix(String prefix) { Builder builder = new Builder(); for (Map.Entry<String, String> entry : getAsMap().entrySet()) { - if (entry.getKey().startsWith(settingPrefix)) { - if (entry.getKey().length() <= settingPrefix.length()) { + if (entry.getKey().startsWith(prefix)) { + if (entry.getKey().length() < prefix.length()) { // ignore this one continue; } - builder.put(entry.getKey().substring(settingPrefix.length() + 1), entry.getValue()); + builder.put(entry.getKey().substring(prefix.length()), entry.getValue()); } } builder.globalSettings(this); diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/Settings.java b/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/Settings.java index 50de0624c5c67..8f39c2066a1ed 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/Settings.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/util/settings/Settings.java @@ -55,7 +55,12 @@ public interface Settings { Settings getComponentSettings(String prefix, Class component); /** - * The class loader associted with this settings. + * A settings that are filtered (and key is removed) with the specified prefix. + */ + Settings getByPrefix(String prefix); + + /** + * The class loader associated with this settings. */ ClassLoader getClassLoader();
2ca004c0298cd87c9a946843ab905154d4d1df65
apache$maven-plugins
[MINVOKER-22] Add feature to install plugin to a local repository. o Refactored functionality into distinct mojo git-svn-id: https://svn.apache.org/repos/asf/maven/plugins/trunk@655034 13f79535-47bb-0310-9956-ffa450edef68
p
https://github.com/apache/maven-plugins
diff --git a/maven-invoker-plugin/pom.xml b/maven-invoker-plugin/pom.xml index c8a8c694fd..5304fd3f08 100644 --- a/maven-invoker-plugin/pom.xml +++ b/maven-invoker-plugin/pom.xml @@ -69,6 +69,11 @@ under the License. <artifactId>maven-plugin-api</artifactId> <version>2.0</version> </dependency> + <dependency> + <groupId>org.apache.maven</groupId> + <artifactId>maven-artifact</artifactId> + <version>2.0</version> + </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-settings</artifactId> diff --git a/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InstallMojo.java b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InstallMojo.java new file mode 100644 index 0000000000..38ab038b23 --- /dev/null +++ b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InstallMojo.java @@ -0,0 +1,176 @@ +package org.apache.maven.plugin.invoker; + +/* + * 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. + */ + +import java.io.File; +import java.util.Collection; +import java.util.Iterator; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.installer.ArtifactInstallationException; +import org.apache.maven.artifact.installer.ArtifactInstaller; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.project.MavenProject; + +/** + * Installs the project artifacts into the local repository as a preparation to run the integration tests. + * + * @goal install + * @phase pre-integration-test + * @since 1.2 + * + * @author Paul Gier + * @author Benjamin Bentmann + * @version $Id$ + */ +public class InstallMojo + extends AbstractMojo +{ + + /** + * Maven artifact install component to copy artifacts to the local repository. + * + * @component + */ + private ArtifactInstaller installer; + + /** + * The component used to create artifacts. + * + * @component + */ + private ArtifactFactory artifactFactory; + + /** + * The component used to create artifacts. + * + * @component + */ + private ArtifactRepositoryFactory repositoryFactory; + + /** + * @parameter expression="${localRepository}" + * @required + * @readonly + */ + protected ArtifactRepository localRepository; + + /** + * The path to the local repository into which the project artifacts should be installed for the integration tests. + * If not set, the regular local repository will be used. + * + * @parameter expression="${invoker.localRepositoryPath}" + */ + private File localRepositoryPath; + + /** + * The current Maven project. + * + * @parameter expression="${project}" + * @required + * @readonly + */ + private MavenProject project; + + /** + * Performs this mojo's tasks. + */ + public void execute() + throws MojoExecutionException, MojoFailureException + { + ArtifactRepository testRepository = createTestRepository(); + installProjectArtifacts( testRepository ); + } + + /** + * Installs the main project artifact and any attached artifacts to the local repository. + * + * @param testRepository The local repository to install the artifacts into, must not be <code>null</code>. + * @throws MojoExecutionException If any artifact could not be installed. + */ + private void installProjectArtifacts( ArtifactRepository testRepository ) + throws MojoExecutionException + { + try + { + // Install the pom + Artifact pomArtifact = + artifactFactory.createArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(), + null, "pom" ); + installer.install( project.getFile(), pomArtifact, testRepository ); + + // Install the main project artifact + installer.install( project.getArtifact().getFile(), project.getArtifact(), testRepository ); + + // Install any attached project artifacts + Collection attachedArtifacts = project.getAttachedArtifacts(); + for ( Iterator artifactIter = attachedArtifacts.iterator(); artifactIter.hasNext(); ) + { + Artifact theArtifact = (Artifact) artifactIter.next(); + installer.install( theArtifact.getFile(), theArtifact, testRepository ); + } + } + catch ( ArtifactInstallationException e ) + { + throw new MojoExecutionException( "Failed to install project artifacts", e ); + } + } + + /** + * Creates the local repository for the integration tests. + * + * @return The local repository for the integration tests, never <code>null</code>. + * @throws MojoExecutionException If the repository could not be created. + */ + private ArtifactRepository createTestRepository() + throws MojoExecutionException + { + ArtifactRepository testRepository = localRepository; + + if ( localRepositoryPath != null ) + { + try + { + if ( !localRepositoryPath.exists() ) + { + localRepositoryPath.mkdirs(); + } + + testRepository = + repositoryFactory.createArtifactRepository( "it-repo", localRepositoryPath.toURL().toString(), + localRepository.getLayout(), + localRepository.getSnapshots(), + localRepository.getReleases() ); + } + catch ( Exception e ) + { + throw new MojoExecutionException( "Failed to create local repository", e ); + } + } + + return testRepository; + } + +} diff --git a/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java index ebb6dd29d5..24e4dbdf28 100644 --- a/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java +++ b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java @@ -28,7 +28,6 @@ import java.io.PrintStream; import java.io.Reader; import java.io.Writer; -import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -39,12 +38,6 @@ import java.util.StringTokenizer; import java.util.TreeSet; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.installer.ArtifactInstallationException; -import org.apache.maven.artifact.installer.ArtifactInstaller; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -85,40 +78,12 @@ * * @author <a href="mailto:[email protected]">Kenney Westerhof</a> * @author <a href="mailto:[email protected]">John Casey</a> + * @version $Id$ */ public class InvokerMojo extends AbstractMojo { - /** - * Maven artifact install component to copy artifacts to the local repository. - * - * @component - */ - protected ArtifactInstaller installer; - - /** - * Used to create artifacts - * - * @component - */ - private ArtifactFactory artifactFactory; - - /** - * Used to create artifacts - * - * @component - */ - private ArtifactRepositoryFactory artifactRepositoryFactory; - /** - * Flag to determine if the project artifact(s) should be installed to the - * local repository. - * - * @parameter default-value="false" - * @since 1.2 - */ - private boolean installProjectArtifacts; - /** * Flag used to suppress certain invocations. This is useful in tailoring the * build using profiles. @@ -145,13 +110,6 @@ public class InvokerMojo */ private boolean streamLogs; - /** - * @parameter expression="${localRepository}" - * @required - * @readonly - */ - protected ArtifactRepository localRepository; - /** * The local repository for caching artifacts. * @@ -425,11 +383,6 @@ public void execute() return; } - if ( installProjectArtifacts ) - { - installProjectArtifacts(); - } - String[] includedPoms; if ( pom != null ) { @@ -555,60 +508,6 @@ private Reader newReader( File file ) } } - /** - * Install the main project artifact and any attached artifacts to the local repository. - * - * @throws MojoExecutionException - */ - private void installProjectArtifacts() - throws MojoExecutionException - { - ArtifactRepository integrationTestRepository = localRepository; - - try - { - if ( localRepositoryPath != null ) - { - if ( ! localRepositoryPath.exists() ) - { - localRepositoryPath.mkdirs(); - } - integrationTestRepository = - artifactRepositoryFactory.createArtifactRepository( "it-repo", - localRepositoryPath.toURL().toString(), - localRepository.getLayout(), - localRepository.getSnapshots(), - localRepository.getReleases() ); - } - - // Install the pom - Artifact pomArtifact = artifactFactory.createArtifact( project.getGroupId(), project.getArtifactId(), - project.getVersion(), null, "pom" ); - installer.install( project.getFile(), pomArtifact, integrationTestRepository ); - - // Install the main project artifact - installer.install( project.getArtifact().getFile(), project.getArtifact(), integrationTestRepository ); - - // Install any attached project artifacts - List attachedArtifacts = project.getAttachedArtifacts(); - Iterator artifactIter = attachedArtifacts.iterator(); - while ( artifactIter.hasNext() ) - { - Artifact theArtifact = (Artifact)artifactIter.next(); - installer.install( theArtifact.getFile(), theArtifact, integrationTestRepository ); - } - } - catch ( MalformedURLException e ) - { - throw new MojoExecutionException( "MalformedURLException: " + e.getMessage(), e ); - } - catch ( ArtifactInstallationException e ) - { - throw new MojoExecutionException( "ArtifactInstallationException: " + e.getMessage(), e ); - } - - } - private void cloneProjects( String[] includedPoms ) throws IOException { diff --git a/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt b/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt index c6074d11cd..855f5d355a 100644 --- a/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt +++ b/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt @@ -8,8 +8,8 @@ Installing Artifacts Example - The following example shows a plugin configuration with the <<<\<installProjectArtifacts\>>>> - parameter set to <<<true>>>. This will cause the project artifact(s) to be installed to the local + The following example shows a plugin configuration using the <<<{{{../install-mojo.html}invoker:install}}>>> + goal. This will cause the project artifact(s) to be installed to the local repository before executing the projects. This can be helpful if you want to build you project and test the new artifacts artifact in a single step instead of installing first and then running tests. @@ -25,13 +25,12 @@ Installing Artifacts Example <executions> <execution> <id>integration-test</id> - <phase>integration-test</phase> <goals> + <goal>install</goal> <goal>run</goal> </goals> <configuration> <localRepositoryPath>target/local-repo</localRepositoryPath> - <installProjectArtifacts>true</installProjectArtifacts> <projectsDirectory>src/it</projectsDirectory> </configuration> </execution> diff --git a/maven-invoker-plugin/src/site/apt/index.apt b/maven-invoker-plugin/src/site/apt/index.apt index 7777c42277..78b5d82bc0 100644 --- a/maven-invoker-plugin/src/site/apt/index.apt +++ b/maven-invoker-plugin/src/site/apt/index.apt @@ -14,6 +14,11 @@ Maven 2 Invoker Plugin * Goals Overview + The Invoker Plugin has two goals: + + * {{{install-mojo.html}invoker:install}} copies the project artifacts into the local repository to prepare the + execution of the integration tests. + * {{{run-mojo.html}invoker:run}} runs a set of Maven projects in a directory and verifies the result. []
4ad749b715f91d48ed71c6be0fc4b66b24ab497e
Vala
gudev-1.0: fix Device.get_property_keys and Client.query_by_subsystem
c
https://github.com/GNOME/vala/
diff --git a/vapi/gudev-1.0.vapi b/vapi/gudev-1.0.vapi index 057ab55290..e176eae246 100644 --- a/vapi/gudev-1.0.vapi +++ b/vapi/gudev-1.0.vapi @@ -8,7 +8,7 @@ namespace GUdev { public Client ([CCode (array_length = false)] string[]? subsystems); public unowned GUdev.Device? query_by_device_file (string device_file); public unowned GUdev.Device? query_by_device_number (GUdev.DeviceType type, GUdev.DeviceNumber number); - public GLib.List query_by_subsystem (string? subsystem); + public GLib.List<GUdev.Device> query_by_subsystem (string? subsystem); public unowned GUdev.Device? query_by_subsystem_and_name (string subsystem, string name); public unowned GUdev.Device? query_by_sysfs_path (string sysfs_path); [NoWrapper] @@ -53,7 +53,7 @@ namespace GUdev { [CCode (array_length = false)] public unowned string?[] get_property_as_strv (string key); public uint64 get_property_as_uint64 (string key); - [CCode (array_length = false)] + [CCode (array_length = false, array_null_terminated = true)] public unowned string?[] get_property_keys (); public uint64 get_seqnum (); public unowned string get_subsystem (); diff --git a/vapi/packages/gudev-1.0/gudev-1.0.metadata b/vapi/packages/gudev-1.0/gudev-1.0.metadata index a46be5164c..3955c54fa0 100644 --- a/vapi/packages/gudev-1.0/gudev-1.0.metadata +++ b/vapi/packages/gudev-1.0/gudev-1.0.metadata @@ -1,7 +1,7 @@ GUdev cheader_filename="gudev/gudev.h" lower_case_cprefix="g_udev_" g_udev_client_new.subsystems is_array="1" no_array_length="1" nullable="1" g_udev_client_query_by_subsystem.subsystem nullable="1" -g_udev_client_query_by_subsystem transfer_ownership="1" +g_udev_client_query_by_subsystem transfer_ownership="1" type_arguments="Device" g_udev_client_query_by_device_number nullable="1" g_udev_client_query_by_device_file nullable="1" g_udev_client_query_by_sysfs_path nullable="1" @@ -12,7 +12,7 @@ g_udev_device_get_device_file_symlinks transfer_ownership="0" is_array="1" no_ar g_udev_device_get_parent nullable="1" g_udev_device_get_parent_with_subsystem.devtype nullable="1" g_udev_device_get_parent_with_subsystem nullable="1" -g_udev_device_get_property_keys nullable="1" transfer_ownership="0" is_array="1" no_array_length="1" +g_udev_device_get_property_keys nullable="1" transfer_ownership="0" is_array="1" no_array_length="1" array_null_terminated="1" g_udev_device_get_property nullable="1" transfer_ownership="0" g_udev_device_get_property_as_strv nullable="1" transfer_ownership="0" is_array="1" no_array_length="1" g_udev_device_get_sysfs_attr nullable="1" transfer_ownership="0"
1c9e9e716a3ec0a545abc4470876da7d2db3339e
robotframework$swinglibrary
Improved tree node popup keyword stability.
p
https://github.com/MarketSquare/SwingLibrary
diff --git a/buildfile b/buildfile index cd5070ee..3675d81a 100644 --- a/buildfile +++ b/buildfile @@ -85,12 +85,12 @@ task :acceptance_tests => :dist do sh "jybot --loglevel TRACE --outputdir #{output_dir} --debugfile debug.txt --critical regression " + __('src/test/resources/robot-tests') end -task :doc => :compile do +task :doc do generate_parameter_names(__('src/main/java'), __('target/classes')) output_dir = project(PROJECT_NAME)._('doc') output_file = "#{output_dir}/#{PROJECT_NAME}-#{VERSION_NUMBER}-doc.html" mkdir_p output_dir - set_env('CLASSPATH', [__('target/classes'), artifacts(DEPENDENCIES, TEST_DEPENDENCIES)]) + ENV['CLASSPATH'] = [__('target/classes'), artifacts(DEPENDENCIES, TEST_DEPENDENCIES)].flatten.join(File::PATH_SEPARATOR) sh "jython -Dpython.path=#{python_path} lib/libdoc/libdoc.py --output #{output_file} SwingLibrary" end diff --git a/core/src/main/java/org/robotframework/swing/tree/TreePopupMenuItemFinder.java b/core/src/main/java/org/robotframework/swing/tree/TreePopupMenuItemFinder.java index 9a3c16fc..d4d8d742 100644 --- a/core/src/main/java/org/robotframework/swing/tree/TreePopupMenuItemFinder.java +++ b/core/src/main/java/org/robotframework/swing/tree/TreePopupMenuItemFinder.java @@ -27,6 +27,7 @@ import abbot.tester.ComponentTester; import abbot.tester.JComponentTester; import abbot.tester.JTreeLocation; +import abbot.util.AWT; public class TreePopupMenuItemFinder implements ITreePopupMenuItemFinder { private BasicFinder basicFinder = new BasicFinder(); @@ -36,6 +37,7 @@ public class TreePopupMenuItemFinder implements ITreePopupMenuItemFinder { public TreePopupMenuItemFinder(Component tree) { this.tree = tree; + AWT.POPUP_TIMEOUT = 250000; } public JMenuItem findMenu(String nodeIdentifier, String menuPath) { diff --git a/core/src/test/resources/robot-tests/treekeywords.tsv b/core/src/test/resources/robot-tests/treekeywords.tsv index e6ebbc97..75fbeb22 100644 --- a/core/src/test/resources/robot-tests/treekeywords.tsv +++ b/core/src/test/resources/robot-tests/treekeywords.tsv @@ -1,9 +1,10 @@ *Setting* *Value* library Collections library SwingLibrary -suiteSetup setJemmyTimeouts 1 +suiteSetup setTimeoutsAndDelays *Variable* *Value* *Value* +${delay} 0 ${treeName} testTree ${nodeIndex} 2 ${rootNode} the java series @@ -314,3 +315,10 @@ nodesShouldBeSaved hideRootNode [arguments] ${root}=${rootNode} selectFromTreeNodePopupMenu ${treeName} ${root} Hide root node + +setTimeoutsAndDelays + ${timeout}= evaluate ${delay}/1000 + log ${timeout} + runKeywordIf ${timeout} setJemmyTimeouts ${timeout} + setDelay ${delay} + randomizeDelay diff --git a/test-application/src/main/java/org/robotframework/swing/testapp/Delay.java b/test-application/src/main/java/org/robotframework/swing/testapp/Delay.java new file mode 100644 index 00000000..5663b698 --- /dev/null +++ b/test-application/src/main/java/org/robotframework/swing/testapp/Delay.java @@ -0,0 +1,40 @@ +/* + * Copyright 2008 Nokia Siemens Networks Oyj + * + * 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.robotframework.swing.testapp; + +public class Delay { + public static long delayTimeMillis = 0; + public static boolean randomEnabled = false; + + public static void delay() { + try { + Thread.sleep(getDelay()); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + private static long getDelay() { + return (long) (getRandom() * delayTimeMillis); + } + + private static double getRandom() { + if (randomEnabled) + return Math.random(); + return 1; + } +} diff --git a/test-application/src/main/java/org/robotframework/swing/testapp/TestTree.java b/test-application/src/main/java/org/robotframework/swing/testapp/TestTree.java index 33eff2d1..df1f0ba1 100644 --- a/test-application/src/main/java/org/robotframework/swing/testapp/TestTree.java +++ b/test-application/src/main/java/org/robotframework/swing/testapp/TestTree.java @@ -1,5 +1,6 @@ package org.robotframework.swing.testapp; +import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; @@ -17,71 +18,22 @@ public class TestTree extends JTree implements ActionListener { private static final String ROOT_NAME = "The Java Series"; private String rootName = ROOT_NAME; - private JPopupMenu popup = new JPopupMenu() {{ - add(new MenuItemWithCommand("Insert a child", "insert")); - add(new MenuItemWithCommand("Remove", "remove")); - add(new MenuItemWithCommand("Save node paths", "savenodes")); - add(new MenuItemWithCommand("Show dialog", "showdialog")); - add(new MenuItemWithCommand("Hide root node", "hideroot")); - add(new MenuItemWithCommand("Show root node", "showroot")); - add(new MenuItemWithCommand("Remove root name", "removerootname")); - add(new MenuItemWithCommand("Restore root name", "restorerootname")); - add(new JMenuItem("Disabled menuitem") {{ - setEnabled(false); - }}); - add(new JMenu("Submenu") {{ - add(new JMenuItem("Disabled menuitem") {{ - setEnabled(false); - }}); - add(new JMenuItem("Enabled menuitem")); - }}); - - setOpaque(true); - setLightWeightPopupEnabled(true); - setName("popupMenu"); - }}; - - public TestTree() { - this(new DefaultMutableTreeNode(ROOT_NAME) {{ + this(new MyTreeNode(ROOT_NAME) {{ add(new DefaultMutableTreeNode("Books for Java Programmers") {{ - add(new DefaultMutableTreeNode(new Object() { - public String toString() { - return "The Java Tutorial: A Short Course on the Basics"; - } - })); - add(new DefaultMutableTreeNode(new Object() { - public String toString() { - return "The Java Tutorial Continued: The Rest of the JDK"; - } - })); - add(new DefaultMutableTreeNode(new Object() { - public String toString() { - return "The JFC Swing Tutorial: A Guide to Constructing GUIs"; - } - })); + add(new MyTreeNode("The Java Tutorial: A Short Course on the Basics")); + add(new MyTreeNode("The Java Tutorial Continued: The Rest of the JDK")); + add(new MyTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs")); }}); - add(new DefaultMutableTreeNode(new Object() { - public String toString() { - return "Books for Java Implementers"; - } - }) {{ - add(new DefaultMutableTreeNode(new Object() { - public String toString() { - return "The Java Virtual Machine Specification"; - } - }) {{ - add(new DefaultMutableTreeNode("leafnode1")); - add(new DefaultMutableTreeNode("leafnode2")); + add(new MyTreeNode("Books for Java Implementers") {{ + add(new MyTreeNode("The Java Virtual Machine Specification") {{ + add(new MyTreeNode("leafnode1")); + add(new MyTreeNode("leafnode2")); }}); - add(new DefaultMutableTreeNode(new Object() { - public String toString() { - return "The Java Language Specification"; - } - }) {{ - add(new DefaultMutableTreeNode("leafnode3")); - add(new DefaultMutableTreeNode("leafnode4")); + add(new MyTreeNode("The Java Language Specification") {{ + add(new MyTreeNode("leafnode3")); + add(new MyTreeNode("leafnode4")); }}); }}); }}); @@ -94,7 +46,7 @@ public TestTree(DefaultMutableTreeNode dmtn) { addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { - popup.show((JComponent) e.getSource(), e.getX(), e.getY()); + new MyPopup().show((JComponent) e.getSource(), e.getX(), e.getY()); } } @@ -117,51 +69,108 @@ public String getText() { } public void actionPerformed(ActionEvent ae) { - if (ae.getActionCommand().equals("insert")) { - getLastPathComponent().add(new DefaultMutableTreeNode("child")); - } else if (ae.getActionCommand().equals("remove")) { - removeSelected(); - } else if (ae.getActionCommand().equals("showdialog")) { - JOptionPane.showMessageDialog(this, "This is an example message"); - } else if (ae.getActionCommand().equals("hideroot")) { - setRootVisible(false); - } else if (ae.getActionCommand().equals("showroot")) { - setRootVisible(true); - } else if (ae.getActionCommand().equals("savenodes")) { - TestTreeResults.saveNodes(getSelectionPaths()); - } else if (ae.getActionCommand().equals("removerootname")) { - rootName = ""; - } else if (ae.getActionCommand().equals("restorerootname")) { - rootName = ROOT_NAME; - } - refresh(); - updateUI(); + createActionCommand(ae.getActionCommand()).perform(); } - @Override - public TreePath[] getSelectionPaths() { - TreePath[] selectionPaths = super.getSelectionPaths(); - return (selectionPaths == null) ? new TreePath[0] : selectionPaths; + private ActionCommand createActionCommand(String command) { + if (command.equals("insert")) { + return insertChild; + } else if (command.equals("remove")) { + return removeSelected; + } else if (command.equals("showdialog")) { + return showMessage; + } else if (command.equals("hideroot")) { + return hideRoot; + } else if (command.equals("showroot")) { + return showRoot; + } else if (command.equals("savenodes")) { + return saveNodes; + } else if (command.equals("removerootname")) { + return removeRootName; + } else if (command.equals("restorerootname")) { + return restoreRootName; + } else { + return new ActionCommand() { + protected void operate() { + // Do nothing + } + }; + } } - private void removeSelected() { - TreePath[] selectionPaths = getSelectionPaths(); - for (TreePath treePath : selectionPaths) { - ((DefaultMutableTreeNode)treePath.getLastPathComponent()).removeFromParent(); + private abstract class ActionCommand { + public void perform() { + Delay.delay(); + operate(); + refresh(); + updateUI(); } - } - private DefaultMutableTreeNode getLastPathComponent() { - TreePath selectionPath = getSelectionPath(); - if (selectionPath == null) { - return null; + protected abstract void operate(); + + private void refresh() { + ((DefaultTreeModel) getModel()).nodeStructureChanged(getLastPathComponent()); + } + + protected DefaultMutableTreeNode getLastPathComponent() { + TreePath selectionPath = getSelectionPath(); + if (selectionPath == null) { + return null; + } + return (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); } - return (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); - } - - private void refresh() { - ((DefaultTreeModel) getModel()).nodeStructureChanged(getLastPathComponent()); } + + private final ActionCommand insertChild = new ActionCommand() { + protected void operate() { + getLastPathComponent().add(new DefaultMutableTreeNode("child")); + } + }; + + private final ActionCommand removeSelected = new ActionCommand() { + protected void operate() { + TreePath[] selectionPaths = getSelectionPaths(); + for (TreePath treePath : selectionPaths) { + ((DefaultMutableTreeNode)treePath.getLastPathComponent()).removeFromParent(); + } + } + }; + + private final ActionCommand showMessage = new ActionCommand() { + protected void operate() { + JOptionPane.showMessageDialog(TestTree.this, "This is an example message"); + } + }; + + private final ActionCommand hideRoot = new ActionCommand() { + protected void operate() { + setRootVisible(false); + } + }; + + private final ActionCommand showRoot = new ActionCommand() { + protected void operate() { + setRootVisible(true); + } + }; + + private final ActionCommand saveNodes = new ActionCommand() { + protected void operate() { + TestTreeResults.saveNodes(getSelectionPaths()); + } + }; + + private final ActionCommand removeRootName = new ActionCommand() { + protected void operate() { + rootName = ""; + } + }; + + private final ActionCommand restoreRootName = new ActionCommand() { + protected void operate() { + rootName = ROOT_NAME; + } + }; private class MenuItemWithCommand extends JMenuItem { public MenuItemWithCommand(String text, String actionCommand) { @@ -169,6 +178,51 @@ public MenuItemWithCommand(String text, String actionCommand) { setName(new KeywordNameNormalizer().normalize(text)); setActionCommand(actionCommand); addActionListener(TestTree.this); + Delay.delay(); + } + } + + private class MyPopup extends JPopupMenu { + public MyPopup() { + add(new MenuItemWithCommand("Insert a child", "insert")); + add(new MenuItemWithCommand("Remove", "remove")); + add(new MenuItemWithCommand("Save node paths", "savenodes")); + add(new MenuItemWithCommand("Show dialog", "showdialog")); + add(new MenuItemWithCommand("Hide root node", "hideroot")); + add(new MenuItemWithCommand("Show root node", "showroot")); + add(new MenuItemWithCommand("Remove root name", "removerootname")); + add(new MenuItemWithCommand("Restore root name", "restorerootname")); + add(new JMenuItem("Disabled menuitem") {{ + setEnabled(false); + }}); + add(new JMenu("Submenu") {{ + add(new JMenuItem("Disabled menuitem") {{ + setEnabled(false); + }}); + add(new JMenuItem("Enabled menuitem")); + }}); + + setOpaque(true); + setLightWeightPopupEnabled(true); + setName("popupMenu"); + } + + @Override + public void show(Component invoker, int x, int y) { + Delay.delay(); + super.show(invoker, x, y); + } + } + + private static class MyTreeNode extends DefaultMutableTreeNode { + public MyTreeNode(final String txt) { + super(new Object() { + public String toString() { + return txt; + } + }); + + Delay.delay(); } } } diff --git a/test-keywords/src/main/java/org/robotframework/swing/keyword/testing/TestingKeywords.java b/test-keywords/src/main/java/org/robotframework/swing/keyword/testing/TestingKeywords.java index fa06a461..cbaaacfc 100644 --- a/test-keywords/src/main/java/org/robotframework/swing/keyword/testing/TestingKeywords.java +++ b/test-keywords/src/main/java/org/robotframework/swing/keyword/testing/TestingKeywords.java @@ -8,6 +8,7 @@ import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.swing.context.Context; import org.robotframework.swing.operator.ComponentWrapper; +import org.robotframework.swing.testapp.Delay; @RobotKeywords @@ -26,4 +27,14 @@ public Component getSource() { public String getCurrentContextSourceAsString() { return ((ContainerOperator) Context.getContext()).toStringSource(); } + + @RobotKeyword + public void setDelay(String delayStr) { + Delay.delayTimeMillis = Long.parseLong(delayStr); + } + + @RobotKeyword + public void randomizeDelay() { + Delay.randomEnabled = true; + } }
9ef72b22e87757ff7ff3a499cb01bb6c771e2f2e
orientdb
Fixed bug on management of indexes with the- introducing of new ODistributedStorage--
c
https://github.com/orientechnologies/orientdb
diff --git a/build.number b/build.number index b3a22ef5cc0..b776f13db09 100644 --- a/build.number +++ b/build.number @@ -1,3 +1,3 @@ #Build Number for ANT. Do not edit! -#Thu Jul 05 12:04:44 CEST 2012 -build.number=12170 +#Thu Jul 05 13:56:06 CEST 2012 +build.number=12174 diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java index 7d888263e3c..4ff55451e75 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java @@ -61,7 +61,6 @@ import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.storage.ORawBuffer; import com.orientechnologies.orient.core.storage.ORecordCallback; -import com.orientechnologies.orient.core.storage.OStorageEmbedded; import com.orientechnologies.orient.core.storage.OStorageProxy; import com.orientechnologies.orient.core.tx.OTransactionRealAbstract; import com.orientechnologies.orient.core.type.tree.provider.OMVRBTreeRIDProvider; @@ -163,7 +162,7 @@ public <DB extends ODatabase> DB create() { getStorage().getConfiguration().update(); - if (getStorage() instanceof OStorageEmbedded) { + if (!(getStorage() instanceof OStorageProxy)) { registerHook(new OUserTrigger()); registerHook(new OClassIndexManager()); } 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 fcda6cce341..536fc2459b6 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 @@ -34,129 +34,129 @@ import com.orientechnologies.orient.core.metadata.security.OSecurityProxy; import com.orientechnologies.orient.core.metadata.security.OSecurityShared; import com.orientechnologies.orient.core.storage.OStorage; -import com.orientechnologies.orient.core.storage.OStorageEmbedded; +import com.orientechnologies.orient.core.storage.OStorageProxy; public class OMetadata { - protected int schemaClusterId; - - protected OSchemaProxy schema; - protected OSecurity security; - protected OIndexManagerProxy indexManager; - - public OMetadata() { - } - - public void load() { - final long timer = OProfiler.getInstance().startChrono(); - - try { - init(true); - - if (schemaClusterId == -1 || getDatabase().countClusterElements(OStorage.CLUSTER_INTERNAL_NAME) == 0) - return; - } finally { - OProfiler.getInstance().stopChrono("OMetadata.load", timer); - } - } - - public void create() throws IOException { - final long timer = OProfiler.getInstance().startChrono(); - - try { - init(false); - - security.create(); - schema.create(); - indexManager.create(); - } finally { - OProfiler.getInstance().stopChrono("OMetadata.load", timer); - } - } - - public OSchema getSchema() { - return schema; - } - - public OSecurity getSecurity() { - return security; - } - - public OIndexManagerProxy getIndexManager() { - return indexManager; - } - - public int getSchemaClusterId() { - return schemaClusterId; - } - - private void init(final boolean iLoad) { - final ODatabaseRecord database = getDatabase(); - schemaClusterId = database.getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME); - - indexManager = new OIndexManagerProxy(database.getStorage().getResource(OIndexManager.class.getSimpleName(), - new Callable<OIndexManager>() { - public OIndexManager call() { - OIndexManager instance; - if (database.getStorage() instanceof OStorageEmbedded) - instance = new OIndexManagerShared(database); - else - instance = new OIndexManagerRemote(database); - - if (iLoad) - instance.load(); - - return instance; - } - }), database); - - schema = new OSchemaProxy(database.getStorage().getResource(OSchema.class.getSimpleName(), new Callable<OSchemaShared>() { - public OSchemaShared call() { - final OSchemaShared instance = new OSchemaShared(schemaClusterId); - if (iLoad) - instance.load(); - return instance; - } - }), database); - - final Boolean enableSecurity = (Boolean) database.getProperty(ODatabase.OPTIONS.SECURITY.toString()); - if (enableSecurity != null && !enableSecurity) - // INSTALL NO SECURITY IMPL - security = new OSecurityNull(); - else - security = new OSecurityProxy(database.getStorage().getResource(OSecurity.class.getSimpleName(), - new Callable<OSecurityShared>() { - public OSecurityShared call() { - final OSecurityShared instance = new OSecurityShared(); - if (iLoad) - instance.load(); - return instance; - } - }), database); - - } - - /** - * Reloads the internal objects. - */ - public void reload() { - schema.reload(); - indexManager.load(); - security.load(); - } - - /** - * Closes internal objects - */ - public void close() { - if (indexManager != null) - indexManager.flush(); - if (schema != null) - schema.close(); - if (security != null) - security.close(); - } - - protected ODatabaseRecord getDatabase() { - return ODatabaseRecordThreadLocal.INSTANCE.get(); - } + protected int schemaClusterId; + + protected OSchemaProxy schema; + protected OSecurity security; + protected OIndexManagerProxy indexManager; + + public OMetadata() { + } + + public void load() { + final long timer = OProfiler.getInstance().startChrono(); + + try { + init(true); + + if (schemaClusterId == -1 || getDatabase().countClusterElements(OStorage.CLUSTER_INTERNAL_NAME) == 0) + return; + } finally { + OProfiler.getInstance().stopChrono("OMetadata.load", timer); + } + } + + public void create() throws IOException { + final long timer = OProfiler.getInstance().startChrono(); + + try { + init(false); + + security.create(); + schema.create(); + indexManager.create(); + } finally { + OProfiler.getInstance().stopChrono("OMetadata.load", timer); + } + } + + public OSchema getSchema() { + return schema; + } + + public OSecurity getSecurity() { + return security; + } + + public OIndexManagerProxy getIndexManager() { + return indexManager; + } + + public int getSchemaClusterId() { + return schemaClusterId; + } + + private void init(final boolean iLoad) { + final ODatabaseRecord database = getDatabase(); + schemaClusterId = database.getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME); + + indexManager = new OIndexManagerProxy(database.getStorage().getResource(OIndexManager.class.getSimpleName(), + new Callable<OIndexManager>() { + public OIndexManager call() { + OIndexManager instance; + if (database.getStorage() instanceof OStorageProxy) + instance = new OIndexManagerRemote(database); + else + instance = new OIndexManagerShared(database); + + if (iLoad) + instance.load(); + + return instance; + } + }), database); + + schema = new OSchemaProxy(database.getStorage().getResource(OSchema.class.getSimpleName(), new Callable<OSchemaShared>() { + public OSchemaShared call() { + final OSchemaShared instance = new OSchemaShared(schemaClusterId); + if (iLoad) + instance.load(); + return instance; + } + }), database); + + final Boolean enableSecurity = (Boolean) database.getProperty(ODatabase.OPTIONS.SECURITY.toString()); + if (enableSecurity != null && !enableSecurity) + // INSTALL NO SECURITY IMPL + security = new OSecurityNull(); + else + security = new OSecurityProxy(database.getStorage().getResource(OSecurity.class.getSimpleName(), + new Callable<OSecurityShared>() { + public OSecurityShared call() { + final OSecurityShared instance = new OSecurityShared(); + if (iLoad) + instance.load(); + return instance; + } + }), database); + + } + + /** + * Reloads the internal objects. + */ + public void reload() { + schema.reload(); + indexManager.load(); + security.load(); + } + + /** + * Closes internal objects + */ + public void close() { + if (indexManager != null) + indexManager.flush(); + if (schema != null) + schema.close(); + if (security != null) + security.close(); + } + + protected ODatabaseRecord getDatabase() { + return ODatabaseRecordThreadLocal.INSTANCE.get(); + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OPropertyImpl.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OPropertyImpl.java index cfb4327c3bf..2b6af561419 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OPropertyImpl.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OPropertyImpl.java @@ -16,7 +16,15 @@ package com.orientechnologies.orient.core.metadata.schema; import java.text.ParseException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +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 com.orientechnologies.common.util.OCaseIncentiveComparator; import com.orientechnologies.common.util.OCollections; @@ -34,7 +42,7 @@ import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; import com.orientechnologies.orient.core.sql.OCommandSQL; -import com.orientechnologies.orient.core.storage.OStorageEmbedded; +import com.orientechnologies.orient.core.storage.OStorageProxy; import com.orientechnologies.orient.core.type.ODocumentWrapperNoClass; /** @@ -364,15 +372,14 @@ public String getCustom(final String iName) { return customFields.get(iName); } - public void setCustomInternal(final String iName, final String iValue) { - if (customFields == null) - customFields = new HashMap<String, String>(); - - customFields.put(iName, iValue); - } + public void setCustomInternal(final String iName, final String iValue) { + if (customFields == null) + customFields = new HashMap<String, String>(); + customFields.put(iName, iValue); + } - public OPropertyImpl setCustom(final String iName, final String iValue) { + public OPropertyImpl setCustom(final String iName, final String iValue) { getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE); final String cmd = String.format("alter property %s custom %s=%s", getFullName(), iName, iValue); getDatabase().command(new OCommandSQL(cmd)).execute(); @@ -380,13 +387,13 @@ public OPropertyImpl setCustom(final String iName, final String iValue) { return this; } - public Map<String, String> getCustomInternal() { - if (customFields != null) - return Collections.unmodifiableMap(customFields); - return null; - } + public Map<String, String> getCustomInternal() { + if (customFields != null) + return Collections.unmodifiableMap(customFields); + return null; + } - /** + /** * Change the type. It checks for compatibility between the change of type. * * @param iType @@ -628,7 +635,7 @@ public ODocument toStream() { } public void saveInternal() { - if (getDatabase().getStorage() instanceof OStorageEmbedded) + if (!(getDatabase().getStorage() instanceof OStorageProxy)) ((OSchemaProxy) getDatabase().getMetadata().getSchema()).saveInternal(); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java index ca4b55d0c09..c6f5cac5d2e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java @@ -31,7 +31,7 @@ import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.storage.OStorage; -import com.orientechnologies.orient.core.storage.OStorageEmbedded; +import com.orientechnologies.orient.core.storage.OStorageProxy; /** * Shared security class. It's shared by all the database instances that point to the same storage. @@ -53,7 +53,7 @@ public OUser authenticate(final String iUserName, final String iUserPassword) { if (user.getAccountStatus() != STATUSES.ACTIVE) throw new OSecurityAccessException(dbName, "User '" + iUserName + "' is not active"); - if (getDatabase().getStorage() instanceof OStorageEmbedded) { + if (!(getDatabase().getStorage() instanceof OStorageProxy)) { // CHECK USER & PASSWORD if (!user.checkPassword(iUserPassword)) { // WAIT A BIT TO AVOID BRUTE FORCE diff --git a/core/src/main/java/com/orientechnologies/orient/core/query/nativ/ONativeAsynchQuery.java b/core/src/main/java/com/orientechnologies/orient/core/query/nativ/ONativeAsynchQuery.java index db49f25a387..f0612926262 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/query/nativ/ONativeAsynchQuery.java +++ b/core/src/main/java/com/orientechnologies/orient/core/query/nativ/ONativeAsynchQuery.java @@ -27,101 +27,101 @@ import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.storage.OStorageEmbedded; +import com.orientechnologies.orient.core.storage.OStorageProxy; @SuppressWarnings("serial") public abstract class ONativeAsynchQuery<CTX extends OQueryContextNative> extends ONativeQuery<CTX> { - protected int resultCount = 0; - protected ORecordInternal<?> record; - - public ONativeAsynchQuery(final String iCluster, final CTX iQueryRecordImpl) { - this(iCluster, iQueryRecordImpl, null); - } - - public ONativeAsynchQuery(final String iCluster, final CTX iQueryRecordImpl, final OCommandResultListener iResultListener) { - super(iCluster); - resultListener = iResultListener; - queryRecord = iQueryRecordImpl; - record = new ODocument(); - } - - @Deprecated - public ONativeAsynchQuery(final ODatabaseRecord iDatabase, final String iCluster, final CTX iQueryRecordImpl, - final OCommandResultListener iResultListener) { - this(iCluster, iQueryRecordImpl, iResultListener); - } - - public boolean isAsynchronous() { - return resultListener != this; - } - - public boolean foreach(final ORecordInternal<?> iRecord) { - final ODocument record = (ODocument) iRecord; - queryRecord.setRecord(record); - - if (filter(queryRecord)) { - resultCount++; - resultListener.result(record.copy()); - - if (limit > -1 && resultCount == limit) - // BREAK THE EXECUTION - return false; - } - return true; - } - - public List<ODocument> run(final Object... iArgs) { - final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.get(); - - if (!(database.getStorage() instanceof OStorageEmbedded)) - throw new OCommandExecutionException("Native queries can run only in embedded-local version. Not in the remote one."); - - queryRecord.setSourceQuery(this); - - // CHECK IF A CLASS WAS CREATED - final OClass cls = database.getMetadata().getSchema().getClass(className); - if (cls == null) - throw new OCommandExecutionException("Class '" + className + "' was not found"); - - final ORecordIteratorClass<ORecordInternal<?>> target = new ORecordIteratorClass<ORecordInternal<?>>(database, - (ODatabaseRecordAbstract) database, className, isPolymorphic()); - - // BROWSE ALL THE RECORDS - for (OIdentifiable id : target) { - final ORecordInternal<?> record = (ORecordInternal<?>) id.getRecord(); - - if (record != null && record.getRecordType() != ODocument.RECORD_TYPE) - // WRONG RECORD TYPE: JUMP IT - continue; - - queryRecord.setRecord((ODocument) record); - - if (filter(queryRecord)) { - resultCount++; - resultListener.result(record.copy()); - - if (limit > -1 && resultCount == limit) - // BREAK THE EXECUTION - break; - } - } - - return null; - } - - public ODocument runFirst(final Object... iArgs) { - setLimit(1); - execute(); - return null; - } - - @Override - public OCommandResultListener getResultListener() { - return resultListener; - } - - @Override - public void setResultListener(final OCommandResultListener resultListener) { - this.resultListener = resultListener; - } + protected int resultCount = 0; + protected ORecordInternal<?> record; + + public ONativeAsynchQuery(final String iCluster, final CTX iQueryRecordImpl) { + this(iCluster, iQueryRecordImpl, null); + } + + public ONativeAsynchQuery(final String iCluster, final CTX iQueryRecordImpl, final OCommandResultListener iResultListener) { + super(iCluster); + resultListener = iResultListener; + queryRecord = iQueryRecordImpl; + record = new ODocument(); + } + + @Deprecated + public ONativeAsynchQuery(final ODatabaseRecord iDatabase, final String iCluster, final CTX iQueryRecordImpl, + final OCommandResultListener iResultListener) { + this(iCluster, iQueryRecordImpl, iResultListener); + } + + public boolean isAsynchronous() { + return resultListener != this; + } + + public boolean foreach(final ORecordInternal<?> iRecord) { + final ODocument record = (ODocument) iRecord; + queryRecord.setRecord(record); + + if (filter(queryRecord)) { + resultCount++; + resultListener.result(record.copy()); + + if (limit > -1 && resultCount == limit) + // BREAK THE EXECUTION + return false; + } + return true; + } + + public List<ODocument> run(final Object... iArgs) { + final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.get(); + + if (database.getStorage() instanceof OStorageProxy) + throw new OCommandExecutionException("Native queries can run only in embedded-local version. Not in the remote one."); + + queryRecord.setSourceQuery(this); + + // CHECK IF A CLASS WAS CREATED + final OClass cls = database.getMetadata().getSchema().getClass(className); + if (cls == null) + throw new OCommandExecutionException("Class '" + className + "' was not found"); + + final ORecordIteratorClass<ORecordInternal<?>> target = new ORecordIteratorClass<ORecordInternal<?>>(database, + (ODatabaseRecordAbstract) database, className, isPolymorphic()); + + // BROWSE ALL THE RECORDS + for (OIdentifiable id : target) { + final ORecordInternal<?> record = (ORecordInternal<?>) id.getRecord(); + + if (record != null && record.getRecordType() != ODocument.RECORD_TYPE) + // WRONG RECORD TYPE: JUMP IT + continue; + + queryRecord.setRecord((ODocument) record); + + if (filter(queryRecord)) { + resultCount++; + resultListener.result(record.copy()); + + if (limit > -1 && resultCount == limit) + // BREAK THE EXECUTION + break; + } + } + + return null; + } + + public ODocument runFirst(final Object... iArgs) { + setLimit(1); + execute(); + return null; + } + + @Override + public OCommandResultListener getResultListener() { + return resultListener; + } + + @Override + public void setResultListener(final OCommandResultListener resultListener) { + this.resultListener = resultListener; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java index f3988a63c62..7452527363e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java @@ -38,6 +38,7 @@ import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.storage.ORecordCallback; import com.orientechnologies.orient.core.storage.OStorageEmbedded; +import com.orientechnologies.orient.core.storage.OStorageProxy; public class OTransactionOptimistic extends OTransactionRealAbstract { private boolean usingLog; @@ -56,7 +57,7 @@ public void commit() { checkTransaction(); status = TXSTATUS.COMMITTING; - if (!(database.getStorage() instanceof OStorageEmbedded)) + if (database.getStorage() instanceof OStorageProxy) database.getStorage().commit(this); else { final List<String> involvedIndexes = getInvolvedIndexes(); diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java index 429906a4d6e..08bcd698245 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java @@ -56,7 +56,7 @@ import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerStringAbstract; import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyStreamable; import com.orientechnologies.orient.core.storage.OCluster; -import com.orientechnologies.orient.core.storage.OStorageEmbedded; +import com.orientechnologies.orient.core.storage.OStorageProxy; import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryServer; import com.orientechnologies.orient.server.OClientConnection; @@ -439,7 +439,7 @@ protected void openDatabase() throws IOException { connection.database = (ODatabaseDocumentTx) OServerMain.server().openDatabase(dbType, dbURL, user, passwd); connection.rawDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying()); - if (!(connection.database.getStorage() instanceof OStorageEmbedded) && !loadUserFromSchema(user, passwd)) { + if (connection.database.getStorage() instanceof OStorageProxy && !loadUserFromSchema(user, passwd)) { sendError(clientTxId, new OSecurityAccessException(connection.database.getName(), "User or password not valid for database: '" + connection.database.getName() + "'")); } else { 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 957ed874e95..b5b0800c9a3 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 @@ -158,7 +158,7 @@ public void service() throws ONetworkProtocolException, IOException { connection.data.totalCommandExecutionTime += connection.data.lastCommandExecutionTime; } - protected void handleError(Exception e) { + protected void handleError(Throwable e) { if (OLogManager.instance().isDebugEnabled()) OLogManager.instance().debug(this, "Caught exception", e); @@ -209,13 +209,10 @@ protected void handleError(Exception e) { } if (cause != null) - e = (Exception) cause; + e = cause; } while (cause != null); } - if (errorReason == null) - errorReason = OHttpUtils.STATUS_INTERNALERROR_DESCRIPTION; - if (errorMessage == null) { // FORMAT GENERIC MESSAGE BY READING THE EXCEPTION STACK final StringBuilder buffer = new StringBuilder(); @@ -229,6 +226,11 @@ protected void handleError(Exception e) { errorMessage = buffer.toString(); } + if (errorReason == null) { + errorReason = OHttpUtils.STATUS_INTERNALERROR_DESCRIPTION; + OLogManager.instance().error(this, "Internal server error", e); + } + try { sendTextContent(errorCode, errorReason, responseHeaders, OHttpUtils.CONTENT_TEXT_PLAIN, errorMessage); } catch (IOException e1) { diff --git a/server/src/main/java/com/orientechnologies/orient/server/task/OCreateRecordDistributedTask.java b/server/src/main/java/com/orientechnologies/orient/server/task/OCreateRecordDistributedTask.java index 0fd763ae34b..65b85931710 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/task/OCreateRecordDistributedTask.java +++ b/server/src/main/java/com/orientechnologies/orient/server/task/OCreateRecordDistributedTask.java @@ -53,8 +53,6 @@ public OCreateRecordDistributedTask(final String nodeSource, final String iDbNam super(nodeSource, iDbName, iMode, iRid, iVersion); content = iContent; recordType = iRecordType; - OLogManager.instance().warn(this, "DISTRIBUTED -> route CREATE RECORD in %s mode to %s %s{%s} v.%d", iMode, nodeSource, - iDbName, iRid, iVersion); } @Override diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/RemoteCreateDocumentSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/RemoteCreateDocumentSpeedTest.java index 9b9d0c3725e..f660ecbfc7a 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/RemoteCreateDocumentSpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/RemoteCreateDocumentSpeedTest.java @@ -34,7 +34,7 @@ public class RemoteCreateDocumentSpeedTest extends OrientMonoThreadTest { private ODocument record; private Date date = new Date(); private long beginRecords; - private final static long DELAY = 0; + private final static long DELAY = 1000; public static void main(String[] iArgs) throws InstantiationException, IllegalAccessException { RemoteCreateDocumentSpeedTest test = new RemoteCreateDocumentSpeedTest(); diff --git a/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java b/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java index 50ce7f77697..555f2bbec48 100644 --- a/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java +++ b/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java @@ -83,7 +83,7 @@ import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.storage.ORawBuffer; import com.orientechnologies.orient.core.storage.OStorage; -import com.orientechnologies.orient.core.storage.OStorageEmbedded; +import com.orientechnologies.orient.core.storage.OStorageProxy; import com.orientechnologies.orient.core.storage.impl.local.ODataHoleInfo; import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal; import com.orientechnologies.orient.enterprise.command.OCommandExecutorScript; @@ -1019,7 +1019,7 @@ public void clusters() { clusterId = currentDatabase.getClusterIdByName(clusterName); clusterType = currentDatabase.getClusterType(clusterName); count = currentDatabase.countClusterElements(clusterName); - if (currentDatabase.getStorage() instanceof OStorageEmbedded) { + if (!(currentDatabase.getStorage() instanceof OStorageProxy)) { size = currentDatabase.getClusterRecordSizeByName(clusterName); totalElements += count; totalSize += size;
66ae626f91e0b2bbfcf9b9059cb06b07883d9b0b
spring-framework
Only register Date converters with global format--Change JodaTimeFormatterRegistrar and DateFormatterRegistrar to only-register converters for the Date and Calendar types when a global format-has been defined. This means that the ObjectToObject converter will-handle String->Date conversion using the deprecated Date(String)-constructor (as was the case with Spring 3.1).--Issue: SPR-
c
https://github.com/spring-projects/spring-framework
diff --git a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java index 5e45fedee3bd..b74b53262b5b 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java @@ -40,20 +40,24 @@ public class DateFormatterRegistrar implements FormatterRegistrar { - private DateFormatter dateFormatter = new DateFormatter(); + private DateFormatter dateFormatter; public void registerFormatters(FormatterRegistry registry) { addDateConverters(registry); - registry.addFormatter(this.dateFormatter); - registry.addFormatterForFieldType(Calendar.class, this.dateFormatter); registry.addFormatterForFieldAnnotation(new DateTimeFormatAnnotationFormatterFactory()); + + // In order to retain back compatibility we only register Date/Calendar + // types when a user defined formatter is specified (see SPR-10105) + if(this.dateFormatter != null) { + registry.addFormatter(this.dateFormatter); + registry.addFormatterForFieldType(Calendar.class, this.dateFormatter); + } } /** - * Set the date formatter to register. If not specified the default {@link DateFormatter} - * will be used. This method can be used if additional formatter configuration is - * required. + * Set the date formatter to register. If not specified no formatter is registered. + * This method can be used if global formatter configuration is required. * @param dateFormatter the date formatter */ public void setFormatter(DateFormatter dateFormatter) { diff --git a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java index 2035b68b8521..7ad1a4e62e64 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java @@ -174,7 +174,16 @@ public void registerFormatters(FormatterRegistry registry) { addFormatterForFields(registry, new ReadableInstantPrinter(dateTimeFormatter), new DateTimeParser(dateTimeFormatter), - ReadableInstant.class, Date.class, Calendar.class); + ReadableInstant.class); + + // In order to retain back compatibility we only register Date/Calendar + // types when a user defined formatter is specified (see SPR-10105) + if(this.formatters.containsKey(Type.DATE_TIME)) { + addFormatterForFields(registry, + new ReadableInstantPrinter(dateTimeFormatter), + new DateTimeParser(dateTimeFormatter), + Date.class, Calendar.class); + } registry.addFormatterForFieldAnnotation( new JodaDateTimeFormatAnnotationFormatterFactory()); diff --git a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java index 5698ed06518e..2803f0dc9f9d 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java @@ -16,7 +16,10 @@ package org.springframework.format.datetime; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Calendar; @@ -50,9 +53,12 @@ public class DateFormattingTests { @Before public void setUp() { - DefaultConversionService.addDefaultConverters(conversionService); - DateFormatterRegistrar registrar = new DateFormatterRegistrar(); + setUp(registrar); + } + + private void setUp(DateFormatterRegistrar registrar) { + DefaultConversionService.addDefaultConverters(conversionService); registrar.registerFormatters(conversionService); SimpleDateBean bean = new SimpleDateBean(); @@ -187,13 +193,48 @@ public void testBindNestedDateAnnotated() { } @Test - public void dateToString() throws Exception { + public void dateToStringWithoutGlobalFormat() throws Exception { + Date date = new Date(); + Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); + String expected = date.toString(); + assertEquals(expected, actual); + } + + @Test + public void dateToStringWithGlobalFormat() throws Exception { + DateFormatterRegistrar registrar = new DateFormatterRegistrar(); + registrar.setFormatter(new DateFormatter()); + setUp(registrar); Date date = new Date(); Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); String expected = new DateFormatter().print(date, Locale.US); assertEquals(expected, actual); } + @Test + @SuppressWarnings("deprecation") + public void stringToDateWithoutGlobalFormat() throws Exception { + // SPR-10105 + String string = "Sat, 12 Aug 1995 13:30:00 GM"; + Date date = this.conversionService.convert(string, Date.class); + assertThat(date, equalTo(new Date(string))); + } + + @Test + public void stringToDateWithGlobalFormat() throws Exception { + // SPR-10105 + DateFormatterRegistrar registrar = new DateFormatterRegistrar(); + DateFormatter dateFormatter = new DateFormatter(); + dateFormatter.setIso(ISO.DATE_TIME); + registrar.setFormatter(dateFormatter); + setUp(registrar); + // This is a format that cannot be parsed by new Date(String) + String string = "2009-06-01T14:23:05.003+0000"; + Date date = this.conversionService.convert(string, Date.class); + assertNotNull(date); + } + + @SuppressWarnings("unused") private static class SimpleDateBean { diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java index 237df0509f3f..c2aaf8d36a3c 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java @@ -16,6 +16,11 @@ package org.springframework.format.datetime.joda; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -32,7 +37,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; - import org.springframework.beans.MutablePropertyValues; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.convert.TypeDescriptor; @@ -42,8 +46,6 @@ import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; -import static org.junit.Assert.*; - /** * @author Keith Donald * @author Juergen Hoeller @@ -459,13 +461,40 @@ public void testBindMutableDateTimeAnnotated() { } @Test - public void dateToString() throws Exception { + public void dateToStringWithFormat() throws Exception { + JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar(); + registrar.setDateTimeFormatter(org.joda.time.format.DateTimeFormat.shortDateTime()); + setUp(registrar); Date date = new Date(); Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); String expected = JodaTimeContextHolder.getFormatter(org.joda.time.format.DateTimeFormat.shortDateTime(), Locale.US).print(new DateTime(date)); assertEquals(expected, actual); } + @Test + @SuppressWarnings("deprecation") + public void stringToDateWithoutGlobalFormat() throws Exception { + // SPR-10105 + String string = "Sat, 12 Aug 1995 13:30:00 GM"; + Date date = this.conversionService.convert(string, Date.class); + assertThat(date, equalTo(new Date(string))); + } + + @Test + public void stringToDateWithGlobalFormat() throws Exception { + // SPR-10105 + JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar(); + DateTimeFormatterFactory factory = new DateTimeFormatterFactory(); + factory.setIso(ISO.DATE_TIME); + registrar.setDateTimeFormatter(factory.createDateTimeFormatter()); + setUp(registrar); + // This is a format that cannot be parsed by new Date(String) + String string = "2009-10-31T07:00:00.000-05:00"; + Date date = this.conversionService.convert(string, Date.class); + assertNotNull(date); + } + + @SuppressWarnings("unused") private static class JodaTimeBean {
fc063b934666bbf12886cd1fd5f07d1b3c82dfa8
Delta Spike
DELTASPIKE-367 upgrade to owb-arquillian-1.2.0-SNAPTHOT we finally need to upgrade to 1.2.0 but for now it's fine.
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml index bcc7fec07..24ea1da9a 100644 --- a/deltaspike/parent/code/pom.xml +++ b/deltaspike/parent/code/pom.xml @@ -186,7 +186,7 @@ <dependency> <groupId>org.apache.openwebbeans.arquillian</groupId> <artifactId>owb-arquillian-standalone</artifactId> - <version>1.1.8</version> + <version>1.2.0-SNAPSHOT</version> <scope>test</scope> </dependency> </dependencies>
4cfe0112b339e227fb89d55ea870eed39c009f9e
Delta Spike
update javadoc
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java index fbdd27bc4..d51342f41 100644 --- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java +++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java @@ -28,7 +28,7 @@ /** * This holder will store the window Ids and it's beans for the current - * Session. We use standard SessionScoped bean to not need + * HTTP Session. We use standard SessionScoped bean to not need * to treat async-supported and similar headache. */ @SessionScoped
5fa9cbdf7684922da39b6b6fdaaa5c89a108b8a8
kotlin
rename--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java index ac115746064ef..6c88e27e4481e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java @@ -89,7 +89,7 @@ public static void initializeFromFunctionType(@NotNull FunctionDescriptorImpl fu ReceiverDescriptor.NO_RECEIVER, Collections.<TypeParameterDescriptor>emptyList(), JetStandardClasses.getValueParameters(functionDescriptor, functionType), - JetStandardClasses.obtainReturnTypeFromFunctionType(functionType), + JetStandardClasses.getReturnTypeFromFunctionType(functionType), Modality.FINAL, Visibility.LOCAL); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java index fb299e1c86eeb..55908afd1b6af 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java @@ -385,7 +385,7 @@ public static List<ValueParameterDescriptor> getValueParameters(@NotNull Functio } @NotNull - public static JetType obtainReturnTypeFromFunctionType(@NotNull JetType type) { + public static JetType getReturnTypeFromFunctionType(@NotNull JetType type) { assert isFunctionType(type); List<TypeProjection> arguments = type.getArguments(); return arguments.get(arguments.size() - 1).getType(); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java index d6e5645c5fb09..41f0705f6aae4 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java @@ -88,7 +88,7 @@ public JetType visitFunctionLiteralExpression(JetFunctionLiteralExpression expre } else { if (functionTypeExpected) { - returnType = JetStandardClasses.obtainReturnTypeFromFunctionType(expectedType); + returnType = JetStandardClasses.getReturnTypeFromFunctionType(expectedType); } returnType = context.getServices().getBlockReturnedType(functionInnerScope, bodyExpression, CoercionStrategy.COERCION_TO_UNIT, context.replaceExpectedType(returnType).replaceExpectedReturnType(returnType)); @@ -98,7 +98,7 @@ public JetType visitFunctionLiteralExpression(JetFunctionLiteralExpression expre boolean hasDeclaredValueParameters = functionLiteral.getValueParameterList() != null; if (!hasDeclaredValueParameters && functionTypeExpected) { - JetType expectedReturnType = JetStandardClasses.obtainReturnTypeFromFunctionType(expectedType); + JetType expectedReturnType = JetStandardClasses.getReturnTypeFromFunctionType(expectedType); if (JetStandardClasses.isUnit(expectedReturnType)) { functionDescriptor.setReturnType(JetStandardClasses.getUnitType()); return DataFlowUtils.checkType(JetStandardClasses.getFunctionType(Collections.<AnnotationDescriptor>emptyList(), receiver, parameterTypes, JetStandardClasses.getUnitType()), expression, context);
86bf398bdff96c03ffb34ef0a60d311557db5077
Vala
gtktemplate: Handle callbacks for detailed signals Fixes bug 720825
a
https://github.com/GNOME/vala/
diff --git a/codegen/valagtkmodule.vala b/codegen/valagtkmodule.vala index f3c9a3d41e..603ec6076f 100644 --- a/codegen/valagtkmodule.vala +++ b/codegen/valagtkmodule.vala @@ -2,7 +2,7 @@ /* valagtkmodule.vala * * Copyright (C) 2013 Jürg Billeter - * Copyright (C) 2013 Luca Bruno + * Copyright (C) 2013-2014 Luca Bruno * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -126,7 +126,13 @@ public class Vala.GtkModule : GSignalModule { var signal_name = reader.get_attribute ("name"); var handler_name = reader.get_attribute ("handler"); if (current_class != null) { - var sig = SemanticAnalyzer.symbol_lookup_inherited (current_class, signal_name.replace("-", "_")) as Signal; + var sep_idx = signal_name.index_of ("::"); + if (sep_idx >= 0) { + // detailed signal, we don't care about the detail + signal_name = signal_name.substring (0, sep_idx); + } + + var sig = SemanticAnalyzer.symbol_lookup_inherited (current_class, signal_name.replace ("-", "_")) as Signal; if (sig != null) { current_handler_to_signal_map.set (handler_name, sig); }
dcef4294453903eaa40123cea302bab5c0ceaabe
edwardkort$wwidesigner
Instrument and Tuning opening/validation functionality.
p
https://github.com/edwardkort/wwidesigner
diff --git a/WWIDesigner/src/main/com/wwidesigner/gui/FileSystemDataView.java b/WWIDesigner/src/main/com/wwidesigner/gui/FileSystemDataView.java deleted file mode 100644 index 80b346e..0000000 --- a/WWIDesigner/src/main/com/wwidesigner/gui/FileSystemDataView.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.wwidesigner.gui; - -import com.jidesoft.app.framework.DataModel; -import com.jidesoft.app.framework.DataModelException; -import com.jidesoft.app.framework.event.EventSubscriber; -import com.jidesoft.app.framework.event.SubscriberEvent; -import com.jidesoft.app.framework.file.FileFormat; -import com.jidesoft.app.framework.file.FileFormatFilenameFilter; -import com.jidesoft.app.framework.gui.ApplicationWindowsUI; -import com.jidesoft.app.framework.gui.DataViewPane; -import com.jidesoft.app.framework.gui.GUIApplication; -import com.jidesoft.app.framework.gui.feature.GlobalSelectionFeature; -import com.jidesoft.app.framework.gui.filebased.FileHandlingFeature; -import com.jidesoft.app.framework.gui.filebased.FileIcon; -import com.jidesoft.tree.TreeUtils; -import com.jidesoft.utils.SystemInfo; - -import javax.swing.*; -import javax.swing.tree.*; -import java.awt.*; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FilenameFilter; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * FileSystemDataView.java - * <p> - * Facilitates a DataView that reflects the local file system in a file tree. The corresponding <code>DataModel</code> - * should have a data type of File[] denoting the directories to show in the File tree. Double-clicking on a node - * sends the file as criteria to GUIApplication.openData(). - * <p> - * This DataView accepts GlobalSelectionFeature selections of type <code>java.io.File</code>. - * <p> - * Used in demos: <code>SplitCodeEditor</code> - */ -@SuppressWarnings("serial") -public class FileSystemDataView extends DataViewPane implements EventSubscriber { - private JTree tree; - - @Override - protected void initializeComponents() { - // create file tree - tree = new JTree(); - tree.setRootVisible(false); - tree.addMouseListener(new TreeClickHandler()); - tree.setCellRenderer(new FileTreeRenderer()); - JScrollPane scrollPane = new JScrollPane(tree); - scrollPane.setPreferredSize(new Dimension(225, 100)); - add(scrollPane); - setPreferredSize(new Dimension(300, 150)); - - // listen to global selection - getApplication().getEventManager().subscribe(GlobalSelectionFeature.GLOBAL_SELECTION, this); - } - - /** - * Sets the tree model. - */ - @Override - public void updateView(DataModel dataModel) throws DataModelException { - // use registered formats if possible - FileHandlingFeature fileHandling = FileHandlingFeature.getFeature(getApplication()); - FileFormat formats = null; - FilenameFilter filter = null; - if(fileHandling != null) { - formats = FileFormat.combinedFileFormat(fileHandling.getSupportedFileFormats()); - filter = new FileFormatFilenameFilter(formats); - } - else { - // otherwise just files in local path - filter = new FilenameFilter() { - public boolean accept(File dir, String name) { - return ((name.endsWith(".java") || (name.endsWith(".txt")) && !name.startsWith(".")) || new File(dir, name).isDirectory()); - } - }; - } - - DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - java.util.List<File> dirs = Arrays.asList((File[])dataModel.getCriteria()); - for (File file : dirs) { - MutableTreeNode node = makeNode(filter, file); - if(node != null) { - root.add(node); - } - } - TreeModel model = new DefaultTreeModel(root); - tree.setModel(model); - } - - /* - * display the globally selected file in tree. - */ - public void doEvent(SubscriberEvent e) { - GlobalSelectionFeature sel = (GlobalSelectionFeature)e.getSource(); - if(sel.hasSelection(File.class)) { - TreeNode node = (TreeNode)TreeUtils.findTreeNode(tree, sel.getSelection()); - if(node != null) { - java.util.List<TreeNode> parents = new ArrayList<TreeNode>(); - while(node != null) { - parents.add(0, node); - node = node.getParent(); - } - TreePath path = new TreePath(parents.toArray()); - tree.setSelectionPath(path); - } - } - } - - /* - * Call GUIApplication.openData() on double-click, passing in the File as the criteria. - */ - private static class TreeClickHandler extends MouseAdapter { - public void mouseClicked(MouseEvent e) { - if(e.getClickCount() > 1) { - JTree tree = (JTree)e.getSource(); - TreePath path = tree.getSelectionPath(); - if(path != null) { - File file = (File)((DefaultMutableTreeNode)path.getLastPathComponent()).getUserObject(); - if(!file.isDirectory()) { - try { - GUIApplication application = ApplicationWindowsUI.getApplicationFromWindow(tree.getTopLevelAncestor()); - application.openData(file); - - // global selection - GlobalSelectionFeature.getFeature(application).setSelection(file); - - } catch (DataModelException e1) { - e1.printStackTrace(); - } - } - } - } - } - } - - /* - * File Tree nodes. - */ - private static DefaultMutableTreeNode makeNode(FilenameFilter filter, File file) { - if(file.isDirectory()) { - DefaultMutableTreeNode node = new DefaultMutableTreeNode(file); - File[] files = file.listFiles(filter); - for (File f : files) { - if(!f.getName().startsWith(".")) { - DefaultMutableTreeNode child = makeNode(filter, f); - if(child != null && (!f.isDirectory() || (f.isDirectory() && child.getChildCount() != 0))) { - node.add(child); - } - } - } - return node; - } - else { - if(filter.accept(file.getParentFile(), file.getName())) { - return new DefaultMutableTreeNode(file); - } - else { - return null; - } - } - } - - /* - * Renderer for File nodes. - */ - private static class FileTreeRenderer extends DefaultTreeCellRenderer { - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { - File file = (File)((DefaultMutableTreeNode)value).getUserObject(); - JLabel label = (JLabel)super.getTreeCellRendererComponent(tree, file == null ? "Root" : file.getName(), sel, expanded, leaf, - row, hasFocus); - if(file != null) { - if(!SystemInfo.isMacOSX()) { - if(!file.isDirectory()) { - label.setIcon(new FileIcon(FileFormat.getExtension(file))); - } - } - } - return label; - } - } -} \ No newline at end of file diff --git a/WWIDesigner/src/main/com/wwidesigner/gui/NafOptimizationRunner.java b/WWIDesigner/src/main/com/wwidesigner/gui/NafOptimizationRunner.java index 46993bc..ebc7514 100644 --- a/WWIDesigner/src/main/com/wwidesigner/gui/NafOptimizationRunner.java +++ b/WWIDesigner/src/main/com/wwidesigner/gui/NafOptimizationRunner.java @@ -1,5 +1,10 @@ package com.wwidesigner.gui; +import java.awt.Dimension; +import java.io.File; + +import javax.swing.Action; + import com.jidesoft.app.framework.ApplicationVetoException; import com.jidesoft.app.framework.DataModel; import com.jidesoft.app.framework.DataModelAdapter; @@ -7,187 +12,202 @@ import com.jidesoft.app.framework.DataModelException; import com.jidesoft.app.framework.JDAFConstants; import com.jidesoft.app.framework.SecondaryBasicDataModel; -import com.jidesoft.app.framework.event.SubscriberEvent; +import com.jidesoft.app.framework.event.EventManager; import com.jidesoft.app.framework.file.FileDataModel; -import com.jidesoft.app.framework.file.FileFormat; import com.jidesoft.app.framework.file.TextFileFormat; import com.jidesoft.app.framework.gui.ActionKeys; import com.jidesoft.app.framework.gui.ApplicationWindowsUI; import com.jidesoft.app.framework.gui.DataViewAdapter; import com.jidesoft.app.framework.gui.DataViewEvent; import com.jidesoft.app.framework.gui.DataViewPane; -import com.jidesoft.app.framework.gui.GUIApplication; import com.jidesoft.app.framework.gui.MenuConstants; import com.jidesoft.app.framework.gui.MessageDialogRequest; -import com.jidesoft.app.framework.gui.SplitApplicationUI; import com.jidesoft.app.framework.gui.actions.ComponentAction; import com.jidesoft.app.framework.gui.feature.AutoInstallActionsFeature; import com.jidesoft.app.framework.gui.feature.GlobalSelectionFeature; import com.jidesoft.app.framework.gui.filebased.FileBasedApplication; -import com.jidesoft.app.framework.gui.filebased.FileIcon; -import com.jidesoft.app.framework.gui.filebased.OpenFileAction; import com.jidesoft.app.framework.gui.framed.DockableConfiguration; import com.jidesoft.app.framework.gui.framed.DockingApplicationFeature; -import com.jidesoft.app.framework.gui.framed.FrameConfiguration; -import com.jidesoft.app.framework.gui.framed.FramedApplicationFeature; import com.jidesoft.app.framework.gui.framed.ToggleFrameAction; import com.jidesoft.docking.DockContext; -import com.jidesoft.swing.JideTabbedPane; -import com.jidesoft.tree.TreeUtils; -import com.jidesoft.utils.SystemInfo; - -import javax.swing.*; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -import java.awt.*; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FilenameFilter; -import java.util.ArrayList; /** * DockedTextEditor2.java * <p/> - * This example is similar to DockedTextEditor, but uses the DockingApplicationFeature. No docking content it provided, - * this is just to show how to facilitate Dockable DataViews. Notice that the DataModels used by the docking are of - * secondary status. This is required. + * This example is similar to DockedTextEditor, but uses the + * DockingApplicationFeature. No docking content it provided, this is just to + * show how to facilitate Dockable DataViews. Notice that the DataModels used by + * the docking are of secondary status. This is required. */ -public class NafOptimizationRunner extends FileBasedApplication { +public class NafOptimizationRunner extends FileBasedApplication +{ - public static void main(String[] args) { + public static void main(String[] args) + { com.jidesoft.utils.Lm.verifyLicense("Edward Kort", "WWIDesigner", "DfuwPRAUR5KQYgePf:CH0LWIp63V8cs2"); - new NafOptimizationRunner().run(args); - } - - public NafOptimizationRunner() { - super("NAF Optimization Runner", TDI_APPLICATION_STYLE); - addFileMapping(new TextFileFormat("xml", "XML"), CodeEditorView.class); - - getApplicationUIManager().setUseJideDockingFramework(true); - getApplicationUIManager().setUseJideActionFramework(true); - - addApplicationFeature(new AutoInstallActionsFeature()); - - // no single tab display - - DockingApplicationFeature docking = new DockingApplicationFeature(); - DockableConfiguration config = new DockableConfiguration(); - - // config for "Console" model-view - config.setFrameName("Console"); - config.setInitState(DockContext.STATE_FRAMEDOCKED); - config.setInitSide(DockContext.DOCK_SIDE_SOUTH); - config.setInitIndex(0); - config.setDataModelClass(SecondaryBasicDataModel.class); - config.setDataViewClass(DockedView.class); - docking.addDockableMapping(config); - - // config for "Study" pane - config = new DockableConfiguration(); - config.setFrameName("Study"); - config.setInitState(DockContext.STATE_FRAMEDOCKED); - config.setInitSide(DockContext.DOCK_SIDE_WEST); - config.setInitIndex(0); - config.setDataModelClass(SecondaryBasicDataModel.class); - config.setDataViewClass(DockedView.class); - docking.addDockableMapping(config); - - // add feature - addApplicationFeature(docking); - - Action action = new OpenFileAction("Instrument", true); - action.putValue(AutoInstallActionsFeature.MENU_ID, MenuConstants.FILE_MENU_ID); - action.putValue(Action.NAME, "Open Instrument..."); - getActionMap().put("instrument", action); - - action = new OpenFileAction("Tuning", true); - action.putValue(AutoInstallActionsFeature.MENU_ID, MenuConstants.FILE_MENU_ID); - action.putValue(Action.NAME, "Open Tuning..."); - getActionMap().put("tuning", action); - - getActionMap().get("open").setEnabled(false); - - // application settings - setExitApplicationOnLastDataView(false); - setNewDataOnRun(false); - - action = new ToggleFrameAction("Console", true); - action.putValue(AutoInstallActionsFeature.MENU_ID, MenuConstants.WINDOW_MENU_ID); - getActionMap().put("consoleToggle", action); - - action = new ToggleFrameAction("Study", true); - action.putValue(AutoInstallActionsFeature.MENU_ID, MenuConstants.WINDOW_MENU_ID); - getActionMap().put("studyToggle", action); - - // The stock JDAF UndoAction and RedoAction are focused on the state of - // the UndoManager of the focused DataModel. But the CodeEditor has its - // own Undo and Redo actions. So we use a ComponentAction which will - // automatically delegate to the CodeEditors Undo and Redo actions in its - // ActionMap when the CodeEditor is focused - getActionMap().put(ActionKeys.UNDO, new ComponentAction("undo")); - getActionMap().put(ActionKeys.REDO, new ComponentAction("redo")); - - // add global selection - addApplicationFeature(new GlobalSelectionFeature(false, true)); - - // set the global selection when a file editor is activated - addDataViewListener(new DataViewAdapter() { - @Override - public void dataViewActivated(DataViewEvent e) { - DataModel model = getDataModel(e.getDataView()); - if (e.isPrimary() && model instanceof FileDataModel) { - File file = ((FileDataModel) model).getFile(); - - // global selection - GlobalSelectionFeature.getFeature(NafOptimizationRunner.this).setSelection(file); - } - } - }); - - // window size - ApplicationWindowsUI windowsUI = getApplicationUIManager().getWindowsUI(); - windowsUI.setPreferredWindowSize(windowsUI.getPreferredMaximumWindowSize()); - - getApplicationUIManager().setUseJideDocumentPane(true); - addDataModelListener(new DataModelAdapter() { - @Override - public void dataModelClosing(DataModelEvent dataModelEvent) throws ApplicationVetoException { - DataModel dataModel = dataModelEvent.getDataModel(); - if (dataModel.isDirty()) { - - int reply = MessageDialogRequest - .showConfirmDialog(NafOptimizationRunner.this, "Would you like to save before closing", "Warning", - MessageDialogRequest.YES_NO_CANCEL_DIALOG, - MessageDialogRequest.WARNING_STYLE); - if (reply == JDAFConstants.RESPONSE_NO) { - return; - } - else if (reply == JDAFConstants.RESPONSE_YES) { - try { - dataModel.saveData(); - } - catch (DataModelException ex) { - throw new ApplicationVetoException("Failed to save data", ex); - } - } - else { - //the user cancelled - throw new ApplicationVetoException(); - } - } - } - }); - } - - - public static class DockedView extends DataViewPane { - protected void initializeComponents() { - setPreferredSize(new Dimension(300, 600)); - } - } + new NafOptimizationRunner().run(args); + } + + public NafOptimizationRunner() + { + super("NAF Optimization Runner", TDI_APPLICATION_STYLE); + addFileMapping(new TextFileFormat("xml", "XML"), CodeEditorView.class); + + getApplicationUIManager().setUseJideDockingFramework(true); + getApplicationUIManager().setUseJideActionFramework(true); + + addApplicationFeature(new AutoInstallActionsFeature()); + + // no single tab display + + DockingApplicationFeature docking = new DockingApplicationFeature(); + DockableConfiguration config = new DockableConfiguration(); + + // config for "Console" model-view + config.setFrameName("Console"); + config.setInitState(DockContext.STATE_FRAMEDOCKED); + config.setInitSide(DockContext.DOCK_SIDE_SOUTH); + config.setInitIndex(1); + config.setCriteria(System.out.toString()); + config.setDataModelClass(SecondaryBasicDataModel.class); + config.setDataViewClass(TextView.class); + docking.addDockableMapping(config); + + // config for "Study" pane + config = new DockableConfiguration(); + config.setFrameName("Study"); + config.setInitState(DockContext.STATE_FRAMEDOCKED); + config.setInitSide(DockContext.DOCK_SIDE_WEST); + config.setInitIndex(0); + config.setDataModelClass(SecondaryBasicDataModel2.class); + config.setDataViewClass(StudyView.class); + docking.addDockableMapping(config); + + // add feature + addApplicationFeature(docking); + + // application settings + setExitApplicationOnLastDataView(false); + setNewDataOnRun(false); + + Action action = new ToggleFrameAction("Console", true); + action.putValue(AutoInstallActionsFeature.MENU_ID, + MenuConstants.WINDOW_MENU_ID); + getActionMap().put("consoleToggle", action); + + action = new ToggleFrameAction("Study", true); + action.putValue(AutoInstallActionsFeature.MENU_ID, + MenuConstants.WINDOW_MENU_ID); + getActionMap().put("studyToggle", action); + + // The stock JDAF UndoAction and RedoAction are focused on the state of + // the UndoManager of the focused DataModel. But the CodeEditor has its + // own Undo and Redo actions. So we use a ComponentAction which will + // automatically delegate to the CodeEditors Undo and Redo actions in + // its + // ActionMap when the CodeEditor is focused + getActionMap().put(ActionKeys.UNDO, new ComponentAction("undo")); + getActionMap().put(ActionKeys.REDO, new ComponentAction("redo")); + + // add global selection + addApplicationFeature(new GlobalSelectionFeature(false, true)); + + // set the global selection when a file editor is activated + addDataViewListener(new DataViewAdapter() + { + @Override + public void dataViewActivated(DataViewEvent e) + { + DataModel model = getDataModel(e.getDataView()); + if (e.isPrimary() && model instanceof FileDataModel) + { + File file = ((FileDataModel) model).getFile(); + + // global selection + GlobalSelectionFeature.getFeature( + NafOptimizationRunner.this).setSelection(file); + } + } + }); + + // window size + ApplicationWindowsUI windowsUI = getApplicationUIManager() + .getWindowsUI(); + windowsUI.setPreferredWindowSize(windowsUI + .getPreferredMaximumWindowSize()); + + EventManager eventManager = getEventManager(); + eventManager.addEvent("FileOpened"); + eventManager.addEvent("FileClosed"); + + getApplicationUIManager().setUseJideDocumentPane(true); + addDataModelListener(new DataModelAdapter() + { + @Override + public void dataModelClosing(DataModelEvent dataModelEvent) + throws ApplicationVetoException + { + DataModel dataModel = dataModelEvent.getDataModel(); + if (dataModel.isDirty()) + { + + int reply = MessageDialogRequest.showConfirmDialog( + NafOptimizationRunner.this, + "Would you like to save before closing", "Warning", + MessageDialogRequest.YES_NO_CANCEL_DIALOG, + MessageDialogRequest.WARNING_STYLE); + if (reply == JDAFConstants.RESPONSE_NO) + { + return; + } + else if (reply == JDAFConstants.RESPONSE_YES) + { + try + { + dataModel.saveData(); + } + catch (DataModelException ex) + { + throw new ApplicationVetoException( + "Failed to save data", ex); + } + } + else + { + // the user cancelled + throw new ApplicationVetoException(); + } + } + } + + @Override + public void dataModelOpened(DataModelEvent dataModelEvent) + { + NafOptimizationRunner.this.getEventManager().publish( + "FileOpened", dataModelEvent); + } + + @Override + public void dataModelClosed(DataModelEvent dataModelEvent) + { + NafOptimizationRunner.this.getEventManager().publish( + "FileClosed", dataModelEvent); + } + }); + + } + + public static class DockedView extends DataViewPane + { + protected void initializeComponents() + { + setPreferredSize(new Dimension(300, 600)); + } + } + + public static class SecondaryBasicDataModel2 extends + SecondaryBasicDataModel + { + } } diff --git a/WWIDesigner/src/main/com/wwidesigner/gui/StudyModel.java b/WWIDesigner/src/main/com/wwidesigner/gui/StudyModel.java new file mode 100644 index 0000000..bd7b801 --- /dev/null +++ b/WWIDesigner/src/main/com/wwidesigner/gui/StudyModel.java @@ -0,0 +1,111 @@ +/** + * + */ +package com.wwidesigner.gui; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * @author kort + * + */ +public class StudyModel +{ + List<Category> categories; + + /** + * + */ + public StudyModel() + { + categories = new ArrayList<Category>(); + categories.add(new Category("Instrument")); + categories.add(new Category("Tuning")); + Category optimizers = new Category("Optimizer"); + optimizers.addSub("Fipple-factor Optimizer", null); + optimizers.addSub("Hole-grouping Optimizer", null); + categories.add(optimizers); + } + + public List<Category> getCategories() + { + return categories; + } + + public Category getCategory(String name) + { + Category category = null; + + for (Category thisCategory : categories) + { + if (thisCategory.toString().equals(name)) + { + category = thisCategory; + break; + } + } + + return category; + } + + public void setCategorySelection(Category category, String subCategoryName) + { + for (Category thisCategory : categories) + { + if (thisCategory.name.equals(category.name)) + { + thisCategory.setSelectedSub(subCategoryName); + } + } + } + + public static class Category + { + private String name; + private Map<String, Object> subs; + private String selectedSub; + + public Category(String name) + { + this.name = name; + } + + public String toString() + { + return name; + } + + public void addSub(String name, Object sub) + { + if (subs == null) + { + subs = new TreeMap<String, Object>(); + } + subs.put(name, sub); + } + + public void removeSub(String name) + { + subs.remove(name); + } + + public Map<String, Object> getSubs() + { + return subs == null ? new TreeMap<String, Object>() : subs; + } + + public void setSelectedSub(String key) + { + selectedSub = key; + } + + public String getSelectedSub() + { + return selectedSub; + } + } + +} diff --git a/WWIDesigner/src/main/com/wwidesigner/gui/StudyView.java b/WWIDesigner/src/main/com/wwidesigner/gui/StudyView.java new file mode 100644 index 0000000..bd3e635 --- /dev/null +++ b/WWIDesigner/src/main/com/wwidesigner/gui/StudyView.java @@ -0,0 +1,166 @@ +/** + * + */ +package com.wwidesigner.gui; + +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; + +import com.jidesoft.app.framework.DataModel; +import com.jidesoft.app.framework.DataModelEvent; +import com.jidesoft.app.framework.event.EventSubscriber; +import com.jidesoft.app.framework.event.SubscriberEvent; +import com.jidesoft.app.framework.file.FileDataModel; +import com.jidesoft.app.framework.gui.DataViewPane; +import com.jidesoft.tree.TreeUtils; +import com.wwidesigner.geometry.bind.GeometryBindFactory; +import com.wwidesigner.gui.StudyModel.Category; +import com.wwidesigner.note.bind.NoteBindFactory; +import com.wwidesigner.util.BindFactory; + +/** + * @author kort + * + */ +public class StudyView extends DataViewPane implements EventSubscriber +{ + private JTree tree; + private StudyModel study; + + @Override + protected void initializeComponents() + { + // create file tree + tree = new JTree(); + tree.setRootVisible(false); + tree.getSelectionModel().setSelectionMode( + TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + tree.addMouseListener(new MouseAdapter() + { + public void mousePressed(MouseEvent e) + { + TreePath path = tree.getPathForLocation(e.getX(), e.getY()); + if (path != null) + { + if (path.getPathCount() == 3) // it is a leaf + { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) path + .getLastPathComponent(); + DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node + .getParent(); + study.setCategorySelection( + (Category) parentNode.getUserObject(), + (String) node.getUserObject()); + } + updateView(); + } + } + }); + JScrollPane scrollPane = new JScrollPane(tree); + scrollPane.setPreferredSize(new Dimension(225, 100)); + add(scrollPane); + + study = new StudyModel(); + updateView(); + + getApplication().getEventManager().subscribe("FileOpened", this); + getApplication().getEventManager().subscribe("FileClosed", this); + } + + public void updateView() + { + DefaultMutableTreeNode root = new DefaultMutableTreeNode(); + List<TreePath> selectionPaths = new ArrayList<TreePath>(); + for (Category category : study.getCategories()) + { + DefaultMutableTreeNode node = new DefaultMutableTreeNode(category); + if (node != null) + { + node.setAllowsChildren(true); + root.add(node); + } + Map<String, Object> subcategories = category.getSubs(); + String selectedSub = category.getSelectedSub(); + for (String name : subcategories.keySet()) + { + DefaultMutableTreeNode childNode = new DefaultMutableTreeNode( + name); + if (childNode != null) + { + node.add(childNode); + if (name.equals(selectedSub)) + { + selectionPaths.add(new TreePath(childNode.getPath())); + } + } + } + } + TreeModel model = new DefaultTreeModel(root); + tree.setModel(model); + TreeUtils.expandAll(tree); + tree.setSelectionPaths(selectionPaths.toArray(new TreePath[0])); + } + + @Override + public void doEvent(SubscriberEvent event) + { + DataModel source = ((DataModelEvent) event.getSource()).getDataModel(); + if (source instanceof FileDataModel) + { + String data = (String) ((FileDataModel) source).getData(); + String categoryName = getCategoryName(data); + if (categoryName != null) + { + Category category = study.getCategory(categoryName); + if (event.getEvent().equals("FileOpened")) + { + category.addSub(source.getName(), source); + updateView(); + } + else if (event.getEvent().equals("FileClosed")) + { + String subName = source.getName(); + if (subName.equals(category.getSelectedSub())) + { + category.setSelectedSub(null); + } + category.removeSub(subName); + + updateView(); + } + } + } + } + + private String getCategoryName(String xmlString) + { + // Check Instrument + BindFactory bindFactory = GeometryBindFactory.getInstance(); + if (bindFactory.isValidXml(xmlString, "Instrument", true)) + { + return "Instrument"; + } + + // Check Tuning + bindFactory = NoteBindFactory.getInstance(); + if (bindFactory.isValidXml(xmlString, "Tuning", true)) + { + return "Tuning"; + } + + return null; + } + +} diff --git a/WWIDesigner/src/main/com/wwidesigner/util/BindFactory.java b/WWIDesigner/src/main/com/wwidesigner/util/BindFactory.java index 34a2ef6..83f78fc 100644 --- a/WWIDesigner/src/main/com/wwidesigner/util/BindFactory.java +++ b/WWIDesigner/src/main/com/wwidesigner/util/BindFactory.java @@ -6,6 +6,7 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; +import java.io.StringReader; import java.io.Writer; import java.util.Map; @@ -13,6 +14,7 @@ import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; @@ -60,7 +62,7 @@ public Object unmarshalXml(String inputFileName, boolean fileInClasspath, inputFileName = getPathFromName(inputFileName); } - return unmarshalXml(inputFileName, toDomainObject); + return unmarshalXml(new File(inputFileName), toDomainObject); } /** @@ -74,11 +76,26 @@ public Object unmarshalXml(File inputFile) throws Exception return unmarshalXml(inputFile, false); } - public Object unmarshalXml(String inputFileName, boolean toDomainObject) + public Object unmarshalXml(String xmlString, boolean toDomainObject) throws Exception { - File inputFile = new File(inputFileName); - return unmarshalXml(inputFile, toDomainObject); + JAXBContext jc = JAXBContext.newInstance(packagePath); + Unmarshaller unmarshaller = jc.createUnmarshaller(); + + // Do validation + unmarshaller.setSchema(getSchema()); + + StreamSource strmSource = new StreamSource(new StringReader(xmlString)); + Object bindObject = ((JAXBElement<?>) unmarshaller + .unmarshal(strmSource)).getValue(); + + if (!toDomainObject) + { + return bindObject; + } + + Object domainObject = mapObject(bindObject, bindToDomainMap); + return domainObject; } public Object unmarshalXml(File inputFile, boolean toDomainObject) @@ -176,5 +193,21 @@ public File getFileFromName(String name) throws FileNotFoundException return new File(filePath); } + + public boolean isValidXml(String xmlString, String rootElementName, boolean isDomainObject) { + try { + Object root = unmarshalXml(xmlString, isDomainObject); + String rootPath = packagePath; + if (isDomainObject) { + rootPath = rootPath.substring(0, rootPath.lastIndexOf('.')); + } + Class<?> rootElement = Class.forName(rootPath + "." + rootElementName); + rootElement.cast(root); + return true; + } + catch (Exception e) { + return false; + } + } }
cb378074d6e3fd71a3ab1681a5b1f9c61239245b
restlet-framework-java
- Fixed NIO client blocking due to reuse attempt- of a busy connection--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java b/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java index 12616a9647..c62b58dec4 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java @@ -78,7 +78,7 @@ * <tr> * <td>minThreads</td> * <td>int</td> - * <td>5</td> + * <td>1</td> * <td>Minimum number of worker threads waiting to service calls, even if they * are idle.</td> * </tr> @@ -152,7 +152,8 @@ * <td>boolean</td> * <td>true</td> * <td>Indicates if direct NIO buffers should be allocated instead of regular - * buffers. See NIO's ByteBuffer Javadocs.</td> + * buffers. See NIO's ByteBuffer Javadocs. Note that tracing must be disabled to + * use direct buffers.</td> * </tr> * <tr> * <td>transport</td> @@ -418,7 +419,7 @@ public int getMaxThreads() { */ public int getMinThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( - "minThreads", "5")); + "minThreads", "1")); } /** @@ -502,13 +503,15 @@ public boolean isClientSide() { public abstract boolean isControllerDaemon(); /** - * Indicates if direct NIO buffers should be used. + * Indicates if direct NIO buffers should be used. Note that tracing must be + * disabled to use direct buffers. * * @return True if direct NIO buffers should be used. */ public boolean isDirectBuffers() { - return Boolean.parseBoolean(getHelpedParameters().getFirstValue( - "directBuffers", "true")); + return !isTracing() + && Boolean.parseBoolean(getHelpedParameters().getFirstValue( + "directBuffers", "true")); } /** diff --git a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java index 7dbd70cfca..4e15d9e088 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java @@ -393,9 +393,13 @@ protected Connection<Client> getBestConnection(Request request) if (socketAddress.equals(currConn.getSocketAddress())) { if (currConn.getState().equals(ConnectionState.OPEN) + && currConn.getInboundWay().getMessageState() + .equals(MessageState.IDLE) && currConn.getInboundWay().getIoState() .equals(IoState.IDLE) && currConn.getInboundWay().getMessages().isEmpty() + && currConn.getOutboundWay().getMessageState() + .equals(MessageState.IDLE) && currConn.getOutboundWay().getIoState() .equals(IoState.IDLE) && currConn.getOutboundWay().getMessages() diff --git a/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java b/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java index 2d407cf3ca..e2477ad0cc 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java +++ b/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java @@ -205,7 +205,7 @@ public void postRead(int length) { * been reached. */ public int read(ByteBuffer targetBuffer) throws IOException { - int totalRead = 0; + int result = 0; int currentRead = 0; boolean tryAgain = true; @@ -231,7 +231,7 @@ public int read(ByteBuffer targetBuffer) throws IOException { targetBuffer.put(getByteBuffer().get()); } - totalRead += currentRead; + result += currentRead; } if (getByteBuffer().remaining() == 0) { @@ -248,7 +248,7 @@ public int read(ByteBuffer targetBuffer) throws IOException { } } - return totalRead; + return result; } /**
7d5abf3972158a3b24d2e075c20bde604de3e813
Valadoc
libvaladoc: reorder @param
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala index d0ea807cbd..0655ce02b9 100755 --- a/src/libvaladoc/html/htmlrenderer.vala +++ b/src/libvaladoc/html/htmlrenderer.vala @@ -115,6 +115,38 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer { element.accept_children (this); taglets = element.find_taglets ((Api.Node) _container, typeof (Taglets.Param)); + taglets.sort ((_a, _b) => { + Taglets.Param a = _a as Taglets.Param; + Taglets.Param b = _b as Taglets.Param; + + if (a.position < 0 && b.position < 0) { + int cmp = a.parameter_name.ascii_casecmp (b.parameter_name); + if (cmp == 0) { + return 0; + } + + if (a.parameter_name == "...") { + return 1; + } + + if (b.parameter_name == "...") { + return -1; + } + + return cmp; + } + + if (a.position < 0) { + return 1; + } + + if (b.position < 0) { + return -1; + } + + return a.position - b.position; + }); + write_taglets ( () => { writer.start_tag ("h2", {"class", "main_title"}).text ("Parameters:").end_tag ("h2"); diff --git a/src/libvaladoc/taglets/tagletparam.vala b/src/libvaladoc/taglets/tagletparam.vala index db0d962c35..6dfb235ef2 100755 --- a/src/libvaladoc/taglets/tagletparam.vala +++ b/src/libvaladoc/taglets/tagletparam.vala @@ -27,7 +27,9 @@ using Valadoc.Content; public class Valadoc.Taglets.Param : InlineContent, Taglet, Block { public string parameter_name { internal set; get; } - public Api.Symbol? parameter { private set; get; } + public weak Api.Symbol? parameter { private set; get; } + + public int position { private set; get; default = -1; } public Rule? get_parser_rule (Rule run_rule) { return Rule.seq ({ @@ -40,7 +42,6 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block { public override void check (Api.Tree api_root, Api.Node container, ErrorReporter reporter, Settings settings) { // Check for the existence of such a parameter - this.parameter = null; if (parameter_name == "...") { @@ -48,16 +49,22 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block { foreach (Api.Node param in params) { if (((Api.FormalParameter) param).ellipsis) { this.parameter = (Api.Symbol) param; + this.position = params.size - 1; break; } } } else { 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) { if (param.name == parameter_name) { this.parameter = (Api.Symbol) param; + this.position = pos; break; } + + pos++; } }
9cd153c55aa071528a013ecd28014734346d4127
drools
Changes to resolve issues discovered in integration- tests--git-svn-id: https://svn.jboss.org/repos/labs/trunk/labs/jbossrules@3441 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java index 4d01a0107dc..163b8d19d8e 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java @@ -1,6 +1,7 @@ package org.drools.integrationtests; import java.io.InputStreamReader; +import java.util.ArrayList; import java.util.List; import org.drools.Cheese; @@ -16,53 +17,150 @@ protected RuleBase getRuleBase() throws Exception { return new org.drools.leaps.RuleBaseImpl(); } - /** - * Leaps query requires fireAll run before any probing can be done. this - * test mirrors one in IntegrationCases.java with addition of call to - * workingMemory.fireAll to facilitate query execution - */ + /** + * Leaps query requires fireAll run before any probing can be done. this + * test mirrors one in IntegrationCases.java with addition of call to + * workingMemory.fireAll to facilitate query execution + */ public void testQuery() throws Exception { PackageBuilder builder = new PackageBuilder(); - builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "simple_query_test.drl" ) ) ); + builder.addPackageFromDrl(new InputStreamReader(getClass() + .getResourceAsStream("simple_query_test.drl"))); Package pkg = builder.getPackage(); - + RuleBase ruleBase = getRuleBase(); - ruleBase.addPackage( pkg ); + ruleBase.addPackage(pkg); WorkingMemory workingMemory = ruleBase.newWorkingMemory(); - + Cheese stilton = new Cheese("stinky", 5); - workingMemory.assertObject( stilton ); - workingMemory.fireAllRules(); - List results = workingMemory.getQueryResults( "simple query" ); - assertEquals(1, results.size()); + workingMemory.assertObject(stilton); + workingMemory.fireAllRules();// <=== the only difference from the base test case + List results = workingMemory.getQueryResults("simple query"); + assertEquals(1, results.size()); } - + + /** + * leaps does not create activations upfront hence its inability to apply + * auto-focus predicate in the same way as reteoo does. activations in + * reteoo sense created in the order rules would fire based what used to be + * called conflict resolution. + * + * So, while agenda groups feature works it mirrors reteoo behaviour up to + * the point where auto-focus comes into play. At this point leaps and + * reteoo are different at which point auto-focus should "fire". + * + * the other problem that relates to the lack of activations before rules + * start firing is that agenda group is removed from focus stack when agenda + * group is empty. This also affects module / focus behaviour + */ public void testAgendaGroups() throws Exception { - //not implemented yet + PackageBuilder builder = new PackageBuilder(); + builder.addPackageFromDrl(new InputStreamReader(getClass() + .getResourceAsStream("test_AgendaGroups.drl"))); + Package pkg = builder.getPackage(); + + RuleBase ruleBase = getRuleBase(); + ruleBase.addPackage(pkg); + WorkingMemory workingMemory = ruleBase.newWorkingMemory(); + + List list = new ArrayList(); + workingMemory.setGlobal("list", list); + + Cheese brie = new Cheese("brie", 12); + workingMemory.assertObject(brie); + + workingMemory.fireAllRules(); + + assertEquals(3, list.size()); + + assertEquals("MAIN", list.get(0)); // salience 10 + assertEquals("group3", list.get(1)); // salience 5. set auto focus to + // group 3 + // no group 3 activations at this point, pop it, next activation that + // can fire is MAIN + assertEquals("MAIN", list.get(2)); + // assertEquals( "group2", list.get( 3 ) ); + // assertEquals( "group4", list.get( 4 ) ); + // assertEquals( "group1", list.get( 5 ) ); + // assertEquals( "group3", list.get( 6 ) ); + // assertEquals( "group1", list.get( 7 ) ); + + workingMemory.setFocus("group2"); + workingMemory.fireAllRules(); + + assertEquals(4, list.size()); + assertEquals("group2", list.get(3)); } + /** + * exception test are leaps specific due to the fact that left hand side of + * the rule is not being evaluated until fireAllRules is called. Otherwise + * the test cases are exactly the same + */ public void testEvalException() throws Exception { - //not implemented yet + PackageBuilder builder = new PackageBuilder(); + builder.addPackageFromDrl(new InputStreamReader(getClass() + .getResourceAsStream("test_EvalException.drl"))); + Package pkg = builder.getPackage(); + + RuleBase ruleBase = getRuleBase(); + ruleBase.addPackage(pkg); + WorkingMemory workingMemory = ruleBase.newWorkingMemory(); + + Cheese brie = new Cheese("brie", 12); + + try { + workingMemory.assertObject(brie); + workingMemory.fireAllRules(); // <=== the only difference from the base test case + fail("Should throw an Exception from the Eval"); + } catch (Exception e) { + assertEquals("this should throw an exception", e.getCause() + .getMessage()); + } } public void testPredicateException() throws Exception { - //not implemented yet + PackageBuilder builder = new PackageBuilder(); + builder.addPackageFromDrl(new InputStreamReader(getClass() + .getResourceAsStream("test_PredicateException.drl"))); + Package pkg = builder.getPackage(); + + RuleBase ruleBase = getRuleBase(); + ruleBase.addPackage(pkg); + WorkingMemory workingMemory = ruleBase.newWorkingMemory(); + + Cheese brie = new Cheese("brie", 12); + + try { + workingMemory.assertObject(brie); + workingMemory.fireAllRules(); // <=== the only difference from the base test case + fail("Should throw an Exception from the Predicate"); + } catch (Exception e) { + assertEquals("this should throw an exception", e.getCause() + .getMessage()); + } } public void testReturnValueException() throws Exception { - //not implemented yet - } + PackageBuilder builder = new PackageBuilder(); + builder.addPackageFromDrl(new InputStreamReader(getClass() + .getResourceAsStream("test_ReturnValueException.drl"))); + Package pkg = builder.getPackage(); - public void testDurationWithNoLoop() { - //not implemented yet - } + RuleBase ruleBase = getRuleBase(); + ruleBase.addPackage(pkg); + WorkingMemory workingMemory = ruleBase.newWorkingMemory(); - public void testNoLoop() throws Exception { - //not implemented yet - } - - public void testDynamicFunction() { - //ERRROR HERE ! + Cheese brie = new Cheese("brie", 12); + + try { + workingMemory.assertObject(brie); + workingMemory.fireAllRules(); // <=== the only difference from the base test case + fail("Should throw an Exception from the ReturnValue"); + } catch (Exception e) { + assertEquals("this should throw an exception", e.getCause() + .getMessage()); + } } } diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java index 002eca68fb7..c75f8edb6b6 100644 --- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java @@ -78,13 +78,11 @@ abstract public class AbstractWorkingMemory /** The actual memory for the <code>JoinNode</code>s. */ private final PrimitiveLongMap nodeMemories = new PrimitiveLongMap( 32, 8 ); - - /** Application data which is associated with this memory. */ - protected final Map applicationData = new HashMap(); - /** Handle-to-object mapping. */ protected final PrimitiveLongMap objects = new PrimitiveLongMap( 32, 8 ); + /** Global values which are associated with this memory. */ + private final Map globals = new HashMap(); /** Object-to-handle mapping. */ protected final Map identityMap = new IdentityMap(); @@ -164,14 +162,14 @@ FactHandle newFactHandle() { * @see WorkingMemory */ public Map getGlobals() { - return this.applicationData; + return this.globals; } /** * @see WorkingMemory */ public Object getGlobal(String name) { - return this.applicationData.get( name ); + return this.globals.get( name ); } /** diff --git a/drools-core/src/main/java/org/drools/leaps/FactTable.java b/drools-core/src/main/java/org/drools/leaps/FactTable.java index 4be84e10208..83c0468c27e 100644 --- a/drools-core/src/main/java/org/drools/leaps/FactTable.java +++ b/drools-core/src/main/java/org/drools/leaps/FactTable.java @@ -20,8 +20,9 @@ import java.util.Iterator; import java.util.Set; +import org.drools.common.PropagationContextImpl; import org.drools.leaps.util.Table; -import org.drools.leaps.util.TableOutOfBoundException; +import org.drools.spi.PropagationContext; /** * Implementation of a container to store data elements used throughout the @@ -41,14 +42,13 @@ class FactTable extends Table { * dynamic rule management support. used to push facts on stack again after * fireAllRules by working memory and adding of a new rule after that */ - private boolean reseededStack = false; + private boolean reseededStack = false; /** - * Tuples that are either already on agenda or are very close (missing exists or - * have not facts matching) + * Tuples that are either already on agenda or are very close (missing + * exists or have not facts matching) */ - - private final Set tuples; + private final Set tuples; /** * initializes base LeapsTable with appropriate Comparator and positive and @@ -58,8 +58,8 @@ class FactTable extends Table { * @param ruleConflictResolver */ public FactTable(ConflictResolver conflictResolver) { - super( conflictResolver.getFactConflictResolver() ); - this.rules = new RuleTable( conflictResolver.getRuleConflictResolver() ); + super(conflictResolver.getFactConflictResolver()); + this.rules = new RuleTable(conflictResolver.getRuleConflictResolver()); this.tuples = new HashSet(); } @@ -69,11 +69,10 @@ public FactTable(ConflictResolver conflictResolver) { * @param workingMemory * @param ruleHandle */ - public void addRule(WorkingMemoryImpl workingMemory, - RuleHandle ruleHandle) { - this.rules.add( ruleHandle ); + public void addRule(WorkingMemoryImpl workingMemory, RuleHandle ruleHandle) { + this.rules.add(ruleHandle); // push facts back to stack if needed - this.checkAndAddFactsToStack( workingMemory ); + this.checkAndAddFactsToStack(workingMemory); } /** @@ -82,7 +81,7 @@ public void addRule(WorkingMemoryImpl workingMemory, * @param ruleHandle */ public void removeRule(RuleHandle ruleHandle) { - this.rules.remove( ruleHandle ); + this.rules.remove(ruleHandle); } /** @@ -95,20 +94,21 @@ public void removeRule(RuleHandle ruleHandle) { * */ private void checkAndAddFactsToStack(WorkingMemoryImpl workingMemory) { - if ( this.reseededStack ) { - this.setReseededStack( false ); + if (this.reseededStack) { + this.setReseededStack(false); + + PropagationContextImpl context = new PropagationContextImpl( + workingMemory.nextPropagationIdCounter(), + PropagationContext.ASSERTION, null, null); + // let's only add facts below waterline - added before rule is added // rest would be added to stack automatically - Handle factHandle = new FactHandleImpl( workingMemory.getIdLastFireAllAt(), - null ); - try { - for ( Iterator it = this.tailIterator( factHandle, - factHandle ); it.hasNext(); ) { - workingMemory.pushTokenOnStack( new Token( workingMemory, - (FactHandleImpl) it.next() ) ); - } - } catch ( TableOutOfBoundException e ) { - // should never get here + Handle factHandle = new FactHandleImpl(workingMemory + .getIdLastFireAllAt(), null); + for (Iterator it = this.tailIterator(factHandle, factHandle); it + .hasNext();) { + workingMemory.pushTokenOnStack(new Token(workingMemory, + (FactHandleImpl) it.next(), context)); } } } @@ -139,22 +139,23 @@ public Iterator getRulesIterator() { public String toString() { StringBuffer ret = new StringBuffer(); - for ( Iterator it = this.iterator(); it.hasNext(); ) { + for (Iterator it = this.iterator(); it.hasNext();) { FactHandleImpl handle = (FactHandleImpl) it.next(); - ret.append( "\n" + handle + "[" + handle.getObject() + "]" ); + ret.append("\n" + handle + "[" + handle.getObject() + "]"); } - ret.append( "\nTuples :" ); + ret.append("\nTuples :"); - for ( Iterator it = this.tuples.iterator(); it.hasNext(); ) { - ret.append( "\n" + it.next() ); + for (Iterator it = this.tuples.iterator(); it.hasNext();) { + ret.append("\n" + it.next()); } - ret.append( "\nRules :" ); + ret.append("\nRules :"); - for ( Iterator it = this.rules.iterator(); it.hasNext(); ) { + for (Iterator it = this.rules.iterator(); it.hasNext();) { RuleHandle handle = (RuleHandle) it.next(); - ret.append( "\n\t" + handle.getLeapsRule().getRule().getName() + "[dominant - " + handle.getDominantPosition() + "]" ); + ret.append("\n\t" + handle.getLeapsRule().getRule().getName() + + "[dominant - " + handle.getDominantPosition() + "]"); } return ret.toString(); @@ -165,10 +166,10 @@ Iterator getTuplesIterator() { } boolean addTuple(LeapsTuple tuple) { - return this.tuples.add( tuple ); + return this.tuples.add(tuple); } void removeTuple(LeapsTuple tuple) { - this.tuples.remove( tuple ); + this.tuples.remove(tuple); } } diff --git a/drools-core/src/main/java/org/drools/leaps/LeapsRule.java b/drools-core/src/main/java/org/drools/leaps/LeapsRule.java index 5748b92ce5a..6179ced1b48 100644 --- a/drools-core/src/main/java/org/drools/leaps/LeapsRule.java +++ b/drools-core/src/main/java/org/drools/leaps/LeapsRule.java @@ -18,6 +18,8 @@ import java.util.ArrayList; +import org.drools.common.ActivationQueue; +import org.drools.common.AgendaGroupImpl; import org.drools.rule.EvalCondition; import org.drools.rule.Rule; @@ -29,7 +31,7 @@ * */ class LeapsRule { - Rule rule; + Rule rule; final ColumnConstraints[] columnConstraints; @@ -37,43 +39,45 @@ class LeapsRule { final ColumnConstraints[] existsColumnConstraints; - final EvalCondition[] evalConditions; + final EvalCondition[] evalConditions; - boolean notColumnsPresent; + boolean notColumnsPresent; - boolean existsColumnsPresent; + boolean existsColumnsPresent; - boolean evalCoditionsPresent; + boolean evalCoditionsPresent; - final Class[] existsNotsClasses; + final Class[] existsNotsClasses; - public LeapsRule(Rule rule, - ArrayList columns, - ArrayList notColumns, - ArrayList existsColumns, - ArrayList evalConditions) { + public LeapsRule(Rule rule, ArrayList columns, ArrayList notColumns, + ArrayList existsColumns, ArrayList evalConditions) { this.rule = rule; - this.columnConstraints = (ColumnConstraints[]) columns.toArray( new ColumnConstraints[0] ); - this.notColumnConstraints = (ColumnConstraints[]) notColumns.toArray( new ColumnConstraints[0] ); - this.existsColumnConstraints = (ColumnConstraints[]) existsColumns.toArray( new ColumnConstraints[0] ); - this.evalConditions = (EvalCondition[]) evalConditions.toArray( new EvalCondition[0] ); + this.columnConstraints = (ColumnConstraints[]) columns + .toArray(new ColumnConstraints[0]); + this.notColumnConstraints = (ColumnConstraints[]) notColumns + .toArray(new ColumnConstraints[0]); + this.existsColumnConstraints = (ColumnConstraints[]) existsColumns + .toArray(new ColumnConstraints[0]); + this.evalConditions = (EvalCondition[]) evalConditions + .toArray(new EvalCondition[0]); this.notColumnsPresent = (this.notColumnConstraints.length != 0); this.existsColumnsPresent = (this.existsColumnConstraints.length != 0); this.evalCoditionsPresent = (this.evalConditions.length != 0); ArrayList classes = new ArrayList(); - for ( int i = 0; i < this.notColumnConstraints.length; i++ ) { - if ( classes.contains( this.notColumnConstraints[i].getClassType() ) ) { - classes.add( this.notColumnConstraints[i].getClassType() ); + for (int i = 0; i < this.notColumnConstraints.length; i++) { + if (classes.contains(this.notColumnConstraints[i].getClassType())) { + classes.add(this.notColumnConstraints[i].getClassType()); } } - for ( int i = 0; i < this.existsColumnConstraints.length; i++ ) { - if ( !classes.contains( this.existsColumnConstraints[i].getClassType() ) ) { - classes.add( this.existsColumnConstraints[i].getClassType() ); + for (int i = 0; i < this.existsColumnConstraints.length; i++) { + if (!classes.contains(this.existsColumnConstraints[i] + .getClassType())) { + classes.add(this.existsColumnConstraints[i].getClassType()); } } - this.existsNotsClasses = (Class[]) classes.toArray( new Class[0] ); + this.existsNotsClasses = (Class[]) classes.toArray(new Class[0]); } Rule getRule() { @@ -139,4 +143,30 @@ public boolean equals(Object that) { Class[] getExistsNotColumnsClasses() { return this.existsNotsClasses; } + + /** + * to simulate terminal node memory we introduce + * TerminalNodeMemory type attributes here + * + */ + private AgendaGroupImpl agendaGroup; + + private ActivationQueue lifo; + + public ActivationQueue getLifo() { + return this.lifo; + } + + public void setLifo(ActivationQueue lifo) { + this.lifo = lifo; + } + + public AgendaGroupImpl getAgendaGroup() { + return this.agendaGroup; + } + + public void setAgendaGroup(AgendaGroupImpl agendaGroup) { + this.agendaGroup = agendaGroup; + } + } diff --git a/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java b/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java index dcbbf1ea3da..1db7fa6032f 100644 --- a/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java +++ b/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java @@ -32,52 +32,51 @@ * * @author Alexander Bagerman */ -class LeapsTuple - implements - Tuple, - Serializable { - private static final long serialVersionUID = 1L; +class LeapsTuple implements Tuple, Serializable { + private static final long serialVersionUID = 1L; private final PropagationContext context; - private boolean readyForActivation; + private boolean readyForActivation; - private final FactHandleImpl[] factHandles; + private final FactHandleImpl[] factHandles; - private Set[] notFactHandles; + private Set[] notFactHandles; - private Set[] existsFactHandles; + private Set[] existsFactHandles; - private Set logicalDependencies; + private Set logicalDependencies; - private Activation activation; + private Activation activation; - private final LeapsRule leapsRule; + private final LeapsRule leapsRule; /** * agendaItem parts */ - LeapsTuple(FactHandleImpl factHandles[], - LeapsRule leapsRule, - PropagationContext context) { + LeapsTuple(FactHandleImpl factHandles[], LeapsRule leapsRule, + PropagationContext context) { this.factHandles = factHandles; this.leapsRule = leapsRule; this.context = context; - if ( this.leapsRule != null && this.leapsRule.containsNotColumns() ) { - this.notFactHandles = new HashSet[this.leapsRule.getNotColumnConstraints().length]; + if (this.leapsRule != null && this.leapsRule.containsNotColumns()) { + this.notFactHandles = new HashSet[this.leapsRule + .getNotColumnConstraints().length]; } - if ( this.leapsRule != null && this.leapsRule.containsExistsColumns() ) { - this.existsFactHandles = new HashSet[this.leapsRule.getExistsColumnConstraints().length]; + if (this.leapsRule != null && this.leapsRule.containsExistsColumns()) { + this.existsFactHandles = new HashSet[this.leapsRule + .getExistsColumnConstraints().length]; } - this.readyForActivation = (this.leapsRule == null || !this.leapsRule.containsExistsColumns()); + this.readyForActivation = (this.leapsRule == null || !this.leapsRule + .containsExistsColumns()); } /** * get rule that caused this tuple to be generated * - * @return rule + * @return rule */ LeapsRule getLeapsRule() { return this.leapsRule; @@ -95,8 +94,8 @@ LeapsRule getLeapsRule() { * @see org.drools.spi.Tuple */ public boolean dependsOn(FactHandle handle) { - for ( int i = 0, length = this.factHandles.length; i < length; i++ ) { - if ( handle.equals( this.factHandles[i] ) ) { + for (int i = 0, length = this.factHandles.length; i < length; i++) { + if (handle.equals(this.factHandles[i])) { return true; } } @@ -114,7 +113,7 @@ public FactHandle get(int col) { * @see org.drools.spi.Tuple */ public FactHandle get(Declaration declaration) { - return this.get( declaration.getColumn() ); + return this.get(declaration.getColumn()); } /** @@ -149,21 +148,21 @@ Activation getActivation() { * @see java.lang.Object */ public boolean equals(Object object) { - if ( this == object ) { + if (this == object) { return true; } - if ( object == null || !(object instanceof LeapsTuple) ) { + if (object == null || !(object instanceof LeapsTuple)) { return false; } FactHandle[] thatFactHandles = ((LeapsTuple) object).getFactHandles(); - if ( thatFactHandles.length != this.factHandles.length ) { + if (thatFactHandles.length != this.factHandles.length) { return false; } - for ( int i = 0, length = this.factHandles.length; i < length; i++ ) { - if ( !this.factHandles[i].equals( thatFactHandles[i] ) ) { + for (int i = 0, length = this.factHandles.length; i < length; i++) { + if (!this.factHandles[i].equals(thatFactHandles[i])) { return false; } @@ -184,67 +183,66 @@ boolean isReadyForActivation() { * @see java.lang.Object */ public String toString() { - StringBuffer buffer = new StringBuffer( "LeapsTuple [" + this.context.getRuleOrigin().getName() + "] " ); + StringBuffer buffer = new StringBuffer("LeapsTuple [" + + this.leapsRule.getRule().getName() + "] "); - for ( int i = 0, length = this.factHandles.length; i < length; i++ ) { - buffer.append( ((i == 0) ? "" : ", ") + this.factHandles[i] ); + for (int i = 0, length = this.factHandles.length; i < length; i++) { + buffer.append(((i == 0) ? "" : ", ") + this.factHandles[i]); } - if ( this.existsFactHandles != null ) { - buffer.append( "\nExists fact handles by position" ); - for ( int i = 0, length = this.existsFactHandles.length; i < length; i++ ) { - buffer.append( "\nposition " + i ); - for ( Iterator it = this.existsFactHandles[i].iterator(); it.hasNext(); ) { - buffer.append( "\n\t" + it.next() ); + if (this.existsFactHandles != null) { + buffer.append("\nExists fact handles by position"); + for (int i = 0, length = this.existsFactHandles.length; i < length; i++) { + buffer.append("\nposition " + i); + for (Iterator it = this.existsFactHandles[i].iterator(); it + .hasNext();) { + buffer.append("\n\t" + it.next()); } } } - if ( this.notFactHandles != null ) { - buffer.append( "\nNot fact handles by position" ); - for ( int i = 0, length = this.notFactHandles.length; i < length; i++ ) { - buffer.append( "\nposition " + i ); - for ( Iterator it = this.notFactHandles[i].iterator(); it.hasNext(); ) { - buffer.append( "\n\t" + it.next() ); + if (this.notFactHandles != null) { + buffer.append("\nNot fact handles by position"); + for (int i = 0, length = this.notFactHandles.length; i < length; i++) { + buffer.append("\nposition " + i); + for (Iterator it = this.notFactHandles[i].iterator(); it + .hasNext();) { + buffer.append("\n\t" + it.next()); } } } return buffer.toString(); } - void addNotFactHandle(FactHandle factHandle, - int index) { + void addNotFactHandle(FactHandle factHandle, int index) { this.readyForActivation = false; Set facts = this.notFactHandles[index]; - if ( facts == null ) { + if (facts == null) { facts = new HashSet(); this.notFactHandles[index] = facts; } - facts.add( factHandle ); + facts.add(factHandle); } - void removeNotFactHandle(FactHandle factHandle, - int index) { - if ( this.notFactHandles[index] != null ) { - this.notFactHandles[index].remove( factHandle ); + void removeNotFactHandle(FactHandle factHandle, int index) { + if (this.notFactHandles[index] != null) { + this.notFactHandles[index].remove(factHandle); } this.setReadyForActivation(); } - void addExistsFactHandle(FactHandle factHandle, - int index) { + void addExistsFactHandle(FactHandle factHandle, int index) { Set facts = this.existsFactHandles[index]; - if ( facts == null ) { + if (facts == null) { facts = new HashSet(); this.existsFactHandles[index] = facts; } - facts.add( factHandle ); + facts.add(factHandle); this.setReadyForActivation(); } - void removeExistsFactHandle(FactHandle factHandle, - int index) { - if ( this.existsFactHandles[index] != null ) { - this.existsFactHandles[index].remove( factHandle ); + void removeExistsFactHandle(FactHandle factHandle, int index) { + if (this.existsFactHandles[index] != null) { + this.existsFactHandles[index].remove(factHandle); } this.setReadyForActivation(); } @@ -252,16 +250,18 @@ void removeExistsFactHandle(FactHandle factHandle, private void setReadyForActivation() { this.readyForActivation = true; - if ( this.notFactHandles != null ) { - for ( int i = 0, length = this.notFactHandles.length; i < length && this.readyForActivation; i++ ) { - if ( this.notFactHandles[i].size() > 0 ) { + if (this.notFactHandles != null) { + for (int i = 0, length = this.notFactHandles.length; i < length + && this.readyForActivation; i++) { + if (this.notFactHandles[i].size() > 0) { this.readyForActivation = false; } } } - if ( this.existsFactHandles != null ) { - for ( int i = 0, length = this.existsFactHandles.length; i < length && this.readyForActivation; i++ ) { - if ( this.existsFactHandles[i].size() == 0 ) { + if (this.existsFactHandles != null) { + for (int i = 0, length = this.existsFactHandles.length; i < length + && this.readyForActivation; i++) { + if (this.existsFactHandles[i].size() == 0) { this.readyForActivation = false; } } @@ -273,14 +273,14 @@ PropagationContext getContext() { } void addLogicalDependency(FactHandle handle) { - if ( this.logicalDependencies == null ) { + if (this.logicalDependencies == null) { this.logicalDependencies = new HashSet(); } - this.logicalDependencies.add( handle ); + this.logicalDependencies.add(handle); } Iterator getLogicalDependencies() { - if ( this.logicalDependencies != null ) { + if (this.logicalDependencies != null) { return this.logicalDependencies.iterator(); } return null; 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 2784906ebef..b5d0e71c94e 100644 --- a/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java +++ b/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java @@ -17,7 +17,6 @@ */ import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -30,6 +29,7 @@ import org.drools.WorkingMemory; import org.drools.rule.InvalidPatternException; import org.drools.rule.Package; +import org.drools.rule.PackageCompilationData; import org.drools.rule.Rule; import org.drools.spi.FactHandleFactory; @@ -40,23 +40,20 @@ * @author Alexander Bagerman * */ -public class RuleBaseImpl - implements - RuleBase { - private static final long serialVersionUID = 1487738104393155409L; +public class RuleBaseImpl implements RuleBase { + private static final long serialVersionUID = 1487738104393155409L; - private HashMap leapsRules = new HashMap(); + private HashMap leapsRules = new HashMap(); /** * The fact handle factory. */ - private final HandleFactory factHandleFactory; + private final FactHandleFactory factHandleFactory; - private Set rulesPackages; + private Map globalDeclarations; - private Map applicationData; + private Map rulesPackages; - // @todo: replace this with a weak HashSet /** * WeakHashMap to keep references of WorkingMemories but allow them to be * garbage collected @@ -64,20 +61,17 @@ public class RuleBaseImpl private final transient Map workingMemories; /** Special value when adding to the underlying map. */ - private static final Object PRESENT = new Object(); + private static final Object PRESENT = new Object(); /** * Construct. * * @param rete * The rete network. - * @throws PackageIntegrationException + * @throws PackageIntegrationException */ public RuleBaseImpl() throws PackageIntegrationException { - this( new HandleFactory(), - new HashSet(), - new HashMap() ); - + this(new HandleFactory()); } /** @@ -91,50 +85,43 @@ public RuleBaseImpl() throws PackageIntegrationException { * The fact handle factory. * @param pkgs * @param applicationData - * @throws PackageIntegrationException - * @throws Exception + * @throws PackageIntegrationException + * @throws Exception */ - public RuleBaseImpl(FactHandleFactory factHandleFactory, - Set pkgs, - Map applicationData) throws PackageIntegrationException { - // because we can deal only with leaps fact handle factory + public RuleBaseImpl(FactHandleFactory factHandleFactory) { + // casting to make sure that it's leaps handle factory this.factHandleFactory = (HandleFactory) factHandleFactory; - this.rulesPackages = pkgs; - this.applicationData = applicationData; + this.globalDeclarations = new HashMap(); this.workingMemories = new WeakHashMap(); - this.rulesPackages = new HashSet(); - for ( Iterator it = pkgs.iterator(); it.hasNext(); ) { - this.addPackage( (Package) it.next() ); - } + this.rulesPackages = new HashMap(); } /** * @see RuleBase */ public WorkingMemory newWorkingMemory() { - return newWorkingMemory( true ); + return newWorkingMemory(true); } /** * @see RuleBase */ public WorkingMemory newWorkingMemory(boolean keepReference) { - WorkingMemoryImpl workingMemory = new WorkingMemoryImpl( this ); + WorkingMemoryImpl workingMemory = new WorkingMemoryImpl(this); // add all rules added so far - for ( Iterator it = this.leapsRules.values().iterator(); it.hasNext(); ) { - workingMemory.addLeapsRules( (List) it.next() ); + for (Iterator it = this.leapsRules.values().iterator(); it.hasNext();) { + workingMemory.addLeapsRules((List) it.next()); } // - if ( keepReference ) { - this.workingMemories.put( workingMemory, - RuleBaseImpl.PRESENT ); + if (keepReference) { + this.workingMemories.put(workingMemory, RuleBaseImpl.PRESENT); } return workingMemory; } void disposeWorkingMemory(WorkingMemory workingMemory) { - this.workingMemories.remove( workingMemory ); + this.workingMemories.remove(workingMemory); } /** @@ -157,12 +144,14 @@ public FactHandleFactory newFactHandleFactory() { /** * @see RuleBase */ + public Package[] getPackages() { - return (Package[]) this.rulesPackages.toArray( new Package[this.rulesPackages.size()] ); + return (Package[]) this.rulesPackages.values().toArray( + new Package[this.rulesPackages.size()]); } - public Map getApplicationData() { - return this.applicationData; + public Map getGlobalDeclarations() { + return this.globalDeclarations; } /** @@ -172,32 +161,74 @@ public Map getApplicationData() { * * @param rulesPackage * The rule-set to add. - * @throws PackageIntegrationException + * @throws PackageIntegrationException * * @throws FactException * @throws InvalidPatternException */ - public void addPackage(Package rulesPackage) throws PackageIntegrationException { - rulesPackage.checkValidity(); - Map newApplicationData = rulesPackage.getGlobals(); + public void addPackage(Package newPackage) + throws PackageIntegrationException { + newPackage.checkValidity(); + Package pkg = (Package) this.rulesPackages.get(newPackage.getName()); + if (pkg != null) { + mergePackage(pkg, newPackage); + } else { + this.rulesPackages.put(newPackage.getName(), newPackage); + } - // 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(); ) { + Map newGlobals = newPackage.getGlobals(); + + // Check that the global data is valid, we cannot change the type + // of an already declared global variable + for (Iterator it = newGlobals.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 PackageIntegrationException( rulesPackage ); + Class type = (Class) newGlobals.get(identifier); + if (this.globalDeclarations.containsKey(identifier) + && !this.globalDeclarations.get(identifier).equals(type)) { + throw new PackageIntegrationException(pkg); } } - this.applicationData.putAll( newApplicationData ); + this.globalDeclarations.putAll(newGlobals); + + Rule[] rules = newPackage.getRules(); + + for (int i = 0; i < rules.length; ++i) { + addRule(rules[i]); + } + } + + public void mergePackage(Package existingPackage, Package newPackage) + throws PackageIntegrationException { + Map globals = existingPackage.getGlobals(); + List imports = existingPackage.getImports(); + + // First update the binary files + // @todo: this probably has issues if you add classes in the incorrect + // order - functions, rules, invokers. + PackageCompilationData compilationData = existingPackage + .getPackageCompilationData(); + PackageCompilationData newCompilationData = newPackage + .getPackageCompilationData(); + String[] files = newCompilationData.list(); + for (int i = 0, length = files.length; i < length; i++) { + compilationData.write(files[i], newCompilationData.read(files[i])); + } - this.rulesPackages.add( rulesPackage ); + // Merge imports + imports.addAll(newPackage.getImports()); - Rule[] rules = rulesPackage.getRules(); + // Add invokers + compilationData.putAllInvokers(newCompilationData.getInvokers()); - for ( int i = 0, length = rules.length; i < length; ++i ) { - addRule( rules[i] ); + // Add globals + for (Iterator it = globals.keySet().iterator(); it.hasNext();) { + String identifier = (String) it.next(); + Class type = (Class) globals.get(identifier); + if (globals.containsKey(identifier) + && !globals.get(identifier).equals(type)) { + throw new PackageIntegrationException( + "Unable to merge new Package", newPackage); + } } } @@ -209,23 +240,35 @@ public void addPackage(Package rulesPackage) throws PackageIntegrationException * @throws InvalidPatternException */ public void addRule(Rule rule) throws FactException, - InvalidPatternException { - if ( !rule.isValid() ) { - throw new IllegalArgumentException( "The rule called " + rule.getName() + " is not valid. Check for compile errors reported." ); + InvalidPatternException { + if (!rule.isValid()) { + throw new IllegalArgumentException("The rule called " + + rule.getName() + + " is not valid. Check for compile errors reported."); } - List rules = Builder.processRule( rule ); + List rules = Builder.processRule(rule); - this.leapsRules.put( rule, - rules ); + this.leapsRules.put(rule, rules); + + for (Iterator it = this.workingMemories.keySet().iterator(); it + .hasNext();) { + ((WorkingMemoryImpl) it.next()).addLeapsRules(rules); + } - for ( Iterator it = this.workingMemories.keySet().iterator(); it.hasNext(); ) { - ((WorkingMemoryImpl) it.next()).addLeapsRules( rules ); + // Iterate each workingMemory and attempt to fire any rules, that were + // activated as a result of the new rule addition + for (Iterator it = this.workingMemories.keySet().iterator(); it + .hasNext();) { + WorkingMemoryImpl workingMemory = (WorkingMemoryImpl) it.next(); + workingMemory.fireAllRules(); } } public void removeRule(Rule rule) { - for ( Iterator it = this.workingMemories.keySet().iterator(); it.hasNext(); ) { - ((WorkingMemoryImpl) it.next()).removeRule( (List) this.leapsRules.remove( rule ) ); + for (Iterator it = this.workingMemories.keySet().iterator(); it + .hasNext();) { + ((WorkingMemoryImpl) it.next()).removeRule((List) this.leapsRules + .remove(rule)); } } diff --git a/drools-core/src/main/java/org/drools/leaps/Token.java b/drools-core/src/main/java/org/drools/leaps/Token.java index 8463bc452ef..8ec2ad3e140 100644 --- a/drools-core/src/main/java/org/drools/leaps/Token.java +++ b/drools-core/src/main/java/org/drools/leaps/Token.java @@ -34,40 +34,43 @@ * @author Alexander Bagerman * */ -class Token - implements - Tuple, - Serializable { +class Token implements Tuple, Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private WorkingMemoryImpl workingMemory; + private WorkingMemoryImpl workingMemory; private final FactHandleImpl dominantFactHandle; - private RuleHandle currentRuleHandle = null; + private RuleHandle currentRuleHandle = null; - private FactHandleImpl[] currentFactHandles = new FactHandleImpl[0]; + private FactHandleImpl[] currentFactHandles = new FactHandleImpl[0]; - boolean resume = false; + boolean resume = false; - private Iterator rules = null; + private Iterator rules = null; + + private final PropagationContextImpl propagationContext; /** - * agendaItem parts + * */ - public Token(WorkingMemoryImpl workingMemory, - FactHandleImpl factHandle) { + public Token(WorkingMemoryImpl workingMemory, FactHandleImpl factHandle, + PropagationContextImpl propagationContext) { this.workingMemory = workingMemory; this.dominantFactHandle = factHandle; + this.propagationContext = propagationContext; } private Iterator rulesIterator() { - if ( this.rules == null ) { - if ( this.dominantFactHandle != null ) { - this.rules = this.workingMemory.getFactTable( this.dominantFactHandle.getObject().getClass() ).getRulesIterator(); + if (this.rules == null) { + if (this.dominantFactHandle != null) { + this.rules = this.workingMemory.getFactTable( + this.dominantFactHandle.getObject().getClass()) + .getRulesIterator(); } else { - this.rules = this.workingMemory.getNoRequiredColumnsLeapsRules(); + this.rules = this.workingMemory + .getNoRequiredColumnsLeapsRules(); } } return this.rules; @@ -75,7 +78,8 @@ private Iterator rulesIterator() { public RuleHandle nextRuleHandle() { this.currentRuleHandle = (RuleHandle) this.rules.next(); - this.currentFactHandles = new FactHandleImpl[this.currentRuleHandle.getLeapsRule().getNumberOfColumns()]; + this.currentFactHandles = new FactHandleImpl[this.currentRuleHandle + .getLeapsRule().getNumberOfColumns()]; return this.currentRuleHandle; } @@ -87,19 +91,21 @@ public RuleHandle nextRuleHandle() { public boolean hasNextRuleHandle() { boolean ret = false; - if ( this.rulesIterator() != null ) { + if (this.rulesIterator() != null) { // starting with calling rulesIterator() to make sure that we picks // rules because fact can be asserted before rules added long levelId = this.workingMemory.getIdLastFireAllAt(); - if ( this.dominantFactHandle == null || this.dominantFactHandle.getId() >= levelId ) { + if (this.dominantFactHandle == null + || this.dominantFactHandle.getId() >= levelId) { ret = this.rules.hasNext(); } else { // then we need to skip rules that have id lower than // workingMemory.idLastFireAllAt boolean done = false; - while ( !done ) { - if ( this.rules.hasNext() ) { - if ( ((RuleHandle) ((TableIterator) this.rules).peekNext()).getId() > levelId ) { + while (!done) { + if (this.rules.hasNext()) { + if (((RuleHandle) ((TableIterator) this.rules) + .peekNext()).getId() > levelId) { ret = true; done = true; } else { @@ -116,15 +122,14 @@ public boolean hasNextRuleHandle() { } public int hashCode() { - if ( this.dominantFactHandle != null ) { + if (this.dominantFactHandle != null) { return this.dominantFactHandle.hashCode(); } else { return 0; } } - public void set(int idx, - FactHandleImpl factHandle) { + public void set(int idx, FactHandleImpl factHandle) { this.currentFactHandles[idx] = factHandle; } @@ -150,11 +155,14 @@ public void setResume(boolean resume) { * @see Object */ public boolean equals(Object that) { - if ( this == that ) return true; - if ( !(that instanceof Token) ) return false; - if ( this.dominantFactHandle != null ) { - if ( ((Token) that).dominantFactHandle != null ) { - return this.dominantFactHandle.getId() == ((Token) that).dominantFactHandle.getId(); + if (this == that) + return true; + if (!(that instanceof Token)) + return false; + if (this.dominantFactHandle != null) { + if (((Token) that).dominantFactHandle != null) { + return this.dominantFactHandle.getId() == ((Token) that).dominantFactHandle + .getId(); } else { return false; } @@ -178,7 +186,7 @@ public FactHandle get(int idx) { * @see org.drools.spi.Tuple */ public FactHandle get(Declaration declaration) { - return this.get( declaration.getColumn() ); + return this.get(declaration.getColumn()); } /** @@ -202,10 +210,14 @@ public WorkingMemory getWorkingMemory() { * @see java.lang.Object */ public String toString() { - String ret = "TOKEN [" + this.dominantFactHandle + "]\n" + "\tRULE : " + this.currentRuleHandle + "\n"; - if ( this.currentFactHandles != null ) { - for ( int i = 0, length = this.currentFactHandles.length; i < length; i++ ) { - ret = ret + ((i == this.currentRuleHandle.getDominantPosition()) ? "***" : "") + "\t" + i + " -> " + this.currentFactHandles[i].getObject() + "\n"; + String ret = "TOKEN [" + this.dominantFactHandle + "]\n" + "\tRULE : " + + this.currentRuleHandle + "\n"; + if (this.currentFactHandles != null) { + for (int i = 0, length = this.currentFactHandles.length; i < length; i++) { + ret = ret + + ((i == this.currentRuleHandle.getDominantPosition()) ? "***" + : "") + "\t" + i + " -> " + + this.currentFactHandles[i].getObject() + "\n"; } } return ret; @@ -216,10 +228,9 @@ public String toString() { * * @return LeapsTuple */ - LeapsTuple getTuple(PropagationContextImpl context) { - return new LeapsTuple( this.currentFactHandles, - this.currentRuleHandle.getLeapsRule(), - context ); + LeapsTuple getTuple() { + return new LeapsTuple(this.currentFactHandles, this.currentRuleHandle + .getLeapsRule(), this.propagationContext); } /** @@ -232,8 +243,8 @@ LeapsTuple getTuple(PropagationContextImpl context) { * object, otherwise <code>false</code>. */ public boolean dependsOn(FactHandle handle) { - for ( int i = 0, length = this.currentFactHandles.length; i < length; i++ ) { - if ( this.currentFactHandles[i].equals( handle ) ) { + for (int i = 0, length = this.currentFactHandles.length; i < length; i++) { + if (this.currentFactHandles[i].equals(handle)) { return true; } } @@ -250,4 +261,8 @@ public boolean dependsOn(FactHandle handle) { public void setActivation(Activation activation) { // do nothing } + + public PropagationContextImpl getPropagationContext() { + return propagationContext; + } } diff --git a/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java b/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java index acc7bcd1c2e..8b21b712ee7 100644 --- a/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java +++ b/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java @@ -16,13 +16,10 @@ * limitations under the License. */ -import org.drools.common.PropagationContextImpl; import org.drools.leaps.util.Table; import org.drools.leaps.util.TableIterator; import org.drools.rule.EvalCondition; import org.drools.rule.InvalidRuleException; -import org.drools.spi.Activation; -import org.drools.spi.PropagationContext; /** * helper class that does condition evaluation on token when working memory does @@ -41,32 +38,51 @@ final class TokenEvaluator { * @throws Exception * @throws InvalidRuleException */ - final static protected void evaluate(Token token) throws NoMatchesFoundException, - Exception, - InvalidRuleException { - WorkingMemoryImpl workingMemory = (WorkingMemoryImpl) token.getWorkingMemory(); + final static protected void evaluate(Token token) + throws NoMatchesFoundException, InvalidRuleException { + WorkingMemoryImpl workingMemory = (WorkingMemoryImpl) token + .getWorkingMemory(); LeapsRule leapsRule = token.getCurrentRuleHandle().getLeapsRule(); // sometimes there is no normal conditions, only not and exists int numberOfColumns = leapsRule.getNumberOfColumns(); - if ( numberOfColumns > 0 ) { - int dominantFactPosition = token.getCurrentRuleHandle().getDominantPosition(); - if ( leapsRule.getColumnConstraintsAtPosition( dominantFactPosition ).isAllowedAlpha( token.getDominantFactHandle(), - token, - workingMemory ) ) { + if (numberOfColumns > 0) { + int dominantFactPosition = token.getCurrentRuleHandle() + .getDominantPosition(); + if (leapsRule.getColumnConstraintsAtPosition(dominantFactPosition) + .isAllowedAlpha(token.getDominantFactHandle(), token, + workingMemory)) { TableIterator[] iterators = new TableIterator[numberOfColumns]; // getting iterators first - for ( int i = 0; i < numberOfColumns; i++ ) { - if ( i == dominantFactPosition ) { - iterators[i] = Table.singleItemIterator( token.getDominantFactHandle() ); + for (int i = 0; i < numberOfColumns; i++) { + if (i == dominantFactPosition) { + iterators[i] = Table.singleItemIterator(token + .getDominantFactHandle()); } else { - if ( i > 0 && leapsRule.getColumnConstraintsAtPosition( i ).isAlphaPresent() ) { - iterators[i] = workingMemory.getFactTable( leapsRule.getColumnClassObjectTypeAtPosition( i ) ).tailConstrainedIterator( workingMemory, - leapsRule.getColumnConstraintsAtPosition( i ), - token.getDominantFactHandle(), - (token.isResume() ? token.get( i ) : token.getDominantFactHandle()) ); + if (i > 0 + && leapsRule.getColumnConstraintsAtPosition(i) + .isAlphaPresent()) { + iterators[i] = workingMemory + .getFactTable( + leapsRule + .getColumnClassObjectTypeAtPosition(i)) + .tailConstrainedIterator( + workingMemory, + leapsRule + .getColumnConstraintsAtPosition(i), + token.getDominantFactHandle(), + (token.isResume() ? token.get(i) + : token + .getDominantFactHandle())); } else { - iterators[i] = workingMemory.getFactTable( leapsRule.getColumnClassObjectTypeAtPosition( i ) ).tailIterator( token.getDominantFactHandle(), - (token.isResume() ? token.get( i ) : token.getDominantFactHandle()) ); + iterators[i] = workingMemory + .getFactTable( + leapsRule + .getColumnClassObjectTypeAtPosition(i)) + .tailIterator( + token.getDominantFactHandle(), + (token.isResume() ? token.get(i) + : token + .getDominantFactHandle())); } } } @@ -78,13 +94,16 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException boolean doReset = false; boolean skip = token.isResume(); TableIterator currentIterator; - for ( int i = 0; i < numberOfColumns && !someIteratorsEmpty; i++ ) { + for (int i = 0; i < numberOfColumns && !someIteratorsEmpty; i++) { currentIterator = iterators[i]; - if ( currentIterator.isEmpty() ) { + if (currentIterator.isEmpty()) { someIteratorsEmpty = true; } else { - if ( !doReset ) { - if ( skip && currentIterator.hasNext() && !currentIterator.peekNext().equals( token.get( i ) ) ) { + if (!doReset) { + if (skip + && currentIterator.hasNext() + && !currentIterator.peekNext().equals( + token.get(i))) { skip = false; doReset = true; } @@ -95,7 +114,7 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException } // check if one of them is empty and immediate return - if ( someIteratorsEmpty ) { + if (someIteratorsEmpty) { throw new NoMatchesFoundException(); // "some of tables do not have facts"); } @@ -103,49 +122,48 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException // column position in the nested loop int jj = 0; boolean done = false; - while ( !done ) { + while (!done) { currentIterator = iterators[jj]; - if ( !currentIterator.hasNext() ) { - if ( jj == 0 ) { + if (!currentIterator.hasNext()) { + if (jj == 0) { done = true; } else { // currentIterator.reset(); - token.set( jj, - (FactHandleImpl) null ); + token.set(jj, (FactHandleImpl) null); jj = jj - 1; - if ( skip ) { + if (skip) { skip = false; } } } else { currentIterator.next(); - token.set( jj, - (FactHandleImpl) iterators[jj].current() ); + token.set(jj, (FactHandleImpl) iterators[jj].current()); // check if match found // we need to check only beta for dominant fact // alpha was already checked boolean localMatch = false; - if ( jj == 0 && jj != dominantFactPosition ) { - localMatch = leapsRule.getColumnConstraintsAtPosition( jj ).isAllowed( token.get( jj ), - token, - workingMemory ); + if (jj == 0 && jj != dominantFactPosition) { + localMatch = leapsRule + .getColumnConstraintsAtPosition(jj) + .isAllowed(token.get(jj), token, + workingMemory); } else { - localMatch = leapsRule.getColumnConstraintsAtPosition( jj ).isAllowedBeta( token.get( jj ), - token, - workingMemory ); + localMatch = leapsRule + .getColumnConstraintsAtPosition(jj) + .isAllowedBeta(token.get(jj), token, + workingMemory); } - if ( localMatch ) { + if (localMatch) { // start iteratating next iterator // or for the last one check negative conditions and // fire // consequence - if ( jj == (numberOfColumns - 1) ) { - if ( !skip ) { - if ( processAfterAllPositiveConstraintOk( token, - leapsRule, - workingMemory ) ) { + if (jj == (numberOfColumns - 1)) { + if (!skip) { + if (processAfterAllPositiveConstraintOk( + token, leapsRule, workingMemory)) { return; } } else { @@ -155,7 +173,7 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException jj = jj + 1; } } else { - if ( skip ) { + if (skip) { skip = false; } } @@ -163,9 +181,8 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException } } } else { - if ( processAfterAllPositiveConstraintOk( token, - leapsRule, - workingMemory ) ) { + if (processAfterAllPositiveConstraintOk(token, leapsRule, + workingMemory)) { return; } } @@ -174,8 +191,8 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException } /** - * Makes final check on eval, exists and not conditions after all column values - * isAllowed by column constraints + * Makes final check on eval, exists and not conditions after all column + * values isAllowed by column constraints * * @param token * @param leapsRule @@ -184,39 +201,32 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException * @throws Exception */ final static boolean processAfterAllPositiveConstraintOk(Token token, - LeapsRule leapsRule, - WorkingMemoryImpl workingMemory) throws Exception { - LeapsTuple tuple = token.getTuple( new PropagationContextImpl( workingMemory.increamentPropagationIdCounter(), - PropagationContext.ASSERTION, - leapsRule.getRule(), - (Activation) null ) ); - if ( leapsRule.containsEvalConditions() ) { - if ( !TokenEvaluator.evaluateEvalConditions( leapsRule, - tuple, - workingMemory ) ) { + LeapsRule leapsRule, WorkingMemoryImpl workingMemory) { + LeapsTuple tuple = token.getTuple(); + if (leapsRule.containsEvalConditions()) { + if (!TokenEvaluator.evaluateEvalConditions(leapsRule, tuple, + workingMemory)) { return false; } } - if ( leapsRule.containsExistsColumns() ) { - TokenEvaluator.evaluateExistsConditions( tuple, - leapsRule, - workingMemory ); + if (leapsRule.containsExistsColumns()) { + TokenEvaluator.evaluateExistsConditions(tuple, leapsRule, + workingMemory); } - if ( leapsRule.containsNotColumns() ) { - TokenEvaluator.evaluateNotConditions( tuple, - leapsRule, - workingMemory ); + if (leapsRule.containsNotColumns()) { + TokenEvaluator.evaluateNotConditions(tuple, leapsRule, + workingMemory); } // Class[] classes = leapsRule.getExistsNotColumnsClasses(); - for ( int i = 0, length = classes.length; i < length; i++ ) { - workingMemory.getFactTable( classes[i] ).addTuple( tuple ); + for (int i = 0, length = classes.length; i < length; i++) { + workingMemory.getFactTable(classes[i]).addTuple(tuple); } // - if ( tuple.isReadyForActivation() ) { + if (tuple.isReadyForActivation()) { // let agenda to do its work - workingMemory.assertTuple( tuple ); + workingMemory.assertTuple(tuple); return true; } else { return false; @@ -233,12 +243,10 @@ final static boolean processAfterAllPositiveConstraintOk(Token token, * @throws Exception */ final static boolean evaluateEvalConditions(LeapsRule leapsRule, - LeapsTuple tuple, - WorkingMemoryImpl workingMemory) throws Exception { + LeapsTuple tuple, WorkingMemoryImpl workingMemory) { EvalCondition[] evals = leapsRule.getEvalConditions(); - for ( int i = 0; i < evals.length; i++ ) { - if ( !evals[i].isAllowed( tuple, - workingMemory ) ) { + for (int i = 0; i < evals.length; i++) { + if (!evals[i].isAllowed(tuple, workingMemory)) { return false; } } @@ -254,28 +262,24 @@ final static boolean evaluateEvalConditions(LeapsRule leapsRule, * @return success * @throws Exception */ - final static void evaluateNotConditions(LeapsTuple tuple, - LeapsRule rule, - WorkingMemoryImpl workingMemory) throws Exception { + final static void evaluateNotConditions(LeapsTuple tuple, LeapsRule rule, + WorkingMemoryImpl workingMemory) { FactHandleImpl factHandle; TableIterator tableIterator; ColumnConstraints constraint; ColumnConstraints[] not = rule.getNotColumnConstraints(); - for ( int i = 0, length = not.length; i < length; i++ ) { + for (int i = 0, length = not.length; i < length; i++) { constraint = not[i]; // scan the whole table - tableIterator = workingMemory.getFactTable( constraint.getClassType() ).iterator(); + tableIterator = workingMemory.getFactTable( + constraint.getClassType()).iterator(); // fails if exists - while ( tableIterator.hasNext() ) { + while (tableIterator.hasNext()) { factHandle = (FactHandleImpl) tableIterator.next(); // check constraint condition - if ( constraint.isAllowed( factHandle, - tuple, - workingMemory ) ) { - tuple.addNotFactHandle( factHandle, - i ); - factHandle.addNotTuple( tuple, - i ); + if (constraint.isAllowed(factHandle, tuple, workingMemory)) { + tuple.addNotFactHandle(factHandle, i); + factHandle.addNotTuple(tuple, i); } } } @@ -289,27 +293,23 @@ final static void evaluateNotConditions(LeapsTuple tuple, * @throws Exception */ final static void evaluateExistsConditions(LeapsTuple tuple, - LeapsRule rule, - WorkingMemoryImpl workingMemory) throws Exception { + LeapsRule rule, WorkingMemoryImpl workingMemory) { FactHandleImpl factHandle; TableIterator tableIterator; ColumnConstraints constraint; ColumnConstraints[] exists = rule.getExistsColumnConstraints(); - for ( int i = 0, length = exists.length; i < length; i++ ) { + for (int i = 0, length = exists.length; i < length; i++) { constraint = exists[i]; // scan the whole table - tableIterator = workingMemory.getFactTable( constraint.getClassType() ).iterator(); + tableIterator = workingMemory.getFactTable( + constraint.getClassType()).iterator(); // fails if exists - while ( tableIterator.hasNext() ) { + while (tableIterator.hasNext()) { factHandle = (FactHandleImpl) tableIterator.next(); // check constraint conditions - if ( constraint.isAllowed( factHandle, - tuple, - workingMemory ) ) { - tuple.addExistsFactHandle( factHandle, - i ); - factHandle.addExistsTuple( tuple, - i ); + if (constraint.isAllowed(factHandle, tuple, workingMemory)) { + tuple.addExistsFactHandle(factHandle, i); + factHandle.addExistsTuple(tuple, i); } } } diff --git a/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java b/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java index 45916837a0e..b6beacc973d 100644 --- a/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java +++ b/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java @@ -62,20 +62,19 @@ * @see java.io.Serializable * */ -class WorkingMemoryImpl extends AbstractWorkingMemory - implements - EventSupport, - PropertyChangeListener { - private static final long serialVersionUID = -2524904474925421759L; +class WorkingMemoryImpl extends AbstractWorkingMemory implements EventSupport, + PropertyChangeListener { + private static final long serialVersionUID = -2524904474925421759L; - protected final Agenda agenda; + protected final Agenda agenda; - private final Map queryResults; + private final Map queryResults; // rules consisting only of not and exists - private final RuleTable noRequiredColumnsLeapsRules = new RuleTable( DefaultConflictResolver.getInstance().getRuleConflictResolver() ); + private final RuleTable noRequiredColumnsLeapsRules = new RuleTable( + DefaultConflictResolver.getInstance().getRuleConflictResolver()); - private final IdentityMap leapsRulesToHandlesMap = new IdentityMap(); + private final IdentityMap leapsRulesToHandlesMap = new IdentityMap(); /** * Construct. @@ -84,13 +83,17 @@ class WorkingMemoryImpl extends AbstractWorkingMemory * The backing rule-base. */ public WorkingMemoryImpl(RuleBaseImpl ruleBase) { - super( ruleBase, - ruleBase.newFactHandleFactory() ); - this.agenda = new LeapsAgenda( this ); + super(ruleBase, ruleBase.newFactHandleFactory()); + this.agenda = new LeapsAgenda(this); + this.agenda.setFocus(AgendaGroup.MAIN); + // this.queryResults = new HashMap(); // to pick up rules that do not require columns, only not and exists - this.pushTokenOnStack( new Token( this, - null ) ); + PropagationContextImpl context = new PropagationContextImpl( + nextPropagationIdCounter(), PropagationContext.ASSERTION, null, + null); + + this.pushTokenOnStack(new Token(this, null, context)); } /** @@ -99,25 +102,26 @@ public WorkingMemoryImpl(RuleBaseImpl ruleBase) { * @return The new fact handle. */ FactHandle newFactHandle(Object object) { - return ((HandleFactory) this.handleFactory).newFactHandle( object ); + return ((HandleFactory) this.handleFactory).newFactHandle(object); } /** * @see WorkingMemory */ - public void setGlobal(String name, - Object value) { + public void setGlobal(String name, Object value) { // Make sure the application data has been declared in the RuleBase - Map applicationDataDefintions = ((RuleBaseImpl) this.ruleBase).getApplicationData(); - Class type = (Class) applicationDataDefintions.get( name ); - if ( (type == null) ) { - throw new RuntimeException( "Unexpected application data [" + name + "]" ); - } else if ( !type.isInstance( value ) ) { - throw new RuntimeException( "Illegal class for application data. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." ); + Map applicationDataDefintions = ((RuleBaseImpl) this.ruleBase) + .getGlobalDeclarations(); + Class type = (Class) applicationDataDefintions.get(name); + if ((type == null)) { + throw new RuntimeException("Unexpected global [" + name + "]"); + } else if (!type.isInstance(value)) { + throw new RuntimeException("Illegal class for global. " + + "Expected [" + type.getName() + "], " + "found [" + + value.getClass().getName() + "]."); } else { - this.applicationData.put( name, - value ); + this.getGlobals().put(name, value); } } @@ -143,8 +147,9 @@ public Object getObject(FactHandle handle) { public List getObjects(Class objectClass) { List list = new LinkedList(); - for ( Iterator it = this.getFactTable( objectClass ).iterator(); it.hasNext(); ) { - list.add( it.next() ); + for (Iterator it = this.getFactTable(objectClass).iterator(); it + .hasNext();) { + list.add(it.next()); } return list; @@ -162,40 +167,26 @@ public boolean containsObject(FactHandle handle) { * @see WorkingMemory */ public FactHandle assertObject(Object object) throws FactException { - return assertObject( object, /* Not-Dynamic */ - false, - false, - null, - null ); + return assertObject(object, /* Not-Dynamic */ + false, false, null, null); } /** * @see WorkingMemory */ public FactHandle assertLogicalObject(Object object) throws FactException { - return assertObject( object, /* Not-Dynamic */ - false, - true, - null, - null ); + return assertObject(object, /* Not-Dynamic */ + false, true, null, null); } - public FactHandle assertObject(Object object, - boolean dynamic) throws FactException { - return assertObject( object, - dynamic, - false, - null, - null ); + public FactHandle assertObject(Object object, boolean dynamic) + throws FactException { + return assertObject(object, dynamic, false, null, null); } - public FactHandle assertLogicalObject(Object object, - boolean dynamic) throws FactException { - return assertObject( object, - dynamic, - true, - null, - null ); + public FactHandle assertLogicalObject(Object object, boolean dynamic) + throws FactException { + return assertObject(object, dynamic, true, null, null); } /** @@ -210,69 +201,64 @@ public FactHandle assertLogicalObject(Object object, * * @see WorkingMemory */ - public FactHandle assertObject(Object object, - boolean dynamic, - boolean logical, - Rule rule, - Activation activation) throws FactException { + public FactHandle assertObject(Object object, boolean dynamic, + boolean logical, Rule rule, Activation activation) + throws FactException { // check if the object already exists in the WM - FactHandleImpl handle = (FactHandleImpl) this.identityMap.get( object ); + FactHandleImpl handle = (FactHandleImpl) this.identityMap.get(object); // return if the handle exists and this is a logical assertion - if ( (handle != null) && (logical) ) { + if ((handle != null) && (logical)) { return handle; } // lets see if the object is already logical asserted - Object logicalState = this.equalsMap.get( object ); + Object logicalState = this.equalsMap.get(object); // if we have a handle and this STATED fact was previously STATED - if ( (handle != null) && (!logical) && logicalState == AbstractWorkingMemory.STATED ) { + if ((handle != null) && (!logical) + && logicalState == AbstractWorkingMemory.STATED) { return handle; } - if ( !logical ) { + if (!logical) { // If this stated assertion already has justifications then we need // to cancel them - if ( logicalState instanceof FactHandleImpl ) { + if (logicalState instanceof FactHandleImpl) { handle = (FactHandleImpl) logicalState; handle.removeAllLogicalDependencies(); } else { - handle = (FactHandleImpl) newFactHandle( object ); + handle = (FactHandleImpl) newFactHandle(object); } - putObject( handle, - object ); + putObject(handle, object); - this.equalsMap.put( object, - AbstractWorkingMemory.STATED ); + this.equalsMap.put(object, AbstractWorkingMemory.STATED); - if ( dynamic ) { - addPropertyChangeListener( object ); + if (dynamic) { + addPropertyChangeListener(object); } } else { // This object is already STATED, we cannot make it justifieable - if ( logicalState == AbstractWorkingMemory.STATED ) { + if (logicalState == AbstractWorkingMemory.STATED) { return null; } handle = (FactHandleImpl) logicalState; // we create a lookup handle for the first asserted equals object // all future equals objects will use that handle - if ( handle == null ) { - handle = (FactHandleImpl) newFactHandle( object ); + if (handle == null) { + handle = (FactHandleImpl) newFactHandle(object); - putObject( handle, - object ); + putObject(handle, object); - this.equalsMap.put( object, - handle ); + this.equalsMap.put(object, handle); } // adding logical dependency LeapsTuple tuple = (LeapsTuple) activation.getTuple(); - tuple.addLogicalDependency( handle ); - handle.addLogicalDependency( tuple ); + tuple.addLogicalDependency(handle); + handle.addLogicalDependency(tuple); } // leaps handle already has object attached @@ -288,66 +274,64 @@ public FactHandle assertObject(Object object, LeapsTuple tuple; LeapsRule leapsRule; Class objectClass = object.getClass(); - for ( Iterator tables = this.getFactTablesList( objectClass ).iterator(); tables.hasNext(); ) { + for (Iterator tables = this.getFactTablesList(objectClass).iterator(); tables + .hasNext();) { FactTable factTable = (FactTable) tables.next(); // adding fact to container - factTable.add( handle ); - // inspect all tuples for exists and not conditions and activate / deactivate + factTable.add(handle); + // inspect all tuples for exists and not conditions and activate / + // deactivate // agenda items ColumnConstraints constraint; ColumnConstraints[] constraints; - for ( Iterator tuples = factTable.getTuplesIterator(); tuples.hasNext(); ) { + for (Iterator tuples = factTable.getTuplesIterator(); tuples + .hasNext();) { tuple = (LeapsTuple) tuples.next(); leapsRule = tuple.getLeapsRule(); // check not constraints constraints = leapsRule.getNotColumnConstraints(); - for ( int i = 0, length = constraints.length; i < length; i++ ) { + for (int i = 0, length = constraints.length; i < length; i++) { constraint = constraints[i]; - if ( objectClass.isAssignableFrom( constraint.getClassType() ) && constraint.isAllowed( handle, - tuple, - this ) ) { - tuple.addNotFactHandle( handle, - i ); - handle.addNotTuple( tuple, - i ); + if (objectClass.isAssignableFrom(constraint.getClassType()) + && constraint.isAllowed(handle, tuple, this)) { + tuple.addNotFactHandle(handle, i); + handle.addNotTuple(tuple, i); } } // check exists constraints constraints = leapsRule.getExistsColumnConstraints(); - for ( int i = 0, length = constraints.length; i < length; i++ ) { + for (int i = 0, length = constraints.length; i < length; i++) { constraint = constraints[i]; - if ( objectClass.isAssignableFrom( constraint.getClassType() ) && constraint.isAllowed( handle, - tuple, - this ) ) { - tuple.addExistsFactHandle( handle, - i ); - handle.addExistsTuple( tuple, - i ); + if (objectClass.isAssignableFrom(constraint.getClassType()) + && constraint.isAllowed(handle, tuple, this)) { + tuple.addExistsFactHandle(handle, i); + handle.addExistsTuple(tuple, i); } } // check and see if we need deactivate / activate - if ( tuple.isReadyForActivation() && tuple.isActivationNull() ) { + if (tuple.isReadyForActivation() && tuple.isActivationNull()) { // ready to activate - this.assertTuple( tuple ); + this.assertTuple(tuple); // remove tuple from fact table tuples.remove(); - } else if ( !tuple.isReadyForActivation() && !tuple.isActivationNull() ) { + } else if (!tuple.isReadyForActivation() + && !tuple.isActivationNull()) { // time to pull from agenda - this.invalidateActivation( tuple ); + this.invalidateActivation(tuple); } } } // new leaps stack token - this.pushTokenOnStack( new Token( this, - handle ) ); - - this.workingMemoryEventSupport.fireObjectAsserted( new PropagationContextImpl( ++this.propagationIdCounter, - PropagationContext.ASSERTION, - rule, - activation ), - handle, - object ); + PropagationContextImpl context = new PropagationContextImpl( + nextPropagationIdCounter(), PropagationContext.ASSERTION, rule, + activation); + + this.pushTokenOnStack(new Token(this, handle, context)); + + this.workingMemoryEventSupport.fireObjectAsserted(context, handle, + object); + return handle; } @@ -359,66 +343,63 @@ public FactHandle assertObject(Object object, * @param object * The object. */ - Object putObject(FactHandle handle, - Object object) { + Object putObject(FactHandle handle, Object object) { - this.identityMap.put( object, - handle ); + this.identityMap.put(object, handle); - return this.objects.put( ((FactHandleImpl) handle).getId(), - object ); + return this.objects.put(((FactHandleImpl) handle).getId(), object); } Object removeObject(FactHandle handle) { - this.identityMap.remove( ((FactHandleImpl) handle).getObject() ); + this.identityMap.remove(((FactHandleImpl) handle).getObject()); - return this.objects.remove( ((FactHandleImpl) handle).getId() ); + return this.objects.remove(((FactHandleImpl) handle).getId()); } /** * @see WorkingMemory */ - public void retractObject(FactHandle handle, - boolean removeLogical, - boolean updateEqualsMap, - Rule rule, - Activation activation) throws FactException { + public void retractObject(FactHandle handle, boolean removeLogical, + boolean updateEqualsMap, Rule rule, Activation activation) + throws FactException { // - removePropertyChangeListener( handle ); + removePropertyChangeListener(handle); /* * leaps specific actions */ // remove fact from all relevant fact tables container - for ( Iterator it = this.getFactTablesList( ((FactHandleImpl) handle).getObject().getClass() ).iterator(); it.hasNext(); ) { - ((FactTable) it.next()).remove( handle ); + for (Iterator it = this.getFactTablesList( + ((FactHandleImpl) handle).getObject().getClass()).iterator(); it + .hasNext();) { + ((FactTable) it.next()).remove(handle); } // 0. remove activated tuples Iterator tuples = ((FactHandleImpl) handle).getActivatedTuples(); - for ( ; tuples != null && tuples.hasNext(); ) { - this.invalidateActivation( (LeapsTuple) tuples.next() ); + for (; tuples != null && tuples.hasNext();) { + this.invalidateActivation((LeapsTuple) tuples.next()); } // 1. remove fact for nots and exists tuples FactHandleTupleAssembly assembly; Iterator it; it = ((FactHandleImpl) handle).getNotTuples(); - if ( it != null ) { - for ( ; it.hasNext(); ) { + if (it != null) { + for (; it.hasNext();) { assembly = (FactHandleTupleAssembly) it.next(); - assembly.getTuple().removeNotFactHandle( handle, - assembly.getIndex() ); + assembly.getTuple().removeNotFactHandle(handle, + assembly.getIndex()); } } it = ((FactHandleImpl) handle).getExistsTuples(); - if ( it != null ) { - for ( ; it.hasNext(); ) { + if (it != null) { + for (; it.hasNext();) { assembly = (FactHandleTupleAssembly) it.next(); - assembly.getTuple().removeExistsFactHandle( handle, - assembly.getIndex() ); + assembly.getTuple().removeExistsFactHandle(handle, + assembly.getIndex()); } } // 2. assert all tuples that are ready for activation or cancel ones @@ -426,76 +407,73 @@ public void retractObject(FactHandle handle, LeapsTuple tuple; IteratorChain chain = new IteratorChain(); it = ((FactHandleImpl) handle).getNotTuples(); - if ( it != null ) { - chain.addIterator( it ); + if (it != null) { + chain.addIterator(it); } it = ((FactHandleImpl) handle).getExistsTuples(); - if ( it != null ) { - chain.addIterator( it ); + if (it != null) { + chain.addIterator(it); } - for ( ; chain.hasNext(); ) { + for (; chain.hasNext();) { tuple = ((FactHandleTupleAssembly) chain.next()).getTuple(); - if ( tuple.isReadyForActivation() && tuple.isActivationNull() ) { + if (tuple.isReadyForActivation() && tuple.isActivationNull()) { // ready to activate - this.assertTuple( tuple ); + this.assertTuple(tuple); } else { // time to pull from agenda - this.invalidateActivation( tuple ); + this.invalidateActivation(tuple); } } // remove it from stack - this.stack.remove( new Token( this, - (FactHandleImpl) handle ) ); + this.stack.remove(new Token(this, (FactHandleImpl) handle, null)); // // end leaps specific actions // - Object oldObject = removeObject( handle ); + Object oldObject = removeObject(handle); /* check to see if this was a logical asserted object */ - if ( removeLogical ) { - this.equalsMap.remove( oldObject ); + if (removeLogical) { + this.equalsMap.remove(oldObject); } - if ( updateEqualsMap ) { - this.equalsMap.remove( oldObject ); + if (updateEqualsMap) { + this.equalsMap.remove(oldObject); } // not applicable to leaps implementation // this.factHandlePool.push( ((FactHandleImpl) handle).getId() ); - PropagationContextImpl context = new PropagationContextImpl( ++this.propagationIdCounter, - PropagationContext.RETRACTION, - rule, - activation ); - - this.workingMemoryEventSupport.fireObjectRetracted( context, - handle, - oldObject ); + PropagationContextImpl context = new PropagationContextImpl( + nextPropagationIdCounter(), PropagationContext.RETRACTION, + rule, activation); + + this.workingMemoryEventSupport.fireObjectRetracted(context, handle, + oldObject); // not applicable to leaps fact handle // ((FactHandleImpl) handle).invalidate(); } private void invalidateActivation(LeapsTuple tuple) { - if ( !tuple.isReadyForActivation() && !tuple.isActivationNull() ) { + if (!tuple.isReadyForActivation() && !tuple.isActivationNull()) { Activation activation = tuple.getActivation(); // invalidate agenda agendaItem - if ( activation.isActivated() ) { + if (activation.isActivated()) { activation.remove(); - getAgendaEventSupport().fireActivationCancelled( activation ); + getAgendaEventSupport().fireActivationCancelled(activation); } // - tuple.setActivation( null ); + tuple.setActivation(null); } // remove logical dependency FactHandleImpl factHandle; Iterator it = tuple.getLogicalDependencies(); - if ( it != null ) { - for ( ; it.hasNext(); ) { + if (it != null) { + for (; it.hasNext();) { factHandle = (FactHandleImpl) it.next(); - factHandle.removeLogicalDependency( tuple ); - if ( !factHandle.isLogicalyValid() ) { - this.retractObject( factHandle ); + factHandle.removeLogicalDependency(tuple); + if (!factHandle.isLogicalyValid()) { + this.retractObject(factHandle); } } } @@ -504,45 +482,38 @@ private void invalidateActivation(LeapsTuple tuple) { /** * @see WorkingMemory */ - public void modifyObject(FactHandle handle, - Object object, - Rule rule, - Activation activation) throws FactException { + public void modifyObject(FactHandle handle, Object object, Rule rule, + Activation activation) throws FactException { - this.retractObject( handle ); + this.retractObject(handle); - this.assertObject( object ); + this.assertObject(object, false, false, rule, activation); /* * this.ruleBase.modifyObject( handle, object, this ); */ - this.workingMemoryEventSupport.fireObjectModified( new PropagationContextImpl( ++this.propagationIdCounter, - PropagationContext.MODIFICATION, - rule, - activation ), - handle, - ((FactHandleImpl) handle).getObject(), - object ); + this.workingMemoryEventSupport.fireObjectModified( + new PropagationContextImpl(nextPropagationIdCounter(), + PropagationContext.MODIFICATION, rule, activation), + handle, ((FactHandleImpl) handle).getObject(), object); } /** - * leaps section + * ************* leaps section ********************* */ + private final Object lock = new Object(); - private final Object lock = new Object(); - - // private long idsSequence; - - private long idLastFireAllAt = -1; + private long idLastFireAllAt = -1; /** - * algorithm stack. TreeSet is used to facilitate dynamic rule add/remove + * algorithm stack. */ + private Stack stack = new Stack(); - private Stack stack = new Stack(); - - // to store facts to cursor over it - private final Hashtable factTables = new Hashtable(); + /** + * to store facts to cursor over it + */ + private final Hashtable factTables = new Hashtable(); /** * generates or just return List of internal factTables that correspond a @@ -553,9 +524,9 @@ public void modifyObject(FactHandle handle, protected List getFactTablesList(Class c) { ArrayList list = new ArrayList(); Class bufClass = c; - while ( bufClass != null ) { + while (bufClass != null) { // - list.add( this.getFactTable( bufClass ) ); + list.add(this.getFactTable(bufClass)); // and get the next class on the list bufClass = bufClass.getSuperclass(); } @@ -568,7 +539,7 @@ protected List getFactTablesList(Class c) { * @param token */ protected void pushTokenOnStack(Token token) { - this.stack.push( token ); + this.stack.push(token); } /** @@ -580,12 +551,11 @@ protected void pushTokenOnStack(Token token) { */ protected FactTable getFactTable(Class c) { FactTable table; - if ( this.factTables.containsKey( c ) ) { - table = (FactTable) this.factTables.get( c ); + if (this.factTables.containsKey(c)) { + table = (FactTable) this.factTables.get(c); } else { - table = new FactTable( DefaultConflictResolver.getInstance() ); - this.factTables.put( c, - table ); + table = new FactTable(DefaultConflictResolver.getInstance()); + this.factTables.put(c, table); } return table; @@ -597,59 +567,62 @@ protected FactTable getFactTable(Class c) { * @param rules */ protected void addLeapsRules(List rules) { - synchronized ( this.lock ) { + synchronized (this.lock) { ArrayList ruleHandlesList; LeapsRule rule; RuleHandle ruleHandle; - for ( Iterator it = rules.iterator(); it.hasNext(); ) { + for (Iterator it = rules.iterator(); it.hasNext();) { rule = (LeapsRule) it.next(); // some times rules do not have "normal" constraints and only // not and exists - if ( rule.getNumberOfColumns() > 0 ) { + if (rule.getNumberOfColumns() > 0) { ruleHandlesList = new ArrayList(); - for ( int i = 0; i < rule.getNumberOfColumns(); i++ ) { - ruleHandle = new RuleHandle( ((HandleFactory) this.handleFactory).getNextId(), - rule, - i ); + for (int i = 0; i < rule.getNumberOfColumns(); i++) { + ruleHandle = new RuleHandle( + ((HandleFactory) this.handleFactory) + .getNextId(), rule, i); // - this.getFactTable( rule.getColumnClassObjectTypeAtPosition( i ) ).addRule( this, - ruleHandle ); + this.getFactTable( + rule.getColumnClassObjectTypeAtPosition(i)) + .addRule(this, ruleHandle); // - ruleHandlesList.add( ruleHandle ); + ruleHandlesList.add(ruleHandle); } - this.leapsRulesToHandlesMap.put( rule, - ruleHandlesList ); + this.leapsRulesToHandlesMap.put(rule, ruleHandlesList); } else { - ruleHandle = new RuleHandle( ((HandleFactory) this.handleFactory).getNextId(), - rule, - -1 ); - this.noRequiredColumnsLeapsRules.add( ruleHandle ); - this.leapsRulesToHandlesMap.put( rule, - ruleHandle ); + ruleHandle = new RuleHandle( + ((HandleFactory) this.handleFactory).getNextId(), + rule, -1); + this.noRequiredColumnsLeapsRules.add(ruleHandle); + this.leapsRulesToHandlesMap.put(rule, ruleHandle); } } } } protected void removeRule(List rules) { - synchronized ( this.lock ) { + synchronized (this.lock) { ArrayList ruleHandlesList; LeapsRule rule; RuleHandle ruleHandle; - for ( Iterator it = rules.iterator(); it.hasNext(); ) { + for (Iterator it = rules.iterator(); it.hasNext();) { rule = (LeapsRule) it.next(); // some times rules do not have "normal" constraints and only // not and exists - if ( rule.getNumberOfColumns() > 0 ) { - ruleHandlesList = (ArrayList) this.leapsRulesToHandlesMap.remove( rule ); - for ( int i = 0; i < ruleHandlesList.size(); i++ ) { - ruleHandle = (RuleHandle) ruleHandlesList.get( i ); + if (rule.getNumberOfColumns() > 0) { + ruleHandlesList = (ArrayList) this.leapsRulesToHandlesMap + .remove(rule); + for (int i = 0; i < ruleHandlesList.size(); i++) { + ruleHandle = (RuleHandle) ruleHandlesList.get(i); // - this.getFactTable( rule.getColumnClassObjectTypeAtPosition( i ) ).removeRule( ruleHandle ); + this.getFactTable( + rule.getColumnClassObjectTypeAtPosition(i)) + .removeRule(ruleHandle); } } else { - ruleHandle = (RuleHandle) this.leapsRulesToHandlesMap.remove( rule ); - this.noRequiredColumnsLeapsRules.remove( ruleHandle ); + ruleHandle = (RuleHandle) this.leapsRulesToHandlesMap + .remove(rule); + this.noRequiredColumnsLeapsRules.remove(ruleHandle); } } } @@ -665,65 +638,64 @@ public void fireAllRules(AgendaFilter agendaFilter) throws FactException { // nested inside, avoiding concurrent-modification // exceptions, depending on code paths of the actions. - if ( !this.firing ) { + if (!this.firing) { try { this.firing = true; // normal rules with required columns - while ( !this.stack.isEmpty() ) { + while (!this.stack.isEmpty()) { Token token = (Token) this.stack.peek(); boolean done = false; - while ( !done ) { - if ( !token.isResume() ) { - if ( token.hasNextRuleHandle() ) { + while (!done) { + if (!token.isResume()) { + if (token.hasNextRuleHandle()) { token.nextRuleHandle(); } else { // we do not pop because something might get // asserted // and placed on hte top of the stack during // firing - this.stack.remove( token ); + this.stack.remove(token); done = true; } } - if ( !done ) { + if (!done) { try { // ok. now we have tuple, dominant fact and // rules and ready to seek to checks if any // agendaItem // matches on current rule - TokenEvaluator.evaluate( token ); + TokenEvaluator.evaluate(token); // something was found so set marks for // resume processing - if ( token.getDominantFactHandle() != null ) { - token.setResume( true ); + if (token.getDominantFactHandle() != null) { + token.setResume(true); done = true; } - } catch ( NoMatchesFoundException ex ) { - token.setResume( false ); - } catch ( Exception e ) { - e.printStackTrace(); - System.out.println( "exception - " + e ); + } catch (NoMatchesFoundException ex) { + token.setResume(false); } } // we put everything on agenda // and if there is no modules or anything like it // it would fire just activated rule - while ( this.agenda.fireNextItem( agendaFilter ) ) { + while (this.agenda.fireNextItem(agendaFilter)) { ; } } } - // pick activations generated by retraction - // retraction does not put tokens on stack but + // pick activations generated by retraction + // retraction does not put tokens on stack but // can generate activations off exists and not pending tuples - while ( this.agenda.fireNextItem( agendaFilter ) ) { + while (this.agenda.fireNextItem(agendaFilter)) { ; } // mark when method was called last time - this.idLastFireAllAt = ((HandleFactory) this.handleFactory).getNextId(); + this.idLastFireAllAt = ((HandleFactory) this.handleFactory) + .getNextId(); // set all factTables to be reseeded - for ( Enumeration e = this.factTables.elements(); e.hasMoreElements(); ) { - ((FactTable) e.nextElement()).setReseededStack( true ); + for (Enumeration e = this.factTables.elements(); e + .hasMoreElements();) { + ((FactTable) e.nextElement()).setReseededStack(true); } } finally { this.firing = false; @@ -740,13 +712,13 @@ public String toString() { Object key; ret = ret + "\n" + "Working memory"; ret = ret + "\n" + "Fact Tables by types:"; - for ( Enumeration e = this.factTables.keys(); e.hasMoreElements(); ) { + for (Enumeration e = this.factTables.keys(); e.hasMoreElements();) { key = e.nextElement(); ret = ret + "\n" + "****************** " + key; - ret = ret + ((FactTable) this.factTables.get( key )).toString(); + ret = ret + ((FactTable) this.factTables.get(key)).toString(); } ret = ret + "\n" + "Stack:"; - for ( Iterator it = this.stack.iterator(); it.hasNext(); ) { + for (Iterator it = this.stack.iterator(); it.hasNext();) { ret = ret + "\n" + "\t" + it.next(); } return ret; @@ -764,109 +736,107 @@ public String toString() { */ public void assertTuple(LeapsTuple tuple) { PropagationContext context = tuple.getContext(); - Rule rule = context.getRuleOrigin(); + Rule rule = tuple.getLeapsRule().getRule(); // if the current Rule is no-loop and the origin rule is the same then // return - if ( rule.getNoLoop() && rule.equals( context.getRuleOrigin() ) ) { + if (rule.getNoLoop() && rule.equals(context.getRuleOrigin())) { return; } Duration dur = rule.getDuration(); Activation agendaItem; - if ( dur != null && dur.getDuration( tuple ) > 0 ) { - agendaItem = new ScheduledAgendaItem( context.getPropagationNumber(), - tuple, - this.agenda, - context, - rule ); - this.agenda.scheduleItem( (ScheduledAgendaItem) agendaItem ); - tuple.setActivation( agendaItem ); - agendaItem.setActivated( true ); - this.getAgendaEventSupport().fireActivationCreated( agendaItem ); + if (dur != null && dur.getDuration(tuple) > 0) { + agendaItem = new ScheduledAgendaItem( + context.getPropagationNumber(), tuple, this.agenda, + context, rule); + this.agenda.scheduleItem((ScheduledAgendaItem) agendaItem); + tuple.setActivation(agendaItem); + agendaItem.setActivated(true); + this.getAgendaEventSupport().fireActivationCreated(agendaItem); } else { - // ----------------- - // Lazy instantiation and addition to the Agenda of AgendGroup - // implementations - // ---------------- - AgendaGroupImpl agendaGroup = null; - if ( rule.getAgendaGroup() == null || rule.getAgendaGroup().equals( "" ) || rule.getAgendaGroup().equals( AgendaGroup.MAIN ) ) { - // Is the Rule AgendaGroup undefined? If it is use MAIN, which - // is added to the Agenda by default - agendaGroup = (AgendaGroupImpl) this.agenda.getAgendaGroup( AgendaGroup.MAIN ); - } else { - // AgendaGroup is defined, so try and get the AgendaGroup from - // the Agenda - agendaGroup = (AgendaGroupImpl) this.agenda.getAgendaGroup( rule.getAgendaGroup() ); - } + LeapsRule leapsRule = tuple.getLeapsRule(); + AgendaGroupImpl agendaGroup = leapsRule.getAgendaGroup(); + if (agendaGroup == null) { + if (rule.getAgendaGroup() == null + || rule.getAgendaGroup().equals("") + || rule.getAgendaGroup().equals(AgendaGroup.MAIN)) { + // Is the Rule AgendaGroup undefined? If it is use MAIN, + // which is added to the Agenda by default + agendaGroup = (AgendaGroupImpl) this.agenda + .getAgendaGroup(AgendaGroup.MAIN); + } else { + // AgendaGroup is defined, so try and get the AgendaGroup + // from the Agenda + agendaGroup = (AgendaGroupImpl) this.agenda + .getAgendaGroup(rule.getAgendaGroup()); + } - if ( agendaGroup == null ) { - // The AgendaGroup is defined but not yet added to the Agenda, - // so create the AgendaGroup and add to the Agenda. - agendaGroup = new AgendaGroupImpl( rule.getAgendaGroup() ); - this.agenda.addAgendaGroup( agendaGroup ); + if (agendaGroup == null) { + // The AgendaGroup is defined but not yet added to the + // Agenda, so create the AgendaGroup and add to the Agenda. + agendaGroup = new AgendaGroupImpl(rule.getAgendaGroup()); + this.getAgenda().addAgendaGroup(agendaGroup); + } + + leapsRule.setAgendaGroup(agendaGroup); } // set the focus if rule autoFocus is true - if ( rule.getAutoFocus() ) { - this.agenda.setFocus( agendaGroup ); + if (rule.getAutoFocus()) { + this.agenda.setFocus(agendaGroup); + } + + // Lazy assignment of the AgendaGroup's Activation Lifo Queue + if (leapsRule.getLifo() == null) { + leapsRule.setLifo(agendaGroup.getActivationQueue(rule + .getSalience())); } - ActivationQueue queue = agendaGroup.getActivationQueue( rule.getSalience() ); - agendaItem = new AgendaItem( context.getPropagationNumber(), - tuple, - context, - rule, - queue ); + ActivationQueue queue = leapsRule.getLifo(); - queue.add( agendaItem ); + agendaItem = new AgendaItem(context.getPropagationNumber(), tuple, + context, rule, queue); + + queue.add(agendaItem); // Makes sure the Lifo is added to the AgendaGroup priority queue // If the AgendaGroup is already in the priority queue it just // returns. - agendaGroup.addToAgenda( queue ); - tuple.setActivation( agendaItem ); - agendaItem.setActivated( true ); - this.getAgendaEventSupport().fireActivationCreated( agendaItem ); + + agendaGroup.addToAgenda(leapsRule.getLifo()); + tuple.setActivation(agendaItem); + agendaItem.setActivated(true); + this.getAgendaEventSupport().fireActivationCreated(agendaItem); + // retract support - FactHandleImpl[] factHandles = (FactHandleImpl[]) tuple.getFactHandles(); - for ( int i = 0; i < factHandles.length; i++ ) { - factHandles[i].addActivatedTuple( tuple ); + FactHandleImpl[] factHandles = (FactHandleImpl[]) tuple + .getFactHandles(); + for (int i = 0; i < factHandles.length; i++) { + factHandles[i].addActivatedTuple(tuple); } } } - protected long increamentPropagationIdCounter() { + protected long nextPropagationIdCounter() { return ++this.propagationIdCounter; } public void dispose() { - ((RuleBaseImpl) this.ruleBase).disposeWorkingMemory( this ); - } - - /** - * Retrieve the rule-firing <code>Agenda</code> for this - * <code>WorkingMemory</code>. - * - * @return The <code>Agenda</code>. - */ - public Agenda getAgenda() { - return this.agenda; + ((RuleBaseImpl) this.ruleBase).disposeWorkingMemory(this); } public List getQueryResults(String query) { - return (List) this.queryResults.remove( query ); + return (List) this.queryResults.remove(query); } - void addToQueryResults(String query, - Tuple tuple) { - LinkedList list = (LinkedList) this.queryResults.get( query ); - if ( list == null ) { + void addToQueryResults(String query, Tuple tuple) { + LinkedList list = (LinkedList) this.queryResults.get(query); + if (list == null) { list = new LinkedList(); - this.queryResults.put( query, - list ); + this.queryResults.put(query, list); } - list.add( tuple ); + list.add(tuple); } protected TableIterator getNoRequiredColumnsLeapsRules() { @@ -876,12 +846,17 @@ protected TableIterator getNoRequiredColumnsLeapsRules() { public AgendaGroup getFocus() { return this.agenda.getFocus(); } - + public void setFocus(String focus) { - this.agenda.setFocus( focus ); + this.agenda.setFocus(focus); } - + public void setFocus(AgendaGroup focus) { - this.agenda.setFocus( focus ); - } + this.agenda.setFocus(focus); + } + + public Agenda getAgenda() { + return this.agenda; + } + } diff --git a/drools-core/src/main/java/org/drools/leaps/util/Table.java b/drools-core/src/main/java/org/drools/leaps/util/Table.java index 8aa1a1473b6..ac3276aae63 100644 --- a/drools-core/src/main/java/org/drools/leaps/util/Table.java +++ b/drools-core/src/main/java/org/drools/leaps/util/Table.java @@ -28,298 +28,301 @@ /** * * @author Alexander Bagerman - * + * */ public class Table implements Serializable { - private final TreeMap map; - - protected TableRecord headRecord; - - protected TableRecord tailRecord; - - private boolean empty = true; - - private int count = 0; - - public Table(Comparator comparator) { - this.map = new TreeMap(comparator); - } - - protected void clear() { - this.headRecord = new TableRecord(null); - this.empty = true; - this.count = 0; - this.map.clear(); - } - - /** - * @param object - * to add - */ - public void add(Object object) { - boolean foundEqualObject = false; - TableRecord newRecord = new TableRecord(object); - if (this.empty) { - this.headRecord = newRecord; - this.empty = false; - } else { - SortedMap bufMap = this.map.headMap(object); - if (!bufMap.isEmpty()) { - TableRecord bufRec = (TableRecord) this.map.get(bufMap.lastKey()); - if (bufRec.right != null) { - bufRec.right.left = newRecord; - } - newRecord.right = bufRec.right; - bufRec.right = newRecord; - newRecord.left = bufRec; - - } else { - this.headRecord.left = newRecord; - newRecord.right = this.headRecord; - this.headRecord = newRecord; - } - } - if (!foundEqualObject) { - // check if the new record was added at the end of the list - // and assign new value to the tail record - if (newRecord.right == null) { - this.tailRecord = newRecord; - } - // - this.count++; - // - this.map.put(object, newRecord); - } - } - - /** - * Removes object from the table - * - * @param object - * to remove from the table - */ - public void remove(Object object) { - if (!this.empty) { - TableRecord record = (TableRecord) this.map.get(object); - - if (record != null) { - if (record == this.headRecord) { - if (record.right != null) { - this.headRecord = record.right; - this.headRecord.left = null; - } else { - // single element in table being valid - // table is empty now - this.headRecord = new TableRecord(null); - this.tailRecord = this.headRecord; - this.empty = true; - } - } else if (record == this.tailRecord) { - // single element in the table case is being solved above - // when - // we checked for headRecord match - this.tailRecord = record.left; - this.tailRecord.right = null; - } else { - // left - record.left.right = record.right; - record.right.left = record.left; - } - } - this.count--; - // - this.map.remove(object); - } - } - - /** - * @param object - * @return indicator of presence of given object in the table - */ - public boolean contains(Object object) { - boolean ret = false; - if (!this.empty) { - ret = this.map.containsKey(object); - } - return ret; - } - - /** - * @return TableIterator for this Table - * @see org.drools.leaps.util.TableIterator - * @see org.drools.leaps.util.BaseTableIterator - */ - public TableIterator iterator() { - TableIterator ret; - if (this.empty) { - ret = new BaseTableIterator(null, null, null); - } else { - ret = new BaseTableIterator(this.headRecord, this.headRecord, - this.tailRecord); - } - return ret; - } - - /** - * iterator over "tail" part of the table data. - * - * @param objectAtStart - - * upper boundary of the iteration - * @param objectAtPosition - - * starting point of the iteration - * @return leaps table iterator - * @throws TableOutOfBoundException - */ - class Markers { - TableRecord start; - TableRecord current; - TableRecord last; - } - - public TableIterator tailConstrainedIterator(WorkingMemory workingMemory, - ColumnConstraints constraints, Object objectAtStart, - Object objectAtPosition) throws TableOutOfBoundException { - Markers markers = this.getTailIteratorMarkers(objectAtStart, - objectAtPosition); - return new ConstrainedFactTableIterator(workingMemory, constraints, - markers.start, markers.current, markers.last); - - } - - public TableIterator tailIterator(Object objectAtStart, - Object objectAtPosition) throws TableOutOfBoundException { - Markers markers = this.getTailIteratorMarkers(objectAtStart, objectAtPosition); - return new BaseTableIterator(markers.start, markers.current, - markers.last); - } - - - private Markers getTailIteratorMarkers(Object objectAtStart, - Object objectAtPosition) throws TableOutOfBoundException { - // validate - Markers ret = new Markers(); - ret.start = null; - ret.current = null; - ret.last = null; - // - if (this.map.comparator().compare(objectAtStart, objectAtPosition) > 0) { - throw new TableOutOfBoundException( - "object at position is out of upper bound"); - } - TableRecord startRecord = null; - TableRecord currentRecord = null; - TableRecord lastRecord = this.tailRecord; - - if (!this.empty) { // validate - // if (!this.map.isEmpty()) { // validate - if (this.map.comparator().compare(objectAtStart, - this.tailRecord.object) <= 0) { - // let's check if we need iterator over the whole table - SortedMap bufMap = this.map.tailMap(objectAtStart); - if (!bufMap.isEmpty()) { - startRecord = (TableRecord) bufMap.get(bufMap.firstKey()); - if (this.map.comparator().compare(objectAtStart, - objectAtPosition) == 0) { - currentRecord = startRecord; - } else { - // rewind to position - bufMap = bufMap.tailMap(objectAtPosition); - - if (!bufMap.isEmpty()) { - currentRecord = ((TableRecord) bufMap.get(bufMap - .firstKey())); - } else { - currentRecord = startRecord; - } - } - ret.start = startRecord; - ret.current = currentRecord; - ret.last = lastRecord; - } - } - } - - return ret; - } - - /** - * iterator over "head" part of the table data. it does not take - * "positional" parameter because it's used for scanning shadow tables and - * this scan never "resumes" - * - * @param objectAtEnd - - * lower boundary of the iteration - * @return leaps table iterator - */ - public TableIterator headIterator(Object objectAtEnd) { - TableIterator iterator = null; - TableRecord startRecord = this.headRecord; - TableRecord currentRecord = this.headRecord; - TableRecord lastRecord = null; - - if (!this.empty) { // validate - if (this.map.comparator().compare(this.headRecord.object, - objectAtEnd) <= 0) { - // let's check if we need iterator over the whole table - SortedMap bufMap = this.map.headMap(objectAtEnd); - if (!bufMap.isEmpty()) { - lastRecord = (TableRecord) bufMap.get(bufMap.lastKey()); - // check if the next one is what we need - if (lastRecord.right != null - && this.map.comparator().compare( - lastRecord.right.object, objectAtEnd) == 0) { - lastRecord = lastRecord.right; - } - iterator = new BaseTableIterator(startRecord, currentRecord, - lastRecord); - } else { - // empty iterator - iterator = new BaseTableIterator(null, null, null); - } - } else { - // empty iterator - iterator = new BaseTableIterator(null, null, null); - } - } else { - // empty iterator - iterator = new BaseTableIterator(null, null, null); - } - - return iterator; - } - - /** - * indicates if table has any elements - * - * @return empty indicator - */ - public boolean isEmpty() { - return this.empty; - } - - public String toString() { - String ret = ""; - - for (Iterator it = this.iterator(); it.hasNext();) { - ret = ret + it.next() + "\n"; - } - return ret; - } - - public int size() { - return this.count; - } - - public Object top() { - return this.headRecord.object; - } - - public Object bottom() { - return this.tailRecord.object; - } - - public static TableIterator singleItemIterator(Object object){ - return new BaseTableIterator(new TableRecord(object)); - } + private final TreeMap map; + + protected TableRecord headRecord; + + protected TableRecord tailRecord; + + private boolean empty = true; + + private int count = 0; + + public Table(Comparator comparator) { + this.map = new TreeMap(comparator); + } + + protected void clear() { + this.headRecord = new TableRecord(null); + this.empty = true; + this.count = 0; + this.map.clear(); + } + + /** + * @param object + * to add + */ + public void add(Object object) { + boolean foundEqualObject = false; + TableRecord newRecord = new TableRecord(object); + if (this.empty) { + this.headRecord = newRecord; + this.empty = false; + } else { + SortedMap bufMap = this.map.headMap(object); + if (!bufMap.isEmpty()) { + TableRecord bufRec = (TableRecord) this.map.get(bufMap + .lastKey()); + if (bufRec.right != null) { + bufRec.right.left = newRecord; + } + newRecord.right = bufRec.right; + bufRec.right = newRecord; + newRecord.left = bufRec; + + } else { + this.headRecord.left = newRecord; + newRecord.right = this.headRecord; + this.headRecord = newRecord; + } + } + if (!foundEqualObject) { + // check if the new record was added at the end of the list + // and assign new value to the tail record + if (newRecord.right == null) { + this.tailRecord = newRecord; + } + // + this.count++; + // + this.map.put(object, newRecord); + } + } + + /** + * Removes object from the table + * + * @param object + * to remove from the table + */ + public void remove(Object object) { + if (!this.empty) { + TableRecord record = (TableRecord) this.map.get(object); + + if (record != null) { + if (record == this.headRecord) { + if (record.right != null) { + this.headRecord = record.right; + this.headRecord.left = null; + } else { + // single element in table being valid + // table is empty now + this.headRecord = new TableRecord(null); + this.tailRecord = this.headRecord; + this.empty = true; + } + } else if (record == this.tailRecord) { + // single element in the table case is being solved above + // when + // we checked for headRecord match + this.tailRecord = record.left; + this.tailRecord.right = null; + } else { + // left + record.left.right = record.right; + record.right.left = record.left; + } + } + this.count--; + // + this.map.remove(object); + } + } + + /** + * @param object + * @return indicator of presence of given object in the table + */ + public boolean contains(Object object) { + boolean ret = false; + if (!this.empty) { + ret = this.map.containsKey(object); + } + return ret; + } + + /** + * @return TableIterator for this Table + * @see org.drools.leaps.util.TableIterator + * @see org.drools.leaps.util.BaseTableIterator + */ + public TableIterator iterator() { + TableIterator ret; + if (this.empty) { + ret = new BaseTableIterator(null, null, null); + } else { + ret = new BaseTableIterator(this.headRecord, this.headRecord, + this.tailRecord); + } + return ret; + } + + /** + * iterator over "tail" part of the table data. + * + * @param objectAtStart - + * upper boundary of the iteration + * @param objectAtPosition - + * starting point of the iteration + * @return leaps table iterator + * @throws TableOutOfBoundException + */ + class Markers { + TableRecord start; + + TableRecord current; + + TableRecord last; + } + + public TableIterator tailConstrainedIterator(WorkingMemory workingMemory, + ColumnConstraints constraints, Object objectAtStart, + Object objectAtPosition) { + Markers markers = this.getTailIteratorMarkers(objectAtStart, + objectAtPosition); + return new ConstrainedFactTableIterator(workingMemory, constraints, + markers.start, markers.current, markers.last); + + } + + public TableIterator tailIterator(Object objectAtStart, + Object objectAtPosition) { + Markers markers = this.getTailIteratorMarkers(objectAtStart, + objectAtPosition); + return new BaseTableIterator(markers.start, markers.current, + markers.last); + } + + private Markers getTailIteratorMarkers(Object objectAtStart, + Object objectAtPosition) { + // validate + Markers ret = new Markers(); + ret.start = null; + ret.current = null; + ret.last = null; + // + if (this.map.comparator().compare(objectAtStart, objectAtPosition) > 0) { + // return empty iterator + return ret; + } + TableRecord startRecord = null; + TableRecord currentRecord = null; + TableRecord lastRecord = this.tailRecord; + + if (!this.empty) { // validate + // if (!this.map.isEmpty()) { // validate + if (this.map.comparator().compare(objectAtStart, + this.tailRecord.object) <= 0) { + // let's check if we need iterator over the whole table + SortedMap bufMap = this.map.tailMap(objectAtStart); + if (!bufMap.isEmpty()) { + startRecord = (TableRecord) bufMap.get(bufMap.firstKey()); + if (this.map.comparator().compare(objectAtStart, + objectAtPosition) == 0) { + currentRecord = startRecord; + } else { + // rewind to position + bufMap = bufMap.tailMap(objectAtPosition); + + if (!bufMap.isEmpty()) { + currentRecord = ((TableRecord) bufMap.get(bufMap + .firstKey())); + } else { + currentRecord = startRecord; + } + } + ret.start = startRecord; + ret.current = currentRecord; + ret.last = lastRecord; + } + } + } + + return ret; + } + + /** + * iterator over "head" part of the table data. it does not take + * "positional" parameter because it's used for scanning shadow tables and + * this scan never "resumes" + * + * @param objectAtEnd - + * lower boundary of the iteration + * @return leaps table iterator + */ + public TableIterator headIterator(Object objectAtEnd) { + TableIterator iterator = null; + TableRecord startRecord = this.headRecord; + TableRecord currentRecord = this.headRecord; + TableRecord lastRecord = null; + + if (!this.empty) { // validate + if (this.map.comparator().compare(this.headRecord.object, + objectAtEnd) <= 0) { + // let's check if we need iterator over the whole table + SortedMap bufMap = this.map.headMap(objectAtEnd); + if (!bufMap.isEmpty()) { + lastRecord = (TableRecord) bufMap.get(bufMap.lastKey()); + // check if the next one is what we need + if (lastRecord.right != null + && this.map.comparator().compare( + lastRecord.right.object, objectAtEnd) == 0) { + lastRecord = lastRecord.right; + } + iterator = new BaseTableIterator(startRecord, + currentRecord, lastRecord); + } else { + // empty iterator + iterator = new BaseTableIterator(null, null, null); + } + } else { + // empty iterator + iterator = new BaseTableIterator(null, null, null); + } + } else { + // empty iterator + iterator = new BaseTableIterator(null, null, null); + } + + return iterator; + } + + /** + * indicates if table has any elements + * + * @return empty indicator + */ + public boolean isEmpty() { + return this.empty; + } + + public String toString() { + String ret = ""; + + for (Iterator it = this.iterator(); it.hasNext();) { + ret = ret + it.next() + "\n"; + } + return ret; + } + + public int size() { + return this.count; + } + + public Object top() { + return this.headRecord.object; + } + + public Object bottom() { + return this.tailRecord.object; + } + + public static TableIterator singleItemIterator(Object object) { + return new BaseTableIterator(new TableRecord(object)); + } } diff --git a/drools-core/src/main/java/org/drools/leaps/util/TableOutOfBoundException.java b/drools-core/src/main/java/org/drools/leaps/util/TableOutOfBoundException.java deleted file mode 100644 index 2aad4938ec6..00000000000 --- a/drools-core/src/main/java/org/drools/leaps/util/TableOutOfBoundException.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.drools.leaps.util; - -/* - * Copyright 2005 Alexander Bagerman - * - * 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. - */ - -/** - * - * @author Alexander Bagerman - * - */ -public class TableOutOfBoundException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; - - public TableOutOfBoundException() { - super(); - } - - public TableOutOfBoundException(String msg) { - super(msg); - } - - public TableOutOfBoundException(Exception ex) { - super(ex); - } -} diff --git a/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java b/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java index 3734ea589ea..0160fe3273c 100644 --- a/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java +++ b/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import java.util.ArrayList; + import org.drools.DroolsTestCase; import org.drools.FactException; import org.drools.FactHandle; @@ -58,6 +60,8 @@ public void testEqualsMap() throws Exception { rule1.setConsequence(this.consequence); + LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()); + FactHandleImpl[] factHandles = new FactHandleImpl[1]; PropagationContext context1; LeapsTuple tuple1; @@ -68,7 +72,7 @@ public void testEqualsMap() throws Exception { context1 = new PropagationContextImpl(1, PropagationContext.ASSERTION, rule1, null); factHandles[0] = (FactHandleImpl) handle1; - tuple1 = new LeapsTuple(factHandles, null, context1); + tuple1 = new LeapsTuple(factHandles, leapsRule1, context1); this.workingMemory.assertTuple(tuple1); FactHandle logicalHandle1 = this.workingMemory.assertObject( logicalString1, false, true, null, this.workingMemory @@ -79,7 +83,7 @@ public void testEqualsMap() throws Exception { logicalString2, false, true, rule1, this.workingMemory .getAgenda().getActivations()[0]); factHandles[0] = (FactHandleImpl) logicalHandle2; - tuple1 = new LeapsTuple(factHandles, null, context1); + tuple1 = new LeapsTuple(factHandles, leapsRule1, context1); this.workingMemory.assertTuple(tuple1); assertSame(logicalHandle1, logicalHandle2); @@ -101,6 +105,8 @@ public void testStatedOverride() throws Exception { rule1.setConsequence(this.consequence); + LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()); + FactHandleImpl[] factHandles = new FactHandleImpl[1]; PropagationContext context1; LeapsTuple tuple1; @@ -111,7 +117,7 @@ public void testStatedOverride() throws Exception { context1 = new PropagationContextImpl(1, PropagationContext.ASSERTION, rule1, null); factHandles[0] = (FactHandleImpl) handle1; - tuple1 = new LeapsTuple(factHandles, null, context1); + tuple1 = new LeapsTuple(factHandles, leapsRule1, context1); this.workingMemory.assertTuple(tuple1); FactHandle logicalHandle1 = this.workingMemory.assertObject( logicalString1, false, true, null, this.workingMemory @@ -133,7 +139,7 @@ public void testStatedOverride() throws Exception { // Test that a logical assertion cannot override a STATED assertion factHandles[0] = (FactHandleImpl) logicalHandle2; - tuple1 = new LeapsTuple(factHandles, null, context1); + tuple1 = new LeapsTuple(factHandles, leapsRule1, context1); this.workingMemory.assertTuple(tuple1); logicalString2 = new String("logical"); @@ -174,6 +180,8 @@ public void testRetract() throws Exception { // create the first agendaItem which will justify the fact "logical" rule1.setConsequence(this.consequence); + LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()); + FactHandleImpl tuple1FactHandle = (FactHandleImpl) this.workingMemory .assertObject("tuple1 object"); FactHandleImpl tuple2FactHandle = (FactHandleImpl) this.workingMemory @@ -185,9 +193,9 @@ public void testRetract() throws Exception { PropagationContext context = new PropagationContextImpl(0, PropagationContext.ASSERTION, rule1, null); - LeapsTuple tuple1 = new LeapsTuple(factHandlesTuple1, null, + LeapsTuple tuple1 = new LeapsTuple(factHandlesTuple1, leapsRule1, context); - LeapsTuple tuple2 = new LeapsTuple(factHandlesTuple2, null, + LeapsTuple tuple2 = new LeapsTuple(factHandlesTuple2, leapsRule1, context); this.workingMemory.assertTuple(tuple1); Activation activation1 = this.workingMemory.getAgenda() @@ -204,7 +212,7 @@ public void testRetract() throws Exception { rule2.setConsequence(this.consequence); PropagationContext context2 = new PropagationContextImpl(0, PropagationContext.ASSERTION, rule2, null); - tuple1 = new LeapsTuple(factHandlesTuple2, null, context2); + tuple1 = new LeapsTuple(factHandlesTuple2, leapsRule1, context2); this.workingMemory.assertTuple(tuple1); Activation activation2 = this.workingMemory.getAgenda() .getActivations()[1]; @@ -227,6 +235,9 @@ public void testMultipleLogicalRelationships() throws FactException { final Rule rule1 = new Rule("test-rule1"); // create the first agendaItem which will justify the fact "logical" rule1.setConsequence(this.consequence); + + LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()); + FactHandleImpl tuple1Fact = (FactHandleImpl) this.workingMemory .assertObject("tuple1 object"); FactHandleImpl tuple2Fact = (FactHandleImpl) this.workingMemory @@ -238,7 +249,7 @@ public void testMultipleLogicalRelationships() throws FactException { PropagationContext context1 = new PropagationContextImpl(0, PropagationContext.ASSERTION, rule1, null); - LeapsTuple tuple1 = new LeapsTuple(tuple1Handles, null, context1); + LeapsTuple tuple1 = new LeapsTuple(tuple1Handles, leapsRule1, context1); this.workingMemory.assertTuple(tuple1); Activation activation1 = this.workingMemory.getAgenda() .getActivations()[0]; @@ -253,7 +264,7 @@ public void testMultipleLogicalRelationships() throws FactException { rule2.setConsequence(this.consequence); PropagationContext context2 = new PropagationContextImpl(0, PropagationContext.ASSERTION, rule2, null); - LeapsTuple tuple2 = new LeapsTuple(tuple2Handles, null, context2); + LeapsTuple tuple2 = new LeapsTuple(tuple2Handles, leapsRule1, context2); this.workingMemory.assertTuple(tuple2); // "logical" should only appear once Activation activation2 = this.workingMemory.getAgenda() diff --git a/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java b/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java index 4e243de91f2..25153262ee3 100644 --- a/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java +++ b/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java @@ -147,7 +147,7 @@ public void evaluate(KnowledgeHelper knowledgeHelper, data.size() ); // sleep for 0.5 seconds - Thread.sleep( 500 ); + Thread.sleep( 1000 ); // now check for update assertEquals( 4, diff --git a/drools-core/src/test/java/org/drools/leaps/util/TableTest.java b/drools-core/src/test/java/org/drools/leaps/util/TableTest.java index ff230cd3cb7..6e876f8235d 100644 --- a/drools-core/src/test/java/org/drools/leaps/util/TableTest.java +++ b/drools-core/src/test/java/org/drools/leaps/util/TableTest.java @@ -171,43 +171,39 @@ public void testTailIterator() { this.testTable.add(this.h1000); this.testTable.add(this.h100); this.testTable.add(this.h10); - try { - TableIterator it = this.testTable.tailIterator(this.h100, this.h10); - assertTrue(it.hasNext()); - assertEquals(it.next(), this.h10); - assertTrue(it.hasNext()); - assertEquals(it.next(), this.h1); - assertFalse(it.hasNext()); - it.reset(); - assertTrue(it.hasNext()); - assertEquals(it.next(), this.h100); - assertTrue(it.hasNext()); - assertEquals(it.next(), this.h10); - assertTrue(it.hasNext()); - assertEquals(it.next(), this.h1); - assertFalse(it.hasNext()); - - this.testTable.clear(); - Handle fh1 = new Handle(1, new Guest("1", Sex.resolve("m"), Hobby - .resolve("h2"))); - Handle fh2 = new Handle(2, new Guest("1", Sex.resolve("m"), Hobby - .resolve("h1"))); - Handle fh3 = new Handle(3, new Guest("1", Sex.resolve("m"), Hobby - .resolve("h3"))); - Handle fh4 = new Handle(4, new Guest("3", Sex.resolve("f"), Hobby - .resolve("h2"))); - Handle fhC = new Handle(5, new Context("start")); - this.testTable.add(fh1); - this.testTable.add(fh2); - this.testTable.add(fh3); - this.testTable.add(fh4); - it = this.testTable.tailIterator(fhC, fhC); - assertTrue(it.hasNext()); - assertEquals(it.next(), fh4); - - } catch (TableOutOfBoundException ex) { - - } + + TableIterator it = this.testTable.tailIterator(this.h100, this.h10); + assertTrue(it.hasNext()); + assertEquals(it.next(), this.h10); + assertTrue(it.hasNext()); + assertEquals(it.next(), this.h1); + assertFalse(it.hasNext()); + it.reset(); + assertTrue(it.hasNext()); + assertEquals(it.next(), this.h100); + assertTrue(it.hasNext()); + assertEquals(it.next(), this.h10); + assertTrue(it.hasNext()); + assertEquals(it.next(), this.h1); + assertFalse(it.hasNext()); + + this.testTable.clear(); + Handle fh1 = new Handle(1, new Guest("1", Sex.resolve("m"), Hobby + .resolve("h2"))); + Handle fh2 = new Handle(2, new Guest("1", Sex.resolve("m"), Hobby + .resolve("h1"))); + Handle fh3 = new Handle(3, new Guest("1", Sex.resolve("m"), Hobby + .resolve("h3"))); + Handle fh4 = new Handle(4, new Guest("3", Sex.resolve("f"), Hobby + .resolve("h2"))); + Handle fhC = new Handle(5, new Context("start")); + this.testTable.add(fh1); + this.testTable.add(fh2); + this.testTable.add(fh3); + this.testTable.add(fh4); + it = this.testTable.tailIterator(fhC, fhC); + assertTrue(it.hasNext()); + assertEquals(it.next(), fh4); } public void testHeadIterator() {
1722fa667819c3cafc6b5de93d7c93bbd570cd47
spring-framework
JSR-223 based StandardScriptFactory (including- <lang:std> support)--This commit also completes 4.2 schema variants in spring-context.--Issue: SPR-5215-
a
https://github.com/spring-projects/spring-framework
diff --git a/spring-context/src/main/java/org/springframework/scripting/ScriptCompilationException.java b/spring-context/src/main/java/org/springframework/scripting/ScriptCompilationException.java index ccb867450063..2064ae90800a 100644 --- a/spring-context/src/main/java/org/springframework/scripting/ScriptCompilationException.java +++ b/spring-context/src/main/java/org/springframework/scripting/ScriptCompilationException.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,7 @@ public ScriptCompilationException(String msg) { /** * Constructor for ScriptCompilationException. * @param msg the detail message - * @param cause the root cause (usually from using an underlying - * script compiler API) + * @param cause the root cause (usually from using an underlying script compiler API) */ public ScriptCompilationException(String msg, Throwable cause) { super(msg, cause); @@ -51,23 +50,32 @@ public ScriptCompilationException(String msg, Throwable cause) { /** * Constructor for ScriptCompilationException. * @param scriptSource the source for the offending script - * @param cause the root cause (usually from using an underlying - * script compiler API) + * @param msg the detail message + * @since 4.2 + */ + public ScriptCompilationException(ScriptSource scriptSource, String msg) { + super("Could not compile " + scriptSource + ": " + msg); + this.scriptSource = scriptSource; + } + + /** + * Constructor for ScriptCompilationException. + * @param scriptSource the source for the offending script + * @param cause the root cause (usually from using an underlying script compiler API) */ public ScriptCompilationException(ScriptSource scriptSource, Throwable cause) { - super("Could not compile script", cause); + super("Could not compile " + scriptSource, cause); this.scriptSource = scriptSource; } /** * Constructor for ScriptCompilationException. - * @param msg the detail message * @param scriptSource the source for the offending script - * @param cause the root cause (usually from using an underlying - * script compiler API) + * @param msg the detail message + * @param cause the root cause (usually from using an underlying script compiler API) */ public ScriptCompilationException(ScriptSource scriptSource, String msg, Throwable cause) { - super("Could not compile script [" + scriptSource + "]: " + msg, cause); + super("Could not compile " + scriptSource + ": " + msg, cause); this.scriptSource = scriptSource; } diff --git a/spring-context/src/main/java/org/springframework/scripting/config/LangNamespaceHandler.java b/spring-context/src/main/java/org/springframework/scripting/config/LangNamespaceHandler.java index b7888faa7817..8a113e9905a9 100644 --- a/spring-context/src/main/java/org/springframework/scripting/config/LangNamespaceHandler.java +++ b/spring-context/src/main/java/org/springframework/scripting/config/LangNamespaceHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,6 +44,7 @@ public void init() { registerScriptBeanDefinitionParser("groovy", "org.springframework.scripting.groovy.GroovyScriptFactory"); registerScriptBeanDefinitionParser("jruby", "org.springframework.scripting.jruby.JRubyScriptFactory"); registerScriptBeanDefinitionParser("bsh", "org.springframework.scripting.bsh.BshScriptFactory"); + registerScriptBeanDefinitionParser("std", "org.springframework.scripting.support.StandardScriptFactory"); registerBeanDefinitionParser("defaults", new ScriptingDefaultsParser()); } diff --git a/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java b/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java index de5aa7ea9ddb..67c9a3fe0b99 100644 --- a/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java +++ b/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,6 +55,8 @@ */ class ScriptBeanDefinitionParser extends AbstractBeanDefinitionParser { + private static final String ENGINE_ATTRIBUTE = "engine"; + private static final String SCRIPT_SOURCE_ATTRIBUTE = "script-source"; private static final String INLINE_SCRIPT_ELEMENT = "inline-script"; @@ -104,6 +106,9 @@ public ScriptBeanDefinitionParser(String scriptFactoryClassName) { @Override @SuppressWarnings("deprecation") protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { + // Engine attribute only supported for <lang:std> + String engine = element.getAttribute(ENGINE_ATTRIBUTE); + // Resolve the script source. String value = resolveScriptSource(element, parserContext.getReaderContext()); if (value == null) { @@ -184,9 +189,13 @@ else if (beanDefinitionDefaults.getDestroyMethodName() != null) { // Add constructor arguments. ConstructorArgumentValues cav = bd.getConstructorArgumentValues(); int constructorArgNum = 0; + if (StringUtils.hasLength(engine)) { + cav.addIndexedArgumentValue(constructorArgNum++, engine); + } cav.addIndexedArgumentValue(constructorArgNum++, value); if (element.hasAttribute(SCRIPT_INTERFACES_ATTRIBUTE)) { - cav.addIndexedArgumentValue(constructorArgNum++, element.getAttribute(SCRIPT_INTERFACES_ATTRIBUTE)); + cav.addIndexedArgumentValue( + constructorArgNum++, element.getAttribute(SCRIPT_INTERFACES_ATTRIBUTE), "java.lang.Class[]"); } // This is used for Groovy. It's a bean reference to a customizer bean. diff --git a/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java b/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java new file mode 100644 index 000000000000..8c6b8c979364 --- /dev/null +++ b/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java @@ -0,0 +1,248 @@ +/* + * Copyright 2002-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.scripting.support; + +import java.io.IOException; +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.scripting.ScriptCompilationException; +import org.springframework.scripting.ScriptFactory; +import org.springframework.scripting.ScriptSource; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * {@link org.springframework.scripting.ScriptFactory} implementation based + * on the JSR-223 script engine abstraction (as included in Java 6+). + * Supports JavaScript, Groovy, JRuby and other JSR-223 compliant engines. + * + * <p>Typically used in combination with a + * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor}; + * see the latter's javadoc for a configuration example. + * + * @author Juergen Hoeller + * @since 4.2 + * @see ScriptFactoryPostProcessor + */ +public class StandardScriptFactory implements ScriptFactory, BeanClassLoaderAware { + + private final String scriptEngineName; + + private final String scriptSourceLocator; + + private final Class<?>[] scriptInterfaces; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + private volatile ScriptEngine scriptEngine; + + + /** + * Create a new StandardScriptFactory for the given script source. + * @param scriptSourceLocator a locator that points to the source of the script. + * Interpreted by the post-processor that actually creates the script. + */ + public StandardScriptFactory(String scriptSourceLocator) { + this(null, scriptSourceLocator, (Class<?>[]) null); + } + + /** + * Create a new StandardScriptFactory for the given script source. + * @param scriptSourceLocator a locator that points to the source of the script. + * Interpreted by the post-processor that actually creates the script. + * @param scriptInterfaces the Java interfaces that the scripted object + * is supposed to implement + */ + public StandardScriptFactory(String scriptSourceLocator, Class<?>... scriptInterfaces) { + this(null, scriptSourceLocator, scriptInterfaces); + } + + /** + * Create a new StandardScriptFactory for the given script source. + * @param scriptEngineName the name of the JSR-223 ScriptEngine to use + * (explicitly given instead of inferred from the script source) + * @param scriptSourceLocator a locator that points to the source of the script. + * Interpreted by the post-processor that actually creates the script. + */ + public StandardScriptFactory(String scriptEngineName, String scriptSourceLocator) { + this(scriptEngineName, scriptSourceLocator, (Class<?>[]) null); + } + + /** + * Create a new StandardScriptFactory for the given script source. + * @param scriptEngineName the name of the JSR-223 ScriptEngine to use + * (explicitly given instead of inferred from the script source) + * @param scriptSourceLocator a locator that points to the source of the script. + * Interpreted by the post-processor that actually creates the script. + * @param scriptInterfaces the Java interfaces that the scripted object + * is supposed to implement + */ + public StandardScriptFactory(String scriptEngineName, String scriptSourceLocator, Class<?>... scriptInterfaces) { + Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty"); + this.scriptEngineName = scriptEngineName; + this.scriptSourceLocator = scriptSourceLocator; + this.scriptInterfaces = scriptInterfaces; + } + + + @Override + public void setBeanClassLoader(ClassLoader classLoader) { + this.beanClassLoader = classLoader; + } + + protected ScriptEngine retrieveScriptEngine(ScriptSource scriptSource) { + ScriptEngineManager scriptEngineManager = new ScriptEngineManager(this.beanClassLoader); + if (this.scriptEngineName != null) { + ScriptEngine engine = scriptEngineManager.getEngineByName(this.scriptEngineName); + if (engine == null) { + throw new IllegalStateException("Script engine named '" + this.scriptEngineName + "' not found"); + } + return engine; + } + if (scriptSource instanceof ResourceScriptSource) { + String filename = ((ResourceScriptSource) scriptSource).getResource().getFilename(); + if (filename != null) { + String extension = StringUtils.getFilenameExtension(filename); + if (extension != null) { + ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension); + if (engine != null) { + return engine; + } + } + } + } + return null; + } + + + @Override + public String getScriptSourceLocator() { + return this.scriptSourceLocator; + } + + @Override + public Class<?>[] getScriptInterfaces() { + return this.scriptInterfaces; + } + + @Override + public boolean requiresConfigInterface() { + return false; + } + + + /** + * Load and parse the script via JSR-223's ScriptEngine. + */ + @Override + public Object getScriptedObject(ScriptSource scriptSource, Class<?>... actualInterfaces) + throws IOException, ScriptCompilationException { + + Object script; + + try { + if (this.scriptEngine == null) { + this.scriptEngine = retrieveScriptEngine(scriptSource); + if (this.scriptEngine == null) { + throw new IllegalStateException("Could not determine script engine for " + scriptSource); + } + } + script = this.scriptEngine.eval(scriptSource.getScriptAsString()); + } + catch (Exception ex) { + throw new ScriptCompilationException(scriptSource, ex); + } + + if (!ObjectUtils.isEmpty(actualInterfaces)) { + boolean adaptationRequired = false; + for (Class<?> requestedIfc : actualInterfaces) { + if (!requestedIfc.isInstance(script)) { + adaptationRequired = true; + } + } + if (adaptationRequired) { + Class<?> adaptedIfc; + if (actualInterfaces.length == 1) { + adaptedIfc = actualInterfaces[0]; + } + else { + adaptedIfc = ClassUtils.createCompositeInterface(actualInterfaces, this.beanClassLoader); + } + if (adaptedIfc != null) { + if (!(this.scriptEngine instanceof Invocable)) { + throw new ScriptCompilationException(scriptSource, + "ScriptEngine must implement Invocable in order to adapt it to an interface: " + + this.scriptEngine); + } + Invocable invocable = (Invocable) this.scriptEngine; + if (script != null) { + script = invocable.getInterface(script, adaptedIfc); + } + if (script == null) { + script = invocable.getInterface(adaptedIfc); + if (script == null) { + throw new ScriptCompilationException(scriptSource, + "Could not adapt script to interface [" + adaptedIfc.getName() + "]"); + } + } + } + } + } + + if (script instanceof Class) { + Class<?> scriptClass = (Class<?>) script; + try { + return scriptClass.newInstance(); + } + catch (InstantiationException ex) { + throw new ScriptCompilationException( + scriptSource, "Could not instantiate script class: " + scriptClass.getName(), ex); + } + catch (IllegalAccessException ex) { + throw new ScriptCompilationException( + scriptSource, "Could not access script constructor: " + scriptClass.getName(), ex); + } + } + + return script; + } + + @Override + public Class<?> getScriptedObjectType(ScriptSource scriptSource) + throws IOException, ScriptCompilationException { + + return null; + } + + @Override + public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) { + return scriptSource.isModified(); + } + + + @Override + public String toString() { + return "StandardScriptFactory: script source locator [" + this.scriptSourceLocator + "]"; + } + +} diff --git a/spring-context/src/main/resources/META-INF/spring.schemas b/spring-context/src/main/resources/META-INF/spring.schemas index 26ff291eed35..3cac0ddd7997 100644 --- a/spring-context/src/main/resources/META-INF/spring.schemas +++ b/spring-context/src/main/resources/META-INF/spring.schemas @@ -4,7 +4,8 @@ http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/spring http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd http\://www.springframework.org/schema/context/spring-context-4.0.xsd=org/springframework/context/config/spring-context-4.0.xsd http\://www.springframework.org/schema/context/spring-context-4.1.xsd=org/springframework/context/config/spring-context-4.1.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-4.1.xsd +http\://www.springframework.org/schema/context/spring-context-4.2.xsd=org/springframework/context/config/spring-context-4.2.xsd +http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-4.2.xsd http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd @@ -12,7 +13,8 @@ http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframewor http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd http\://www.springframework.org/schema/jee/spring-jee-4.0.xsd=org/springframework/ejb/config/spring-jee-4.0.xsd http\://www.springframework.org/schema/jee/spring-jee-4.1.xsd=org/springframework/ejb/config/spring-jee-4.1.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-4.1.xsd +http\://www.springframework.org/schema/jee/spring-jee-4.2.xsd=org/springframework/ejb/config/spring-jee-4.2.xsd +http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-4.2.xsd http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd @@ -20,15 +22,18 @@ http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframew http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd http\://www.springframework.org/schema/lang/spring-lang-4.0.xsd=org/springframework/scripting/config/spring-lang-4.0.xsd http\://www.springframework.org/schema/lang/spring-lang-4.1.xsd=org/springframework/scripting/config/spring-lang-4.1.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-4.1.xsd +http\://www.springframework.org/schema/lang/spring-lang-4.2.xsd=org/springframework/scripting/config/spring-lang-4.2.xsd +http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-4.2.xsd http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd http\://www.springframework.org/schema/task/spring-task-4.0.xsd=org/springframework/scheduling/config/spring-task-4.0.xsd http\://www.springframework.org/schema/task/spring-task-4.1.xsd=org/springframework/scheduling/config/spring-task-4.1.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-4.1.xsd +http\://www.springframework.org/schema/task/spring-task-4.2.xsd=org/springframework/scheduling/config/spring-task-4.2.xsd +http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-4.2.xsd http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd http\://www.springframework.org/schema/cache/spring-cache-4.0.xsd=org/springframework/cache/config/spring-cache-4.0.xsd http\://www.springframework.org/schema/cache/spring-cache-4.1.xsd=org/springframework/cache/config/spring-cache-4.1.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-4.1.xsd +http\://www.springframework.org/schema/cache/spring-cache-4.2.xsd=org/springframework/cache/config/spring-cache-4.2.xsd +http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-4.2.xsd diff --git a/spring-context/src/main/resources/org/springframework/cache/config/spring-cache-4.2.xsd b/spring-context/src/main/resources/org/springframework/cache/config/spring-cache-4.2.xsd new file mode 100644 index 000000000000..66104b98dbe2 --- /dev/null +++ b/spring-context/src/main/resources/org/springframework/cache/config/spring-cache-4.2.xsd @@ -0,0 +1,310 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> + +<xsd:schema xmlns="http://www.springframework.org/schema/cache" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:beans="http://www.springframework.org/schema/beans" + xmlns:tool="http://www.springframework.org/schema/tool" + targetNamespace="http://www.springframework.org/schema/cache" + elementFormDefault="qualified" + attributeFormDefault="unqualified"> + + <xsd:import namespace="http://www.springframework.org/schema/beans" schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"/> + <xsd:import namespace="http://www.springframework.org/schema/tool" schemaLocation="http://www.springframework.org/schema/tool/spring-tool-4.1.xsd"/> + + <xsd:annotation> + <xsd:documentation><![CDATA[ + Defines the elements used in the Spring Framework's declarative + cache management infrastructure. + ]]></xsd:documentation> + </xsd:annotation> + + <xsd:element name="annotation-driven"> + <xsd:complexType> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.annotation.AnnotationCacheOperationDefinitionSource"><![CDATA[ + Indicates that cache configuration is defined by Java 5 + annotations on bean classes, and that proxies are automatically + to be created for the relevant annotated beans. + + The default annotations supported are Spring's @Cacheable, @CachePut and @CacheEvict. If + spring-context-support and the JSR-107 API are on the classpath, additional proxies are + automatically created for JSR-107 annotated beans, that is @CacheResult, @CachePut, + @CacheRemove and @CacheRemoveAll. + + See org.springframework.cache.annotation.EnableCaching Javadoc + for information on code-based alternatives to this XML element. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:attribute name="cache-manager" type="xsd:string" default="cacheManager"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.CacheManager"><![CDATA[ + The bean name of the CacheManager that is to be used to retrieve the backing + caches. A default CacheResolver will be initialized behind the scenes with + this cache manager (or "cacheManager" if not set). For more fine-grained + management of the cache resolution, consider setting the 'cache-resolver' + attribute. + + Note that this attribute is still mandatory if you are using JSR-107 as an + additional exception cache resolver should be created and requires a CacheManager + to do so. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="org.springframework.cache.CacheManager"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="cache-resolver" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.interceptor.CacheResolver"><![CDATA[ + The bean name of the CacheResolver that is to be used to resolve the backing caches. + + This attribute is not required, and only needs to be specified as an alternative to + the 'cache-manager' attribute. See the javadoc of CacheResolver for more details. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="org.springframework.cache.interceptor.CacheResolver"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="key-generator" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.interceptor.KeyGenerator"><![CDATA[ + The bean name of the KeyGenerator that is to be used to retrieve the backing caches. + + This attribute is not required, and only needs to be specified + explicitly if the default strategy (DefaultKeyGenerator) is not sufficient. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="org.springframework.cache.interceptor.KeyGenerator"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="error-handler" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.interceptor.CacheErrorHandler"><![CDATA[ + The bean name of the CacheErrorHandler that is to be used to handle cache-related errors. + + This attribute is not required, and only needs to be specified + explicitly if the default strategy (SimpleCacheErrorHandler) is not sufficient. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="org.springframework.cache.interceptor.CacheErrorHandler"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="mode" default="proxy"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Should annotated beans be proxied using Spring's AOP framework, + or should they rather be weaved with an AspectJ transaction aspect? + + AspectJ weaving requires spring-aspects.jar on the classpath, + as well as load-time weaving (or compile-time weaving) enabled. + + Note: The weaving-based aspect requires the @Cacheable and @CacheInvalidate + annotations to be defined on the concrete class. Annotations in interfaces + will not work in that case (they will rather only work with interface-based proxies)! + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="proxy"/> + <xsd:enumeration value="aspectj"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="proxy-target-class" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Are class-based (CGLIB) proxies to be created? By default, standard + Java interface-based proxies are created. + + Note: Class-based proxies require the @Cacheable and @CacheInvalidate annotations + to be defined on the concrete class. Annotations in interfaces will not work + in that case (they will rather only work with interface-based proxies)! + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="order" type="xsd:token"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.core.Ordered"><![CDATA[ + Controls the ordering of the execution of the cache advisor + when multiple advice executes at a specific joinpoint. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="advice"> + <xsd:complexType> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.interceptor.CacheInterceptor"><![CDATA[ + Defines the cache semantics of the AOP advice that is to be + executed. + + That is, this advice element is where the cacheable semantics of + any number of methods are defined (where cacheable semantics + includes the backing cache(s), the key, cache condition rules, and suchlike). + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:exports type="java:org.springframework.cache.interceptor.CacheInterceptor"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + <xsd:complexContent> + <xsd:extension base="beans:identifiedType"> + <xsd:sequence> + <xsd:element name="caching" type="definitionsType" minOccurs="0" maxOccurs="unbounded"/> + </xsd:sequence> + <xsd:attribute name="cache-manager" type="xsd:string" default="cacheManager"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.CacheManager"><![CDATA[ + The bean name of the CacheManager that is to be used + for storing and retrieving data. + + This attribute is not required, and only needs to be specified + explicitly if the bean name of the desired CacheManager + is not 'cacheManager'. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="org.springframework.cache.CacheManager"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="key-generator" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.cache.interceptor.KeyGenerator"><![CDATA[ + The bean name of the KeyGenerator that is to be used to retrieve the backing caches. + + This attribute is not required, and only needs to be specified + explicitly if the default strategy (DefaultKeyGenerator) is not sufficient. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="org.springframework.cache.interceptor.KeyGenerator"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:complexType name="basedefinitionType"> + <xsd:attribute name="cache" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of the backing cache(s). Multiple caches can be specified by separating them using comma: 'orders, books']]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="key" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The SpEL expression used for computing the cache key, mutually exclusive with the key-generator parameter.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="key-generator" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of the KeyGenerator bean responsible to compute the key, mutually exclusive with the key parameter.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="cache-manager" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of the CacheManager bean responsible to manage the operation.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="condition" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The SpEL expression used for conditioning the method caching.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="method" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The method name(s) with which the cache attributes are to be + associated. The wildcard (*) character can be used to associate the + same cache attribute settings with a number of methods; for + example, 'get*', 'handle*', '*Order', 'on*Event', etc.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + + </xsd:complexType> + + <xsd:complexType name="definitionsType"> + <xsd:complexContent> + <xsd:extension base="basedefinitionType"> + <xsd:sequence> + <xsd:choice minOccurs="0" maxOccurs="unbounded"> + <xsd:element name="cacheable" minOccurs="0" maxOccurs="unbounded"> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="basedefinitionType"> + <xsd:attribute name="unless" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The SpEL expression used to veto the method caching.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + <xsd:element name="cache-put" minOccurs="0" maxOccurs="unbounded"> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="basedefinitionType"> + <xsd:attribute name="unless" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The SpEL expression used to veto the method caching.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + <xsd:element name="cache-evict" minOccurs="0" maxOccurs="unbounded"> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="basedefinitionType"> + <xsd:attribute name="all-entries" type="xsd:boolean" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Whether all the entries should be evicted.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="before-invocation" type="xsd:boolean" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Whether the eviction should occur after the method is successfully + invoked (default) or before.]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:sequence> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + +</xsd:schema> diff --git a/spring-context/src/main/resources/org/springframework/context/config/spring-context-4.2.xsd b/spring-context/src/main/resources/org/springframework/context/config/spring-context-4.2.xsd new file mode 100644 index 000000000000..d9aeea34c1ae --- /dev/null +++ b/spring-context/src/main/resources/org/springframework/context/config/spring-context-4.2.xsd @@ -0,0 +1,520 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<xsd:schema xmlns="http://www.springframework.org/schema/context" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:beans="http://www.springframework.org/schema/beans" + xmlns:tool="http://www.springframework.org/schema/tool" + targetNamespace="http://www.springframework.org/schema/context" + elementFormDefault="qualified" + attributeFormDefault="unqualified"> + + <xsd:import namespace="http://www.springframework.org/schema/beans" schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"/> + <xsd:import namespace="http://www.springframework.org/schema/tool" schemaLocation="http://www.springframework.org/schema/tool/spring-tool-4.1.xsd"/> + + <xsd:annotation> + <xsd:documentation><![CDATA[ + Defines the configuration elements for the Spring Framework's application + context support. Effects the activation of various configuration styles + for the containing Spring ApplicationContext. + ]]></xsd:documentation> + </xsd:annotation> + + <xsd:complexType name="propertyPlaceholder"> + <xsd:attribute name="location" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The location of the properties file to resolve placeholders against, as a Spring + resource location: a URL, a "classpath:" pseudo URL, or a relative file path. + Multiple locations may be specified, separated by commas. If neither location nor + properties-ref is specified, placeholders will be resolved against system properties. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="properties-ref" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:java.util.Properties"><![CDATA[ + The bean name of a Properties object that will be used for property substitution. + If neither location nor properties-ref is specified, placeholders will be resolved + against system properties. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="file-encoding" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies the encoding to use for parsing properties files. Default is none, + using the java.util.Properties default encoding. Only applies to classic + properties files, not to XML files. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="order" type="xsd:token"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies the order for this placeholder configurer. If more than one is present + in a context, the order can be important since the first one to be match a + placeholder will win. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="ignore-resource-not-found" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies if failure to find the property resource location should be ignored. + Default is "false", meaning that if there is no file in the location specified + an exception will be raised at runtime. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="ignore-unresolvable" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies if failure to find the property value to replace a key should be ignored. + Default is "false", meaning that this placeholder configurer will raise an exception + if it cannot resolve a key. Set to "true" to allow the configurer to pass on the key + to any others in the context that have not yet visited the key in question. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="local-override" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies whether local properties override properties from files. + Default is "false": Properties from files override local defaults. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + + <xsd:element name="property-placeholder"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Activates replacement of ${...} placeholders by registering a + PropertySourcesPlaceholderConfigurer within the application context. Properties will + be resolved against the specified properties file or Properties object -- so called + "local properties", if any, and against the Spring Environment's current set of + PropertySources. + + Note that as of Spring 3.1 the system-properties-mode attribute has been removed in + favor of the more flexible PropertySources mechanism. However, Spring 3.1-based + applications may continue to use the 3.0 (and older) versions of the spring-context + schema in order to preserve system-properties-mode behavior. In this case, the + traditional PropertyPlaceholderConfigurer component will be registered instead of the + new PropertySourcesPlaceholderConfigurer. + + See ConfigurableEnvironment javadoc for more information on using. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:exports type="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="propertyPlaceholder"> + <xsd:attribute name="system-properties-mode" default="ENVIRONMENT"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls how to resolve placeholders against system properties. As of Spring 3.1, this + attribute value defaults to "ENVIRONMENT", indicating that resolution of placeholders + against system properties is handled via PropertySourcesPlaceholderConfigurer and its + delegation to the current Spring Environment object. + + For maximum backward compatibility, this attribute is preserved going forward with the + 3.1 version of the context schema, and any values other than the default "ENVIRONMENT" + will cause a traditional PropertyPlaceholderConfigurer to be registered instead of the + newer PropertySourcesPlaceholderConfigurer variant. In this case, the Spring Environment + and its property sources are not interrogated when resolving placeholders. Users are + encouraged to consider this attribute deprecated, and to take advantage of + Environment/PropertySource mechanisms. See ConfigurableEnvironment javadoc for examples. + + "ENVIRONMENT" indicates placeholders should be resolved against the current Environment and against any local properties; + "NEVER" indicates placeholders should be resolved only against local properties and never against system properties; + "FALLBACK" indicates placeholders should be resolved against any local properties and then against system properties; + "OVERRIDE" indicates placeholders should be resolved first against system properties and then against any local properties; + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="ENVIRONMENT"/> + <xsd:enumeration value="NEVER"/> + <xsd:enumeration value="FALLBACK"/> + <xsd:enumeration value="OVERRIDE"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:element name="property-override"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Activates pushing of override values into bean properties, based on configuration + lines of the following format: beanName.property=value + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:exports type="org.springframework.beans.factory.config.PropertyOverrideConfigurer"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="propertyPlaceholder"/> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:element name="annotation-config"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Activates various annotations to be detected in bean classes: Spring's @Required and + @Autowired, as well as JSR 250's @PostConstruct, @PreDestroy and @Resource (if available), + JAX-WS's @WebServiceRef (if available), EJB3's @EJB (if available), and JPA's + @PersistenceContext and @PersistenceUnit (if available). Alternatively, you may + choose to activate the individual BeanPostProcessors for those annotations. + + Note: This tag does not activate processing of Spring's @Transactional or EJB3's + @TransactionAttribute annotation. Consider the use of the <tx:annotation-driven> + tag for that purpose. + + See javadoc for org.springframework.context.annotation.AnnotationConfigApplicationContext + for information on code-based alternatives to bootstrapping annotation-driven support. + from XML. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + + <xsd:element name="component-scan"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Scans the classpath for annotated components that will be auto-registered as + Spring beans. By default, the Spring-provided @Component, @Repository, + @Service, and @Controller stereotypes will be detected. + + Note: This tag implies the effects of the 'annotation-config' tag, activating @Required, + @Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext and @PersistenceUnit + annotations in the component classes, which is usually desired for autodetected components + (without external configuration). Turn off the 'annotation-config' attribute to deactivate + this default behavior, for example in order to use custom BeanPostProcessor definitions + for handling those annotations. + + Note: You may use placeholders in package paths, but only resolved against system + properties (analogous to resource paths). A component scan results in new bean definition + being registered; Spring's PropertyPlaceholderConfigurer will apply to those bean + definitions just like to regular bean definitions, but it won't apply to the component + scan settings themselves. + + See javadoc for org.springframework.context.annotation.ComponentScan for information + on code-based alternatives to bootstrapping component-scanning. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="include-filter" type="filterType" + minOccurs="0" maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls which eligible types to include for component scanning. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + <xsd:element name="exclude-filter" type="filterType" + minOccurs="0" maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls which eligible types to exclude for component scanning. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + <xsd:attribute name="base-package" type="xsd:string" + use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The comma/semicolon/space/tab/linefeed-separated list of packages to scan for annotated components. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="resource-pattern" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls the class files eligible for component detection. Defaults to "**/*.class", the recommended value. + Consider use of the include-filter and exclude-filter elements for a more fine-grained approach. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="use-default-filters" type="xsd:boolean" + default="true"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Indicates whether automatic detection of classes annotated with @Component, @Repository, @Service, + or @Controller should be enabled. Default is "true". + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="annotation-config" type="xsd:boolean" + default="true"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Indicates whether the implicit annotation post-processors should be enabled. Default is "true". + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="name-generator" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The fully-qualified class name of the BeanNameGenerator to be used for naming detected components. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:expected-type type="java.lang.Class"/> + <tool:assignable-to type="org.springframework.beans.factory.support.BeanNameGenerator"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="scope-resolver" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The fully-qualified class name of the ScopeMetadataResolver to be used for resolving the scope of + detected components. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:expected-type type="java.lang.Class"/> + <tool:assignable-to type="org.springframework.context.annotation.ScopeMetadataResolver"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="scoped-proxy"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Indicates whether proxies should be generated for detected components, which may be necessary + when using scopes in a proxy-style fashion. Default is to generate no such proxies. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="no"/> + <xsd:enumeration value="interfaces"/> + <xsd:enumeration value="targetClass"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="load-time-weaver"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Activates a Spring LoadTimeWeaver for this application context, available as + a bean with the name "loadTimeWeaver". Any bean that implements the + LoadTimeWeaverAware interface will then receive the LoadTimeWeaver reference + automatically; for example, Spring's JPA bootstrap support. + + The default weaver is determined automatically: see DefaultContextLoadTimeWeaver's + javadoc for details. + + The activation of AspectJ load-time weaving is specified via a simple flag + (the 'aspectj-weaving' attribute), with the AspectJ class transformer + registered through Spring's LoadTimeWeaver. AspectJ weaving will be activated + by default if a "META-INF/aop.xml" resource is present in the classpath. + + This also activates the current application context for applying dependency + injection to non-managed classes that are instantiated outside of the Spring + bean factory (typically classes annotated with the @Configurable annotation). + This will only happen if the AnnotationBeanConfigurerAspect is on the classpath + (i.e. spring-aspects.jar), effectively activating "spring-configured" by default. + + See javadoc for org.springframework.context.annotation.EnableLoadTimeWeaving + for information on code-based alternatives to bootstrapping load-time weaving support. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:exports type="org.springframework.instrument.classloading.LoadTimeWeaver"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + <xsd:complexType> + <xsd:attribute name="weaver-class" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The fully-qualified classname of the LoadTimeWeaver that is to be activated. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:expected-type type="java.lang.Class"/> + <tool:assignable-to type="org.springframework.instrument.classloading.LoadTimeWeaver"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="aspectj-weaving" default="autodetect"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="on"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Switches Spring-based AspectJ load-time weaving on. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:enumeration> + <xsd:enumeration value="off"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Switches Spring-based AspectJ load-time weaving off. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:enumeration> + <xsd:enumeration value="autodetect"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Switches AspectJ load-time weaving on if a "META-INF/aop.xml" resource + is present in the classpath. If there is no such resource, then AspectJ + load-time weaving will be switched off. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:enumeration> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="spring-configured"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect"><![CDATA[ + Signals the current application context to apply dependency injection + to non-managed classes that are instantiated outside of the Spring bean + factory (typically classes annotated with the @Configurable annotation). + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:element> + + <xsd:element name="mbean-export"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.jmx.export.annotation.AnnotationMBeanExporter"><![CDATA[ + Activates default exporting of MBeans by detecting standard MBeans in the Spring + context as well as @ManagedResource annotations on Spring-defined beans. + + The resulting MBeanExporter bean is defined under the name "mbeanExporter". + Alternatively, consider defining a custom AnnotationMBeanExporter bean explicitly. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:exports type="org.springframework.jmx.export.annotation.AnnotationMBeanExporter"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + <xsd:complexType> + <xsd:attribute name="default-domain" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The default domain to use when generating JMX ObjectNames. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="server" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The bean name of the MBeanServer to which MBeans should be exported. + Default is to use the platform's default MBeanServer (autodetecting + WebLogic, WebSphere and the JVM's platform MBeanServer). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="registration"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The registration behavior, indicating how to deal with existing MBeans + of the same name: fail with an exception, ignore and keep the existing + MBean, or replace the existing one with the new MBean. + + Default is to fail with an exception. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:NMTOKEN"> + <xsd:enumeration value="failOnExisting"/> + <xsd:enumeration value="ignoreExisting"/> + <xsd:enumeration value="replaceExisting"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="mbean-server"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.jmx.support.MBeanServerFactoryBean"><![CDATA[ + Exposes a default MBeanServer for the current platform. + Autodetects WebLogic, WebSphere and the JVM's platform MBeanServer. + + The default bean name for the exposed MBeanServer is "mbeanServer". + This may be customized through specifying the "id" attribute. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:exports type="javax.management.MBeanServer"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="beans:identifiedType"> + <xsd:attribute name="agent-id" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The agent id of the target MBeanServer, if any. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:complexType name="filterType"> + <xsd:attribute name="type" use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls the type of filtering to apply to the expression. + + "annotation" indicates an annotation to be present at the type level in target components; + "assignable" indicates a class (or interface) that the target components are assignable to (extend/implement); + "aspectj" indicates an AspectJ type pattern expression to be matched by the target components; + "regex" indicates a regex pattern to be matched by the target components' class names; + "custom" indicates a custom implementation of the org.springframework.core.type.TypeFilter interface. + + Note: This attribute will not be inherited by child bean definitions. + Hence, it needs to be specified per concrete bean definition. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="annotation"/> + <xsd:enumeration value="assignable"/> + <xsd:enumeration value="aspectj"/> + <xsd:enumeration value="regex"/> + <xsd:enumeration value="custom"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="expression" type="xsd:string" use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Indicates the filter expression, the type of which is indicated by "type". + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + +</xsd:schema> diff --git a/spring-context/src/main/resources/org/springframework/ejb/config/spring-jee-4.2.xsd b/spring-context/src/main/resources/org/springframework/ejb/config/spring-jee-4.2.xsd new file mode 100644 index 000000000000..3ad80562fbe0 --- /dev/null +++ b/spring-context/src/main/resources/org/springframework/ejb/config/spring-jee-4.2.xsd @@ -0,0 +1,267 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> + +<xsd:schema xmlns="http://www.springframework.org/schema/jee" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:beans="http://www.springframework.org/schema/beans" + xmlns:tool="http://www.springframework.org/schema/tool" + targetNamespace="http://www.springframework.org/schema/jee" + elementFormDefault="qualified" + attributeFormDefault="unqualified"> + + <xsd:import namespace="http://www.springframework.org/schema/beans" schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"/> + <xsd:import namespace="http://www.springframework.org/schema/tool" schemaLocation="http://www.springframework.org/schema/tool/spring-tool-4.1.xsd"/> + + <xsd:annotation> + <xsd:documentation><![CDATA[ + Defines configuration elements for access to traditional Java EE components + such as JNDI resources and EJB session beans. + ]]></xsd:documentation> + </xsd:annotation> + + <xsd:element name="jndi-lookup"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.jndi.JndiObjectFactoryBean"><![CDATA[ + Exposes an object reference via a JNDI lookup. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="jndiLocatingType"> + <xsd:attribute name="cache" type="xsd:boolean" default="true"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls whether the object returned from the JNDI lookup is cached + after the first lookup. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="expected-type" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:java.lang.Class"><![CDATA[ + The type that the located JNDI object is supposed to be assignable + to, if indeed any. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="lookup-on-startup" type="xsd:boolean" default="true"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls whether the JNDI lookup is performed immediately on startup + (if true, the default), or on first access (if false). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="proxy-interface" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:java.lang.Class"><![CDATA[ + The proxy interface to use for the JNDI object. + + Needs to be specified because the actual JNDI object type is not + known in advance in case of a lazy lookup. + + Typically used in conjunction with "lookupOnStartup"=false and/or + "cache"=false. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:expected-type type="java.lang.Class"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="default-value" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specify a default literal value to fall back to if the JNDI lookup fails. + This is typically used for literal values in scenarios where the JNDI environment + might define specific config settings but those are not required to be present. + + Default is none. Note: This is only supported for lookup on startup. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="default-ref" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specify a default bean reference to fall back to if the JNDI lookup fails. + This might for example point to a local fallback DataSource. + + Default is none. Note: This is only supported for lookup on startup. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:element name="local-slsb" type="ejbType"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean"><![CDATA[ + Exposes a reference to a local EJB Stateless SessionBean. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + + <xsd:element name="remote-slsb"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean"><![CDATA[ + Exposes a reference to a remote EJB Stateless SessionBean. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="ejbType"> + <xsd:attribute name="home-interface" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:java.lang.Class"><![CDATA[ + The home interface that will be narrowed to before performing + the parameterless SLSB create() call that returns the actual + SLSB proxy. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="refresh-home-on-connect-failure" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls whether to refresh the EJB home on connect failure. + + Can be turned on to allow for hot restart of the EJB server. + If a cached EJB home throws an RMI exception that indicates a + remote connect failure, a fresh home will be fetched and the + invocation will be retried. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="cache-session-bean" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls whether to cache the actual session bean object. + + Off by default for standard EJB compliance. Turn this flag + on to optimize session bean access for servers that are + known to allow for caching the actual session bean object. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <!-- base types --> + <xsd:complexType name="jndiLocatingType" abstract="true"> + <xsd:complexContent> + <xsd:extension base="beans:identifiedType"> + <xsd:sequence> + <xsd:element name="environment" minOccurs="0" maxOccurs="1"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The newline-separated, key-value pairs for the JNDI environment + (in standard Properties format, namely 'key=value' pairs) + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"/> + </xsd:simpleType> + </xsd:element> + </xsd:sequence> + <xsd:attribute name="environment-ref" type="environmentRefType"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + A reference to JNDI environment properties, indicating the name of a + shared bean of type [java.util.Properties}. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="jndi-name" type="xsd:string" use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The JNDI name to look up. This may be a fully-qualified JNDI path + or a local Java EE environment naming context path in which case the + prefix "java:comp/env/" will be prepended if applicable. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="resource-ref" type="xsd:boolean" default="true"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls whether the lookup occurs in a Java EE container, i.e. if the + prefix "java:comp/env/" needs to be added if the JNDI name doesn't + already contain it. Default is "true" (since Spring 2.5). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="expose-access-context" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Set whether to expose the JNDI environment context for all access to the target + EJB, i.e. for all method invocations on the exposed object reference. + Default is "false", i.e. to only expose the JNDI context for object lookup. + + Switch this flag to "true" in order to expose the JNDI environment (including + the authorization context) for each EJB invocation, as needed by WebLogic + for EJBs with authorization requirements. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="lazy-init" default="default" type="beans:defaultable-boolean"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Indicates whether or not this bean is to be lazily initialized. + If false, it will be instantiated on startup by bean factories + that perform eager initialization of singletons. The default is + "false". + + Note: This attribute will not be inherited by child bean definitions. + Hence, it needs to be specified per concrete bean definition. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + + <xsd:complexType name="ejbType"> + <xsd:complexContent> + <xsd:extension base="jndiLocatingType"> + <xsd:attribute name="lookup-home-on-startup" type="xsd:boolean" default="true"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls whether the lookup of the EJB home object is performed + immediately on startup (if true, the default), or on first access + (if false). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="cache-home" type="xsd:boolean" default="true"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Controls whether the EJB home object is cached once it has been located. + On by default; turn this flag off to always reobtain fresh home objects. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="business-interface" type="xsd:string" use="required"> + <xsd:annotation> + <xsd:documentation source="java:java.lang.Class"><![CDATA[ + The business interface of the EJB being proxied. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + + <xsd:simpleType name="environmentRefType"> + <xsd:annotation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="java.util.Properties"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + <xsd:union memberTypes="xsd:string"/> + </xsd:simpleType> + +</xsd:schema> diff --git a/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-4.2.xsd b/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-4.2.xsd new file mode 100644 index 000000000000..c4304fa185ea --- /dev/null +++ b/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-4.2.xsd @@ -0,0 +1,307 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> + +<xsd:schema xmlns="http://www.springframework.org/schema/task" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:tool="http://www.springframework.org/schema/tool" + targetNamespace="http://www.springframework.org/schema/task" + elementFormDefault="qualified" + attributeFormDefault="unqualified"> + + <xsd:annotation> + <xsd:documentation><![CDATA[ + Defines the elements used in the Spring Framework's support for task execution and scheduling. + ]]></xsd:documentation> + </xsd:annotation> + + <xsd:import namespace="http://www.springframework.org/schema/beans" schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"/> + <xsd:import namespace="http://www.springframework.org/schema/tool" schemaLocation="http://www.springframework.org/schema/tool/spring-tool-4.1.xsd"/> + + <xsd:element name="annotation-driven"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Enables the detection of @Async and @Scheduled annotations on any Spring-managed + object. If present, a proxy will be generated for executing the annotated methods + asynchronously. + + See Javadoc for the org.springframework.scheduling.annotation.EnableAsync and + org.springframework.scheduling.annotation.EnableScheduling annotations for information + on code-based alternatives to this XML element. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:attribute name="executor" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies the java.util.Executor instance to use when invoking asynchronous methods. + If not provided, an instance of org.springframework.core.task.SimpleAsyncTaskExecutor + will be used by default. + Note that as of Spring 3.1.2, individual @Async methods may qualify which executor to + use, meaning that the executor specified here acts as a default for all non-qualified + @Async methods. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="exception-handler" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies the org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler + instance to use when an exception is thrown during an asynchronous method execution + and cannot be accessed by the caller. If not provided, an instance of + org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler will be + used by default. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="scheduler" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Specifies the org.springframework.scheduling.TaskScheduler or + java.util.ScheduledExecutorService instance to use when invoking scheduled + methods. If no reference is provided, a TaskScheduler backed by a single + thread scheduled executor will be used. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="mode" default="proxy"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Should annotated beans be proxied using Spring's AOP framework, + or should they rather be weaved with an AspectJ async execution aspect? + + AspectJ weaving requires spring-aspects.jar on the classpath, + as well as load-time weaving (or compile-time weaving) enabled. + + Note: The weaving-based aspect requires the @Async annotation to be + defined on the concrete class. Annotations in interfaces will not work + in that case (they will rather only work with interface-based proxies)! + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="proxy"/> + <xsd:enumeration value="aspectj"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="proxy-target-class" type="xsd:boolean" default="false"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Are class-based (CGLIB) proxies to be created? By default, standard + Java interface-based proxies are created. + + Note: Class-based proxies require the @Async annotation to be defined + on the concrete class. Annotations in interfaces will not work in + that case (they will rather only work with interface-based proxies)! + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="scheduler"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Defines a ThreadPoolTaskScheduler instance with configurable pool size. See Javadoc + for the org.springframework.scheduling.annotation.EnableScheduling annotation for + information on a code-based alternative to this XML element. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:attribute name="id" type="xsd:string" use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The bean name for the generated ThreadPoolTaskScheduler instance. + It will also be used as the default thread name prefix. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="pool-size" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The size of the ScheduledExecutorService's thread pool. The default is 1. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="executor"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Defines a ThreadPoolTaskExecutor instance with configurable pool size, + queue-capacity, keep-alive, and rejection-policy values. + + See Javadoc for the org.springframework.scheduling.annotation.EnableAsync annotation + for information on code-based alternatives to this XML element. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:attribute name="id" type="xsd:string" use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The bean name for the generated ThreadPoolTaskExecutor instance. + This value will also be used as the thread name prefix which is why it is + required even when defining the executor as an inner bean: The executor + won't be directly accessible then but will nevertheless use the specified + id as the thread name prefix of the threads that it manages. + In the case of multiple task:executors, as of Spring 3.1.2 this value may be used to + qualify which executor should handle a given @Async method, e.g. @Async("executorId"). + See the Javadoc for the #value attribute of Spring's @Async annotation for details. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="pool-size" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The size of the executor's thread pool as either a single value or a range + (e.g. 5-10). If no bounded queue-capacity value is provided, then a max value + has no effect unless the range is specified as 0-n. In that case, the core pool + will have a size of n, but the 'allowCoreThreadTimeout' flag will be set to true. + If a queue-capacity is provided, then the lower bound of a range will map to the + core size and the upper bound will map to the max size. If this attribute is not + provided, the default core size will be 1, and the default max size will be + Integer.MAX_VALUE (i.e. unbounded). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="queue-capacity" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Queue capacity for the ThreadPoolTaskExecutor. If not specified, the default will + be Integer.MAX_VALUE (i.e. unbounded). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="keep-alive" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Keep-alive time in seconds. Inactive threads that have been created beyond the + core size will timeout after the specified number of seconds elapse. If the + executor has an unbounded queue capacity and a size range represented as 0-n, + then the core threads will also be configured to timeout when inactive. + Otherwise, core threads will not ever timeout. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="rejection-policy" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The RejectedExecutionHandler type. When a bounded queue cannot accept any + additional tasks, this determines the behavior. While the default is ABORT, + consider using CALLER_RUNS to throttle inbound tasks. In other words, by forcing + the caller to run the task itself, it will not be able to provide another task + until after it completes the task at hand. In the meantime, one or more tasks + may be removed from the queue. Alternatively, if it is not critical to run every + task, consider using DISCARD to drop the current task or DISCARD_OLDEST to drop + the task at the head of the queue. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="ABORT"/> + <xsd:enumeration value="CALLER_RUNS"/> + <xsd:enumeration value="DISCARD"/> + <xsd:enumeration value="DISCARD_OLDEST"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:element name="scheduled-tasks"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Top-level element that contains one or more task sub-elements to be + managed by a given TaskScheduler. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="scheduled" type="scheduledTaskType" minOccurs="1" maxOccurs="unbounded"/> + </xsd:sequence> + <xsd:attribute name="scheduler" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Reference to an instance of TaskScheduler to manage the provided tasks. If not specified, + the default value will be a wrapper for a single-threaded Executor. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref"> + <tool:expected-type type="org.springframework.scheduling.TaskScheduler"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + </xsd:element> + + <xsd:complexType name="scheduledTaskType"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Element defining a scheduled method-invoking task and its corresponding trigger. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:attribute name="cron" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + A cron-based trigger. See the org.springframework.scheduling.support.CronSequenceGenerator + JavaDoc for example patterns. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="fixed-delay" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + An interval-based trigger where the interval is measured from the completion time of the + previous task. The time unit value is measured in milliseconds. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="fixed-rate" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + An interval-based trigger where the interval is measured from the start time of the + previous task. The time unit value is measured in milliseconds. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="trigger" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + A reference to a bean that implements the Trigger interface. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="initial-delay" type="xsd:string" use="optional"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Number of milliseconds to delay before the first execution of a 'fixed-rate' or + 'fixed-delay' task. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="ref" type="xsd:string" use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Reference to an object that provides a method to be invoked. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation kind="ref" /> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="method" type="xsd:string" use="required"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of the method to be invoked. + ]]></xsd:documentation> + <xsd:appinfo> + <tool:annotation> + <tool:expected-method type-ref="@ref"/> + </tool:annotation> + </xsd:appinfo> + </xsd:annotation> + </xsd:attribute> + </xsd:complexType> + +</xsd:schema> diff --git a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-4.2.xsd b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-4.2.xsd new file mode 100644 index 000000000000..061d7c1bada0 --- /dev/null +++ b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-4.2.xsd @@ -0,0 +1,255 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> + +<xsd:schema xmlns="http://www.springframework.org/schema/lang" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:beans="http://www.springframework.org/schema/beans" + targetNamespace="http://www.springframework.org/schema/lang" + elementFormDefault="qualified" + attributeFormDefault="unqualified"> + + <xsd:annotation> + <xsd:documentation><![CDATA[ + Defines the elements used in the Spring Framework's dynamic language + support, which allows bean definitions that are backed by classes + written in a language other than Java. + ]]></xsd:documentation> + </xsd:annotation> + + <xsd:import namespace="http://www.springframework.org/schema/beans" schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"/> + <xsd:import namespace="http://www.springframework.org/schema/tool" schemaLocation="http://www.springframework.org/schema/tool/spring-tool-4.2.xsd"/> + + <xsd:element name="defaults"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Default settings for any scripted beans registered within this context. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:attributeGroup ref="defaultableAttributes"/> + </xsd:complexType> + </xsd:element> + + <xsd:element name="groovy"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + A Spring bean backed by a Groovy class definition. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="customizableScriptType"> + <xsd:attributeGroup ref="defaultableAttributes"/> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:element name="jruby"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + A Spring bean backed by a JRuby class definition. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="dynamicScriptType"> + <xsd:attributeGroup ref="vanillaScriptAttributes"/> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:element name="bsh"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + A Spring bean backed by a BeanShell script. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="dynamicScriptType"> + <xsd:attributeGroup ref="vanillaScriptAttributes"/> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <xsd:element name="std"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + A Spring bean backed by a standard JSR-223 based script. + Supports JavaScript, Groovy, JRuby and other JSR-223 compliant engines. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="dynamicScriptType"> + <xsd:attribute name="engine" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of the script engine (if not inferred from the file extension). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attributeGroup ref="vanillaScriptAttributes"/> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + + <!-- Script Types --> + <xsd:complexType name="simpleScriptType"> + <xsd:complexContent> + <xsd:extension base="beans:identifiedType"> + <xsd:sequence> + <xsd:element name="inline-script" minOccurs="0" maxOccurs="1"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The source code for the dynamic language-backed bean. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + <xsd:element name="property" type="beans:propertyType" minOccurs="0" maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Dynamic language-backed bean definitions can have zero or more properties. + Property elements correspond to JavaBean setter methods exposed + by the bean classes. Spring supports primitives, references to other + beans in the same or related factories, lists, maps and properties. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + <xsd:attribute name="script-source" type="xsd:string"> + <xsd:annotation> + <xsd:documentation source="java:org.springframework.core.io.Resource"><![CDATA[ + The resource containing the script for the dynamic language-backed bean. + + Examples might be '/WEB-INF/scripts/Anais.groovy', 'classpath:Nin.bsh', etc. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="name" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of this scripted bean as an alias or replacement for the id. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="scope" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The scope of this scripted bean: typically "singleton" (one shared instance, + which will be returned by all calls to getBean with the given id), or + "prototype" (independent instance resulting from each call to getBean). + Default is "singleton". + + Singletons are most commonly used, and are ideal for multi-threaded + service objects. Further scopes, such as "request" or "session", might + be supported by extended bean factories (e.g. in a web environment). + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="autowire" default="default"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The autowire mode for the scripted bean. + Analogous to the 'autowire' attribute on a standard bean definition. + ]]></xsd:documentation> + </xsd:annotation> + <xsd:simpleType> + <xsd:restriction base="xsd:NMTOKEN"> + <xsd:enumeration value="default"/> + <xsd:enumeration value="no"/> + <xsd:enumeration value="byName"/> + <xsd:enumeration value="byType"/> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + <xsd:attribute name="depends-on" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The names of the beans that this bean depends on being initialized. + The bean factory will guarantee that these beans get initialized + before this bean. + + Note that dependencies are normally expressed through bean properties. + This property should just be necessary for other kinds of dependencies + like statics (*ugh*) or database preparation on startup. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="init-method" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of an initialization method defined on the scripted bean. + Analogous to the 'init-method' attribute on a standard bean definition. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attribute name="destroy-method" type="xsd:string"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The name of a destruction method defined on the scripted bean. + Analogous to the 'destroy-method' attribute on a standard bean definition. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + + <xsd:complexType name="dynamicScriptType"> + <xsd:complexContent> + <xsd:extension base="simpleScriptType"> + <xsd:attribute name="script-interfaces"> + <xsd:annotation> + <xsd:documentation source="java:java.lang.Class"><![CDATA[ + The Java interfaces that the dynamic language-backed object is to expose; comma-delimited. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + + <xsd:complexType name="customizableScriptType"> + <xsd:complexContent> + <xsd:extension base="simpleScriptType"> + <xsd:attribute name="customizer-ref"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Reference to a GroovyObjectCustomizer or similar customizer bean. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + + <xsd:attributeGroup name="vanillaScriptAttributes"> + <xsd:attribute name="refresh-check-delay" type="xsd:long"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + The delay (in milliseconds) between checks for updated sources when + using the refreshable beans feature. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + </xsd:attributeGroup> + + <xsd:attributeGroup name="defaultableAttributes"> + <xsd:attribute name="proxy-target-class" type="xsd:boolean"> + <xsd:annotation> + <xsd:documentation><![CDATA[ + Flag to tell the bean factory that if this bean is proxied it should be done using the target class type, + not its interfaces. A refreshable script is normally proxied, so often this is useful in conjunction with + refresh-check-delay. Defaults to false requiring no additional library dependencies, but hiding behavior + in the bean that is not defined in an interface. + ]]></xsd:documentation> + </xsd:annotation> + </xsd:attribute> + <xsd:attributeGroup ref="vanillaScriptAttributes"></xsd:attributeGroup> + </xsd:attributeGroup> + +</xsd:schema> diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java index 21044dd9a5c7..1f5131a51c50 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,6 +90,35 @@ public void testStaticScript() throws Exception { assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); } + @Test + public void testStaticScriptUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContextWithJsr223.xml", getClass()); + + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")); + + Calculator calc = (Calculator) ctx.getBean("calculator"); + Messenger messenger = (Messenger) ctx.getBean("messenger"); + + assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(calc)); + assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); + + assertFalse("Scripted object should not be instance of Refreshable", calc instanceof Refreshable); + assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + + assertEquals(calc, calc); + assertEquals(messenger, messenger); + assertTrue(!messenger.equals(calc)); + assertTrue(messenger.hashCode() != calc.hashCode()); + assertTrue(!messenger.toString().equals(calc.toString())); + + String desiredMessage = "Hello World!"; + assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + + assertTrue(ctx.getBeansOfType(Calculator.class).values().contains(calc)); + assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + } + @Test public void testStaticPrototypeScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); @@ -109,6 +138,25 @@ public void testStaticPrototypeScript() throws Exception { assertEquals("Byebye World!", messenger2.getMessage()); } + @Test + public void testStaticPrototypeScriptUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContextWithJsr223.xml", getClass()); + ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); + ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); + + assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); + assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + + assertNotSame(messenger, messenger2); + assertSame(messenger.getClass(), messenger2.getClass()); + assertEquals("Hello World!", messenger.getMessage()); + assertEquals("Hello World!", messenger2.getMessage()); + messenger.setMessage("Bye World!"); + messenger2.setMessage("Byebye World!"); + assertEquals("Bye World!", messenger.getMessage()); + assertEquals("Byebye World!", messenger2.getMessage()); + } + @Test public void testStaticScriptWithInstance() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); @@ -123,6 +171,20 @@ public void testStaticScriptWithInstance() throws Exception { assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); } + @Test + public void testStaticScriptWithInstanceUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContextWithJsr223.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")); + Messenger messenger = (Messenger) ctx.getBean("messengerInstance"); + + assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); + assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + + String desiredMessage = "Hello World!"; + assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + } + @Test public void testStaticScriptWithInlineDefinedInstance() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); @@ -137,6 +199,20 @@ public void testStaticScriptWithInlineDefinedInstance() throws Exception { assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); } + @Test + public void testStaticScriptWithInlineDefinedInstanceUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContextWithJsr223.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstanceInline")); + Messenger messenger = (Messenger) ctx.getBean("messengerInstanceInline"); + + assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); + assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + + String desiredMessage = "Hello World!"; + assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + } + @Test public void testNonStaticScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyRefreshableContext.xml", getClass()); @@ -311,8 +387,6 @@ public void testGetScriptedObjectDoesChokeOnNullScriptSourceBeingPassedIn() thro } } - @Ignore - // see http://build.springframework.org/browse/SPR-TRUNKQUICK-908 @Test public void testResourceScriptFromTag() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass()); @@ -409,6 +483,49 @@ public void testAnonymousScriptDetected() throws Exception { assertEquals(4, beans.size()); } + @Test + public void testJsr223FromTag() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")); + Messenger messenger = (Messenger) ctx.getBean("messenger"); + assertFalse(AopUtils.isAopProxy(messenger)); + assertEquals("Hello World!", messenger.getMessage()); + } + + @Test + public void testJsr223FromTagWithInterface() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithInterface")); + Messenger messenger = (Messenger) ctx.getBean("messengerWithInterface"); + assertFalse(AopUtils.isAopProxy(messenger)); + } + + @Test + public void testRefreshableJsr223FromTag() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger")); + Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger"); + assertTrue(AopUtils.isAopProxy(messenger)); + assertTrue(messenger instanceof Refreshable); + assertEquals("Hello World!", messenger.getMessage()); + } + + @Test + public void testInlineJsr223FromTag() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessenger")); + Messenger messenger = (Messenger) ctx.getBean("inlineMessenger"); + assertFalse(AopUtils.isAopProxy(messenger)); + } + + @Test + public void testInlineJsr223FromTagWithInterface() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessengerWithInterface")); + Messenger messenger = (Messenger) ctx.getBean("inlineMessengerWithInterface"); + assertFalse(AopUtils.isAopProxy(messenger)); + } + /** * Tests the SPR-2098 bug whereby no more than 1 property element could be * passed to a scripted bean :( diff --git a/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java index 0c45266dbf82..95c6de6f4872 100644 --- a/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,6 +64,27 @@ public void testStaticScript() throws Exception { assertNotSame(messenger.hashCode(), calc.hashCode()); assertTrue(!messenger.toString().equals(calc.toString())); + assertEquals(3, calc.add(1, 2)); + String desiredMessage = "Hello World!"; + assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + } + + @Test + public void testStaticScriptUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContextWithJsr223.xml", getClass()); + Calculator calc = (Calculator) ctx.getBean("calculator"); + Messenger messenger = (Messenger) ctx.getBean("messenger"); + + assertFalse("Scripted object should not be instance of Refreshable", calc instanceof Refreshable); + assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + + assertEquals(calc, calc); + assertEquals(messenger, messenger); + assertTrue(!messenger.equals(calc)); + assertNotSame(messenger.hashCode(), calc.hashCode()); + assertTrue(!messenger.toString().equals(calc.toString())); + + assertEquals(3, calc.add(1, 2)); String desiredMessage = "Hello World!"; assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); } @@ -163,6 +184,15 @@ public void testResourceScriptFromTag() throws Exception { assertEquals(testBean, messengerByName.getTestBean()); } + @Test + public void testResourceScriptFromTagUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd-jsr223.xml", getClass()); + + Messenger messenger = (Messenger) ctx.getBean("messenger"); + assertEquals("Hello World!", messenger.getMessage()); + assertFalse(messenger instanceof Refreshable); + } + @Test public void testPrototypeScriptFromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd.xml", getClass()); @@ -185,6 +215,16 @@ public void testInlineScriptFromTag() throws Exception { Calculator calculator = (Calculator) ctx.getBean("calculator"); assertNotNull(calculator); assertFalse(calculator instanceof Refreshable); + assertEquals(3, calculator.add(1, 2)); + } + + @Test + public void testInlineScriptFromTagUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd-jsr223.xml", getClass()); + Calculator calculator = (Calculator) ctx.getBean("calculator"); + assertNotNull(calculator); + assertFalse(calculator instanceof Refreshable); + assertEquals(3, calculator.add(1, 2)); } @Test @@ -195,6 +235,15 @@ public void testRefreshableFromTag() throws Exception { assertTrue("Messenger should be Refreshable", messenger instanceof Refreshable); } + @Test + public void testRefreshableFromTagUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd-jsr223.xml", getClass()); + Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger"); + assertEquals("Hello World!", messenger.getMessage()); + assertTrue("Messenger should be Refreshable", messenger instanceof Refreshable); + } + + @Test public void testThatMultipleScriptInterfacesAreSupported() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("jruby-with-xsd.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("calculatingMessenger"); @@ -214,6 +263,15 @@ public void testWithComplexArg() throws Exception { assertEquals(1, printable.count); } + @Test + public void testWithComplexArgUsingJsr223() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContextWithJsr223.xml", getClass()); + Printer printer = (Printer) ctx.getBean("printer"); + CountingPrintable printable = new CountingPrintable(); + printer.print(printable); + assertEquals(1, printable.count); + } + @Test public void testWithPrimitiveArgsInReturnTypeAndParameters() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContextForPrimitives.xml", getClass()); diff --git a/spring-context/src/test/java/org/springframework/scripting/support/StandardScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/support/StandardScriptFactoryTests.java new file mode 100644 index 000000000000..fdd33ad84240 --- /dev/null +++ b/spring-context/src/test/java/org/springframework/scripting/support/StandardScriptFactoryTests.java @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.scripting.support; + +import java.util.Arrays; + +import org.junit.Test; + +import org.springframework.aop.support.AopUtils; +import org.springframework.aop.target.dynamic.Refreshable; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.scripting.Messenger; + +import static org.junit.Assert.*; + +/** + * {@link StandardScriptFactory} (lang:std) tests for JavaScript. + * + * @author Juergen Hoeller + * @since 4.2 + */ +public class StandardScriptFactoryTests { + + @Test + public void testJsr223FromTagWithInterface() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jsr223-with-xsd.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithInterface")); + Messenger messenger = (Messenger) ctx.getBean("messengerWithInterface"); + assertFalse(AopUtils.isAopProxy(messenger)); + assertEquals("Hello World!", messenger.getMessage()); + } + + @Test + public void testRefreshableJsr223FromTagWithInterface() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jsr223-with-xsd.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessengerWithInterface")); + Messenger messenger = (Messenger) ctx.getBean("refreshableMessengerWithInterface"); + assertTrue(AopUtils.isAopProxy(messenger)); + assertTrue(messenger instanceof Refreshable); + assertEquals("Hello World!", messenger.getMessage()); + } + + @Test + public void testInlineJsr223FromTagWithInterface() throws Exception { + ApplicationContext ctx = new ClassPathXmlApplicationContext("jsr223-with-xsd.xml", getClass()); + assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessengerWithInterface")); + Messenger messenger = (Messenger) ctx.getBean("inlineMessengerWithInterface"); + assertFalse(AopUtils.isAopProxy(messenger)); + assertEquals("Hello World!", messenger.getMessage()); + } + +} diff --git a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd-jsr223.xml b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd-jsr223.xml new file mode 100644 index 000000000000..5d7f2739900a --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd-jsr223.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:lang="http://www.springframework.org/schema/lang" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd + http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.2.xsd"> + + <lang:std id="messenger" script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy"> + <lang:property name="message" value="Hello World!"/> + </lang:std> + + <lang:std id="messengerWithInterface" script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy" + script-interfaces="org.springframework.scripting.Messenger"/> + + <lang:std id="refreshableMessenger" refresh-check-delay="5000" + script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy"> + <lang:property name="message" value="Hello World!"/> + </lang:std> + + <lang:std id="inlineMessenger" engine="Groovy"> + <lang:inline-script> + package org.springframework.scripting.groovy; + import org.springframework.scripting.Messenger + class GroovyMessenger implements Messenger { + def String message; + } + return new GroovyMessenger(); + </lang:inline-script> + </lang:std> + + <lang:std id="inlineMessengerWithInterface" engine="Groovy" script-interfaces="org.springframework.scripting.Messenger"> + <lang:inline-script> + package org.springframework.scripting.groovy; + import org.springframework.scripting.Messenger + class GroovyMessenger implements Messenger { + def String message; + } + return new GroovyMessenger(); + </lang:inline-script> + </lang:std> + +</beans> diff --git a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd-proxy-target-class.xml b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd-proxy-target-class.xml index 822ad89a0662..44a43339403a 100644 --- a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd-proxy-target-class.xml +++ b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd-proxy-target-class.xml @@ -3,12 +3,11 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd - http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd"> <lang:groovy id="refreshableMessenger" refresh-check-delay="5000" proxy-target-class="true" - script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy"> - <lang:property name="message" value="Hello World!" /> + script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy"> + <lang:property name="message" value="Hello World!"/> </lang:groovy> </beans> diff --git a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd.xml b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd.xml index 8de3522ab662..a573d6a2e093 100644 --- a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd.xml +++ b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovy-with-xsd.xml @@ -33,7 +33,7 @@ class GroovyCalculator implements Calculator { return x + y; } } - </lang:inline-script> + </lang:inline-script> </lang:groovy> <lang:groovy id="customizer"> diff --git a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovyContext.xml b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovyContext.xml index a159b1791e71..e9c674b9592b 100644 --- a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovyContext.xml +++ b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovyContext.xml @@ -10,8 +10,7 @@ <bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/> - <bean id="calculator" - class="org.springframework.scripting.groovy.GroovyScriptFactory"> + <bean id="calculator" class="org.springframework.scripting.groovy.GroovyScriptFactory"> <constructor-arg> <value>inline: package org.springframework.scripting.groovy; @@ -25,28 +24,24 @@ class GroovyCalculator implements Calculator { </constructor-arg> </bean> - <bean id="messenger" - class="org.springframework.scripting.groovy.GroovyScriptFactory"> + <bean id="messenger" class="org.springframework.scripting.groovy.GroovyScriptFactory"> <constructor-arg value="classpath:org/springframework/scripting/groovy/Messenger.groovy"/> <property name="message" value="Hello World!"/> </bean> - <bean id="messengerPrototype" - class="org.springframework.scripting.groovy.GroovyScriptFactory" + <bean id="messengerPrototype" class="org.springframework.scripting.groovy.GroovyScriptFactory" scope="prototype"> <constructor-arg value="classpath:org/springframework/scripting/groovy/Messenger.groovy"/> <property name="message" value="Hello World!"/> </bean> - <bean id="messengerInstance" - class="org.springframework.scripting.groovy.GroovyScriptFactory"> + <bean id="messengerInstance" class="org.springframework.scripting.groovy.GroovyScriptFactory"> <constructor-arg value="classpath:org/springframework/scripting/groovy/MessengerInstance.groovy"/> <property name="message" ref="myMessage"/> </bean> - <bean id="messengerInstanceInline" - class="org.springframework.scripting.groovy.GroovyScriptFactory"> - <constructor-arg> + <bean id="messengerInstanceInline" class="org.springframework.scripting.groovy.GroovyScriptFactory"> + <constructor-arg> <value>inline: package org.springframework.scripting.groovy; import org.springframework.scripting.Messenger diff --git a/spring-context/src/test/resources/org/springframework/scripting/groovy/groovyContextWithJsr223.xml b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovyContextWithJsr223.xml new file mode 100644 index 000000000000..c5f69cd7eaa7 --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/groovy/groovyContextWithJsr223.xml @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:lang="http://www.springframework.org/schema/lang" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd" + default-lazy-init="true"> + + <bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/> + + <bean id="calculator" class="org.springframework.scripting.support.StandardScriptFactory"> + <constructor-arg value="Groovy"/> + <constructor-arg> + <value>inline: +package org.springframework.scripting.groovy; +import org.springframework.scripting.Calculator +class GroovyCalculator implements Calculator { + int add(int x, int y) { + return x + y; + } +} + </value> + </constructor-arg> + </bean> + + <bean id="messenger" class="org.springframework.scripting.support.StandardScriptFactory"> + <constructor-arg value="classpath:org/springframework/scripting/groovy/Messenger.groovy"/> + <property name="message" value="Hello World!"/> + </bean> + + <bean id="messengerPrototype" class="org.springframework.scripting.support.StandardScriptFactory" + scope="prototype"> + <constructor-arg value="classpath:org/springframework/scripting/groovy/Messenger.groovy"/> + <property name="message" value="Hello World!"/> + </bean> + + <bean id="messengerInstance" class="org.springframework.scripting.support.StandardScriptFactory"> + <constructor-arg value="classpath:org/springframework/scripting/groovy/MessengerInstance.groovy"/> + <property name="message" ref="myMessage"/> + </bean> + + <bean id="messengerInstanceInline" class="org.springframework.scripting.support.StandardScriptFactory"> + <constructor-arg value="Groovy"/> + <constructor-arg> + <value>inline: +package org.springframework.scripting.groovy; +import org.springframework.scripting.Messenger +class GroovyMessenger implements Messenger { + def String message; +} +return new GroovyMessenger(); + </value> + </constructor-arg> + <property name="message" ref="myMessage"/> + </bean> + + <bean id="myMessage" class="java.lang.String"> + <constructor-arg value="Hello World!"/> + </bean> + +</beans> diff --git a/spring-context/src/test/resources/org/springframework/scripting/jruby/MessengerWithInstance.rb b/spring-context/src/test/resources/org/springframework/scripting/jruby/MessengerWithInstance.rb new file mode 100644 index 000000000000..3bdb75e3c9f6 --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/jruby/MessengerWithInstance.rb @@ -0,0 +1,25 @@ +require 'java' + +class RubyMessenger + include org.springframework.scripting.ConfigurableMessenger + + @@message = "Hello World!" + + def setMessage(message) + @@message = message + end + + def getMessage + @@message + end + + def setTestBean(testBean) + @@testBean = testBean + end + + def getTestBean + @@testBean + end +end + +RubyMessenger.new diff --git a/spring-context/src/test/resources/org/springframework/scripting/jruby/PrinterWithInstance.rb b/spring-context/src/test/resources/org/springframework/scripting/jruby/PrinterWithInstance.rb new file mode 100644 index 000000000000..58f8a7b5123d --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/jruby/PrinterWithInstance.rb @@ -0,0 +1,11 @@ +require 'java' + +class RubyPrinter + include org.springframework.scripting.jruby.Printer + + def print(obj) + puts obj.getContent + end +end + +RubyPrinter.new diff --git a/spring-context/src/test/resources/org/springframework/scripting/jruby/jruby-with-xsd-jsr223.xml b/spring-context/src/test/resources/org/springframework/scripting/jruby/jruby-with-xsd-jsr223.xml new file mode 100644 index 000000000000..c07e66dc45ac --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/jruby/jruby-with-xsd-jsr223.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:lang="http://www.springframework.org/schema/lang" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd + http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.2.xsd"> + + <lang:std id="messenger" + script-source="classpath:org/springframework/scripting/jruby/MessengerWithInstance.rb"> + </lang:std> + + <lang:std id="calculator" engine="jruby"> + <lang:inline-script> + require 'java' + + class RubyCalculator + include org.springframework.scripting.Calculator + + def add(x, y) + x + y + end + end + + RubyCalculator.new + </lang:inline-script> + </lang:std> + + <lang:std id="refreshableMessenger" + script-source="classpath:org/springframework/scripting/jruby/MessengerWithInstance.rb" + refresh-check-delay="5000"> + </lang:std> + +</beans> \ No newline at end of file diff --git a/spring-context/src/test/resources/org/springframework/scripting/jruby/jrubyContextWithJsr223.xml b/spring-context/src/test/resources/org/springframework/scripting/jruby/jrubyContextWithJsr223.xml new file mode 100644 index 000000000000..f552bc90c29c --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/jruby/jrubyContextWithJsr223.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> + +<beans> + + <bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/> + + <bean id="calculator" class="org.springframework.scripting.support.StandardScriptFactory"> + <constructor-arg value="jruby"/> + <constructor-arg> + <value>inline: +require 'java' + +class RubyCalculator + include org.springframework.scripting.Calculator + + def add(x, y) + x + y + end +end + +RubyCalculator.new + </value> + </constructor-arg> + <constructor-arg value="org.springframework.scripting.Calculator"/> + </bean> + + <bean id="messenger" class="org.springframework.scripting.support.StandardScriptFactory"> + <constructor-arg value="jruby"/> + <constructor-arg value="classpath:org/springframework/scripting/jruby/MessengerWithInstance.rb"/> + <constructor-arg value="org.springframework.scripting.Messenger"/> + </bean> + + <bean id="printer" class="org.springframework.scripting.support.StandardScriptFactory"> + <constructor-arg value="jruby"/> + <constructor-arg value="classpath:org/springframework/scripting/jruby/PrinterWithInstance.rb"/> + <constructor-arg value="org.springframework.scripting.jruby.Printer"/> + </bean> + +</beans> diff --git a/spring-context/src/test/resources/org/springframework/scripting/support/Messenger.js b/spring-context/src/test/resources/org/springframework/scripting/support/Messenger.js new file mode 100644 index 000000000000..5277c3c73aeb --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/support/Messenger.js @@ -0,0 +1 @@ +function getMessage() { return "Hello World!" } diff --git a/spring-context/src/test/resources/org/springframework/scripting/support/jsr223-with-xsd.xml b/spring-context/src/test/resources/org/springframework/scripting/support/jsr223-with-xsd.xml new file mode 100644 index 000000000000..b88c93bcabcc --- /dev/null +++ b/spring-context/src/test/resources/org/springframework/scripting/support/jsr223-with-xsd.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:lang="http://www.springframework.org/schema/lang" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd + http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.2.xsd"> + + <lang:std id="messengerWithInterface" script-source="classpath:org/springframework/scripting/support/Messenger.js" + script-interfaces="org.springframework.scripting.Messenger"/> + + <lang:std id="refreshableMessengerWithInterface" refresh-check-delay="5000" + script-source="classpath:org/springframework/scripting/support/Messenger.js" + script-interfaces="org.springframework.scripting.Messenger"> + </lang:std> + + <lang:std id="inlineMessengerWithInterface" engine="JavaScript" + script-interfaces="org.springframework.scripting.Messenger"> + <lang:inline-script> + function getMessage() { return "Hello World!" } + </lang:inline-script> + </lang:std> + +</beans>
744fa1046d5e930af976a313b02f427c4be6ac54
Delta Spike
add comment about ALv2 license of this special hibernate part.
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/data/impl/pom.xml b/deltaspike/modules/data/impl/pom.xml index 926d89cf4..bf063648c 100755 --- a/deltaspike/modules/data/impl/pom.xml +++ b/deltaspike/modules/data/impl/pom.xml @@ -75,6 +75,7 @@ </processors> </configuration> <dependencies> + <!-- this part of Hibernate is Apache License 2.0, thus O.K. for us. --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-jpamodelgen</artifactId>
deb17da4bbf1ddd29c88d7f0b39718c5c4473687
Mylyn Reviews
Hierarchical review scope - scope table is now a tree. - review section will be automatically collapsed if no scope is found. - refined descriptions and types for scope items
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java index e81f3b41..fd2459f7 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java @@ -74,7 +74,12 @@ public List<IReviewFile> getReviewFiles( @Override public String getDescription() { - return "patch"; + return "Patch "+attachment.getFileName(); + } + + @Override + public String getType(int count) { + return count ==1? "patch":"patches"; } } \ No newline at end of file diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java index 55ec2e6a..195f30a0 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java @@ -136,7 +136,13 @@ public String getType() { @Override public String getDescription() { - return "resource"; + return "Attachment "+attachment.getFileName(); } + @Override + public String getType(int count) { + return count==1?"resource":"resources"; + } + + } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java index 62aafced..87bf3993 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java @@ -23,5 +23,6 @@ public interface ReviewScopeItem { List<IReviewFile> getReviewFiles(NullProgressMonitor monitor)throws CoreException; String getDescription(); + String getType(int count); } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java index ba77e9cb..8299e9b4 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java @@ -13,7 +13,6 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; import org.eclipse.mylyn.reviews.tasks.core.Rating; @@ -46,16 +45,22 @@ public String getDescription() { } return description; } - + private static class Counter { + int counter; + ReviewScopeItem item; + public Counter(ReviewScopeItem item) { + this.item=item; + } + } private String convertScopeToDescription() { StringBuilder sb = new StringBuilder(); - Map<String, AtomicInteger> counts = new TreeMap<String, AtomicInteger>(); + Map<String, Counter> counts = new TreeMap<String, Counter>(); for (ReviewScopeItem item : scope.getItems()) { - String key = item.getDescription(); + String key = item.getType(1); if (!counts.containsKey(key)) { - counts.put(key, new AtomicInteger()); + counts.put(key, new Counter(item)); } - counts.get(key).incrementAndGet(); + counts.get(key).counter++; } boolean isFirstElement = true; for (String type : counts.keySet()) { @@ -65,10 +70,10 @@ private String convertScopeToDescription() { sb.append(", "); } - int count = counts.get(type).get(); + int count = counts.get(type).counter; sb.append(count); sb.append(" "); - sb.append(type); + sb.append(counts.get(type).item.getType(count)); } return sb.toString(); } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java index 26607f5e..bc582f6e 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java @@ -38,7 +38,7 @@ public String getDescription() { StringBuilder sb = new StringBuilder(); if(patchCount >0) { sb.append(patchCount); - sb.append(" Patch"); + sb.append(" patch"); if(patchCount>1) { sb.append("es"); } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java index b99ea49f..657ed0a5 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java @@ -120,9 +120,8 @@ public ReviewScope getReviewScope() throws CoreException { return scope; } - /*package*/ ITreeNode getReviewResults(IProgressMonitor monitor) throws CoreException { - return ReviewsUtil - .getReviewSubTasksFor(getModel().getTask(), + /* package */ITreeNode getReviewResults(IProgressMonitor monitor) throws CoreException { + return ReviewsUtil.getReviewSubTasksFor(getModel().getTask(), TasksUi.getTaskDataManager(), ReviewsUiPlugin.getMapper(), monitor); diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java index 38861453..2881a1ed 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java @@ -13,7 +13,6 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; import java.util.List; import org.eclipse.compare.CompareConfiguration; @@ -27,7 +26,6 @@ import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.resource.CompositeImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; -import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; @@ -36,9 +34,10 @@ import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.TableLayout; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.TreeNode; +import org.eclipse.jface.viewers.TreeNodeContentProvider; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.mylyn.reviews.tasks.core.IReviewFile; import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; @@ -74,10 +73,11 @@ */ public class ReviewTaskEditorPart extends AbstractReviewTaskEditorPart { public static final String ID_PART_REVIEW = "org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPart"; //$NON-NLS-1$ - private TableViewer fileList; + private TreeViewer fileList; private Composite composite; private ITaskProperties taskProperties; private ComboViewer ratingList; + private Section section; public ReviewTaskEditorPart() { setPartName("Review "); @@ -86,53 +86,58 @@ public ReviewTaskEditorPart() { @Override public void createControl(Composite parent, FormToolkit toolkit) { - Section section = createSection(parent, toolkit, true); + section = createSection(parent, toolkit, true); GridLayout gl = new GridLayout(1, false); gl.marginBottom = 16; GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.horizontalSpan = 4; section.setLayout(gl); section.setLayoutData(gd); +setSection(toolkit, section); composite = toolkit.createComposite(section); composite.setLayout(new GridLayout(1, true)); - fileList = new TableViewer(composite); + fileList = new TreeViewer(composite); fileList.getControl().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true)); - TableViewerColumn column = new TableViewerColumn(fileList, SWT.LEFT); - column.getColumn().setText("Filename"); - column.getColumn().setWidth(100); - column.getColumn().setResizable(true); - - TableLayout tableLayout = new TableLayout(); - tableLayout.addColumnData(new ColumnWeightData(100, true)); - fileList.getTable().setLayout(tableLayout); + createColumn(fileList, "Group", 100); + createColumn(fileList, "Filename", 100); + fileList.getTree().setLinesVisible(true); + fileList.getTree().setHeaderVisible(true); fileList.setLabelProvider(new TableLabelProvider() { - private final int COLUMN_FILE = 0; + private final int COLUMN_GROUP = 0; + private final int COLUMN_FILE = 1; @Override - public String getColumnText(Object element, int columnIndex) { - if (columnIndex == COLUMN_FILE) { + public String getColumnText(Object node, int columnIndex) { + Object element = ((TreeNode) node).getValue(); + switch (columnIndex) { + case COLUMN_GROUP: + if (element instanceof ReviewScopeItem) { + return ((ReviewScopeItem) element).getDescription(); + } + break; + case COLUMN_FILE: if (element instanceof IReviewFile) { - IReviewFile file = ((IReviewFile) element); - - return file.getFileName(); + return ((IReviewFile) element).getFileName(); } + break; } return null; } @Override - public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == COLUMN_FILE) { - ISharedImages sharedImages = PlatformUI.getWorkbench() - .getSharedImages(); - if (element instanceof IReviewFile) { + public Image getColumnImage(Object node, int columnIndex) { + Object element = ((TreeNode) node).getValue(); + if (element instanceof IReviewFile) { + if (columnIndex == COLUMN_FILE) { + ISharedImages sharedImages = PlatformUI.getWorkbench() + .getSharedImages(); IReviewFile file = ((IReviewFile) element); if (file.isNewFile()) { return new NewFile().createImage(); @@ -140,24 +145,25 @@ public Image getColumnImage(Object element, int columnIndex) { if (!file.canReview()) { return new MissingFile().createImage(); } - } - return sharedImages.getImage(ISharedImages.IMG_OBJ_FILE); + return sharedImages + .getImage(ISharedImages.IMG_OBJ_FILE); + } } return null; } }); - fileList.setContentProvider(ArrayContentProvider.getInstance()); + fileList.setContentProvider(new TreeNodeContentProvider()); fileList.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection sel = (IStructuredSelection) selection; - if (sel.getFirstElement() instanceof IReviewFile) { - final IReviewFile file = ((IReviewFile) sel - .getFirstElement()); + Object value = ((TreeNode)sel.getFirstElement()).getValue(); + if (value instanceof IReviewFile) { + final IReviewFile file = (IReviewFile) value; if (file.canReview()) { CompareConfiguration configuration = new CompareConfiguration(); configuration.setLeftEditable(false); @@ -173,7 +179,8 @@ public void doubleClick(DoubleClickEvent event) { .setProperty( CompareConfiguration.USE_OUTLINE_VIEW, true); - CompareUI.openCompareEditor(new CompareEditorInput(configuration) { + CompareUI.openCompareEditor(new CompareEditorInput( + configuration) { @Override protected Object prepareInput( @@ -207,39 +214,62 @@ protected Object prepareInput( setSection(toolkit, section); SafeRunner.run(new ISafeRunnable() { - + @Override public void run() throws Exception { - final List<IReviewFile> files = getInput(); + + ReviewScope reviewScope = getReviewScope(); + if (reviewScope == null) { + section.setExpanded(false); + return; + } + List<ReviewScopeItem> files = reviewScope.getItems(); + + final TreeNode[] rootNodes = new TreeNode[files.size()]; + int index = 0; + for (ReviewScopeItem item : files) { + TreeNode node = new TreeNode(item); + List<IReviewFile> reviewFiles = item + .getReviewFiles(new NullProgressMonitor()); + TreeNode[] children = new TreeNode[reviewFiles.size()]; + for (int i = 0; i < reviewFiles.size(); i++) { + children[i] = new TreeNode(reviewFiles.get(i)); + children[i].setParent(node); + } + node.setChildren(children); + + rootNodes[index++] = node; + } + Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { - fileList.setInput(files); + fileList.setInput(rootNodes); + if(rootNodes.length==0) { + section.setExpanded(false); + } } }); - + } - + @Override public void handleException(Throwable exception) { exception.printStackTrace(); } - private List<IReviewFile> getInput() throws CoreException { - List<IReviewFile> files = new ArrayList<IReviewFile>(); - ReviewScope reviewScope = getReviewScope(); - if (reviewScope != null) { - // FIXME parse all scopes - for (ReviewScopeItem scopeItem : reviewScope.getItems()) { - files.addAll(scopeItem - .getReviewFiles(new NullProgressMonitor())); - } - } - return files; - } }); } + private TreeViewerColumn createColumn(TreeViewer tree, String title, + int width) { + TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT); + column.getColumn().setText(title); + column.getColumn().setWidth(width); + column.getColumn().setResizable(true); + return column; + } + private void createResultFields(Composite composite, FormToolkit toolkit) { Composite resultComposite = toolkit.createComposite(composite); toolkit.paintBordersFor(resultComposite); @@ -368,7 +398,6 @@ private ReviewResult getCurrentResult() { return res; } - private static class MissingFile extends CompositeImageDescriptor { ISharedImages sharedImages = PlatformUI.getWorkbench() .getSharedImages();
e1ab934e5d80c32b63db7569f76b12375fe2a6f7
hbase
HBASE-798 Provide Client API to explicitly lock- and unlock rows (Jonathan Gray via Jim Kellerman)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@685391 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index becddd4e9cfb..216aac8c4fb9 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -32,6 +32,8 @@ Release 0.3.0 - Unreleased NEW FEATURES HBASE-787 Postgresql to HBase table replication example (Tim Sell via Stack) + HBASE-798 Provide Client API to explicitly lock and unlock rows (Jonathan + Gray via Jim Kellerman) OPTIMIZATIONS diff --git a/src/java/org/apache/hadoop/hbase/HMerge.java b/src/java/org/apache/hadoop/hbase/HMerge.java index f43b35e1fc5b..f87b6c7d5778 100644 --- a/src/java/org/apache/hadoop/hbase/HMerge.java +++ b/src/java/org/apache/hadoop/hbase/HMerge.java @@ -373,7 +373,7 @@ protected void updateMeta(final byte [] oldRegion1, b.delete(COL_STARTCODE); b.delete(COL_SPLITA); b.delete(COL_SPLITB); - root.batchUpdate(b); + root.batchUpdate(b,null); if(LOG.isDebugEnabled()) { LOG.debug("updated columns in row: " + regionsToDelete[r]); @@ -383,7 +383,7 @@ protected void updateMeta(final byte [] oldRegion1, newInfo.setOffline(true); BatchUpdate b = new BatchUpdate(newRegion.getRegionName()); b.put(COL_REGIONINFO, Writables.getBytes(newInfo)); - root.batchUpdate(b); + root.batchUpdate(b,null); if(LOG.isDebugEnabled()) { LOG.debug("updated columns in row: " + newRegion.getRegionName()); } diff --git a/src/java/org/apache/hadoop/hbase/client/HTable.java b/src/java/org/apache/hadoop/hbase/client/HTable.java index 6d086e91fc4e..676da7b6b350 100644 --- a/src/java/org/apache/hadoop/hbase/client/HTable.java +++ b/src/java/org/apache/hadoop/hbase/client/HTable.java @@ -639,12 +639,33 @@ public RowResult getRow(final String row, final String [] columns, */ public RowResult getRow(final byte [] row, final byte [][] columns, final long ts) + throws IOException { + return getRow(row,columns,ts,null); + } + + /** + * Get selected columns for the specified row at a specified timestamp + * using existing row lock. + * + * @param row row key + * @param columns Array of column names and families you want to retrieve. + * @param ts timestamp + * @param rl row lock + * @return RowResult is empty if row does not exist. + * @throws IOException + */ + public RowResult getRow(final byte [] row, final byte [][] columns, + final long ts, final RowLock rl) throws IOException { return connection.getRegionServerWithRetries( new ServerCallable<RowResult>(connection, tableName, row) { public RowResult call() throws IOException { + long lockId = -1L; + if(rl != null) { + lockId = rl.getLockId(); + } return server.getRow(location.getRegionInfo().getRegionName(), row, - columns, ts); + columns, ts, lockId); } } ); @@ -1103,16 +1124,36 @@ public void deleteAll(final String row, final String column, final long ts) * @throws IOException */ public void deleteAll(final byte [] row, final byte [] column, final long ts) + throws IOException { + deleteAll(row,column,ts,null); + } + + /** + * Delete all cells that match the passed row and column and whose + * timestamp is equal-to or older than the passed timestamp, using an + * existing row lock. + * @param row Row to update + * @param column name of column whose value is to be deleted + * @param ts Delete all cells of the same timestamp or older. + * @param rl Existing row lock + * @throws IOException + */ + public void deleteAll(final byte [] row, final byte [] column, final long ts, + final RowLock rl) throws IOException { connection.getRegionServerWithRetries( new ServerCallable<Boolean>(connection, tableName, row) { public Boolean call() throws IOException { + long lockId = -1L; + if(rl != null) { + lockId = rl.getLockId(); + } if (column != null) { this.server.deleteAll(location.getRegionInfo().getRegionName(), - row, column, ts); + row, column, ts, lockId); } else { this.server.deleteAll(location.getRegionInfo().getRegionName(), - row, ts); + row, ts, lockId); } return null; } @@ -1160,12 +1201,32 @@ public void deleteFamily(final String row, final String family, */ public void deleteFamily(final byte [] row, final byte [] family, final long timestamp) + throws IOException { + deleteFamily(row,family,timestamp,null); + } + + /** + * Delete all cells for a row with matching column family with timestamps + * less than or equal to <i>timestamp</i>, using existing row lock. + * + * @param row The row to operate on + * @param family The column family to match + * @param timestamp Timestamp to match + * @param rl Existing row lock + * @throws IOException + */ + public void deleteFamily(final byte [] row, final byte [] family, + final long timestamp, final RowLock rl) throws IOException { connection.getRegionServerWithRetries( new ServerCallable<Boolean>(connection, tableName, row) { public Boolean call() throws IOException { + long lockId = -1L; + if(rl != null) { + lockId = rl.getLockId(); + } server.deleteFamily(location.getRegionInfo().getRegionName(), row, - family, timestamp); + family, timestamp, lockId); return null; } } @@ -1178,12 +1239,28 @@ public Boolean call() throws IOException { * @throws IOException */ public synchronized void commit(final BatchUpdate batchUpdate) + throws IOException { + commit(batchUpdate,null); + } + + /** + * Commit a BatchUpdate to the table using existing row lock. + * @param batchUpdate + * @param rl Existing row lock + * @throws IOException + */ + public synchronized void commit(final BatchUpdate batchUpdate, + final RowLock rl) throws IOException { connection.getRegionServerWithRetries( new ServerCallable<Boolean>(connection, tableName, batchUpdate.getRow()) { public Boolean call() throws IOException { + long lockId = -1L; + if(rl != null) { + lockId = rl.getLockId(); + } server.batchUpdate(location.getRegionInfo().getRegionName(), - batchUpdate); + batchUpdate, lockId); return null; } } @@ -1198,7 +1275,45 @@ public Boolean call() throws IOException { public synchronized void commit(final List<BatchUpdate> batchUpdates) throws IOException { for (BatchUpdate batchUpdate : batchUpdates) - commit(batchUpdate); + commit(batchUpdate,null); + } + + /** + * Obtain a row lock + * @param row The row to lock + * @return rowLock RowLock containing row and lock id + * @throws IOException + */ + public RowLock lockRow(final byte [] row) + throws IOException { + return connection.getRegionServerWithRetries( + new ServerCallable<RowLock>(connection, tableName, row) { + public RowLock call() throws IOException { + long lockId = + server.lockRow(location.getRegionInfo().getRegionName(), row); + RowLock rowLock = new RowLock(row,lockId); + return rowLock; + } + } + ); + } + + /** + * Release a row lock + * @param rl The row lock to release + * @throws IOException + */ + public void unlockRow(final RowLock rl) + throws IOException { + connection.getRegionServerWithRetries( + new ServerCallable<Boolean>(connection, tableName, rl.getRow()) { + public Boolean call() throws IOException { + server.unlockRow(location.getRegionInfo().getRegionName(), + rl.getLockId()); + return null; + } + } + ); } /** diff --git a/src/java/org/apache/hadoop/hbase/ipc/HRegionInterface.java b/src/java/org/apache/hadoop/hbase/ipc/HRegionInterface.java index 0aed6af99111..46c6afc3d65e 100644 --- a/src/java/org/apache/hadoop/hbase/ipc/HRegionInterface.java +++ b/src/java/org/apache/hadoop/hbase/ipc/HRegionInterface.java @@ -111,11 +111,12 @@ public RowResult getClosestRowBefore(final byte [] regionName, * * @param regionName region name * @param row row key + * @param lockId lock id * @return map of values * @throws IOException */ public RowResult getRow(final byte [] regionName, final byte [] row, - final byte[][] columns, final long ts) + final byte[][] columns, final long ts, final long lockId) throws IOException; /** @@ -123,9 +124,11 @@ public RowResult getRow(final byte [] regionName, final byte [] row, * * @param regionName name of the region to update * @param b BatchUpdate + * @param lockId lock id * @throws IOException */ - public void batchUpdate(final byte [] regionName, final BatchUpdate b) + public void batchUpdate(final byte [] regionName, final BatchUpdate b, + final long lockId) throws IOException; /** @@ -136,10 +139,11 @@ public void batchUpdate(final byte [] regionName, final BatchUpdate b) * @param row row key * @param column column key * @param timestamp Delete all entries that have this timestamp or older + * @param lockId lock id * @throws IOException */ public void deleteAll(byte [] regionName, byte [] row, byte [] column, - long timestamp) + long timestamp, long lockId) throws IOException; /** @@ -149,9 +153,11 @@ public void deleteAll(byte [] regionName, byte [] row, byte [] column, * @param regionName region name * @param row row key * @param timestamp Delete all entries that have this timestamp or older + * @param lockId lock id * @throws IOException */ - public void deleteAll(byte [] regionName, byte [] row, long timestamp) + public void deleteAll(byte [] regionName, byte [] row, long timestamp, + long lockId) throws IOException; /** @@ -162,9 +168,10 @@ public void deleteAll(byte [] regionName, byte [] row, long timestamp) * @param row The row to operate on * @param family The column family to match * @param timestamp Timestamp to match + * @param lockId lock id */ public void deleteFamily(byte [] regionName, byte [] row, byte [] family, - long timestamp) + long timestamp, long lockId) throws IOException; @@ -207,4 +214,24 @@ public long openScanner(final byte [] regionName, final byte [][] columns, * @throws IOException */ public void close(long scannerId) throws IOException; + + /** + * Opens a remote row lock. + * + * @param regionName name of region + * @param row row to lock + * @return lockId lock identifier + * @throws IOException + */ + public long lockRow(final byte [] regionName, final byte [] row) + throws IOException; + + /** + * Releases a remote row lock. + * + * @param lockId the lock id returned by lockRow + * @throws IOException + */ + public void unlockRow(final byte [] regionName, final long lockId) + throws IOException; } \ No newline at end of file diff --git a/src/java/org/apache/hadoop/hbase/master/BaseScanner.java b/src/java/org/apache/hadoop/hbase/master/BaseScanner.java index 22d900369a8c..5f17ea2b62f8 100644 --- a/src/java/org/apache/hadoop/hbase/master/BaseScanner.java +++ b/src/java/org/apache/hadoop/hbase/master/BaseScanner.java @@ -332,7 +332,7 @@ public boolean accept(Path path) { BatchUpdate b = new BatchUpdate(parent); b.delete(splitColumn); - srvr.batchUpdate(metaRegionName, b); + srvr.batchUpdate(metaRegionName, b, -1L); return result; } diff --git a/src/java/org/apache/hadoop/hbase/master/ChangeTableState.java b/src/java/org/apache/hadoop/hbase/master/ChangeTableState.java index 48670a56caf6..4bea278d7945 100644 --- a/src/java/org/apache/hadoop/hbase/master/ChangeTableState.java +++ b/src/java/org/apache/hadoop/hbase/master/ChangeTableState.java @@ -91,7 +91,7 @@ protected void postProcessMeta(MetaRegion m, HRegionInterface server) updateRegionInfo(b, i); b.delete(COL_SERVER); b.delete(COL_STARTCODE); - server.batchUpdate(m.getRegionName(), b); + server.batchUpdate(m.getRegionName(), b, -1L); if (LOG.isDebugEnabled()) { LOG.debug("updated columns in row: " + i.getRegionNameAsString()); } diff --git a/src/java/org/apache/hadoop/hbase/master/ColumnOperation.java b/src/java/org/apache/hadoop/hbase/master/ColumnOperation.java index dae8405949ee..94d31ad46918 100644 --- a/src/java/org/apache/hadoop/hbase/master/ColumnOperation.java +++ b/src/java/org/apache/hadoop/hbase/master/ColumnOperation.java @@ -52,7 +52,7 @@ protected void updateRegionInfo(HRegionInterface server, byte [] regionName, throws IOException { BatchUpdate b = new BatchUpdate(i.getRegionName()); b.put(COL_REGIONINFO, Writables.getBytes(i)); - server.batchUpdate(regionName, b); + server.batchUpdate(regionName, b, -1L); if (LOG.isDebugEnabled()) { LOG.debug("updated columns in row: " + i.getRegionNameAsString()); } diff --git a/src/java/org/apache/hadoop/hbase/master/ModifyTableMeta.java b/src/java/org/apache/hadoop/hbase/master/ModifyTableMeta.java index c7a15999d49a..ee1b915fdafb 100644 --- a/src/java/org/apache/hadoop/hbase/master/ModifyTableMeta.java +++ b/src/java/org/apache/hadoop/hbase/master/ModifyTableMeta.java @@ -52,7 +52,7 @@ protected void updateRegionInfo(HRegionInterface server, byte [] regionName, throws IOException { BatchUpdate b = new BatchUpdate(i.getRegionName()); b.put(COL_REGIONINFO, Writables.getBytes(i)); - server.batchUpdate(regionName, b); + server.batchUpdate(regionName, b, -1L); LOG.debug("updated HTableDescriptor for region " + i.getRegionNameAsString()); } diff --git a/src/java/org/apache/hadoop/hbase/master/ProcessRegionOpen.java b/src/java/org/apache/hadoop/hbase/master/ProcessRegionOpen.java index aecced363058..022c03dc7291 100644 --- a/src/java/org/apache/hadoop/hbase/master/ProcessRegionOpen.java +++ b/src/java/org/apache/hadoop/hbase/master/ProcessRegionOpen.java @@ -83,7 +83,7 @@ public Boolean call() throws IOException { BatchUpdate b = new BatchUpdate(regionInfo.getRegionName()); b.put(COL_SERVER, Bytes.toBytes(serverAddress.toString())); b.put(COL_STARTCODE, startCode); - server.batchUpdate(metaRegionName, b); + server.batchUpdate(metaRegionName, b, -1L); if (!this.historian.isOnline()) { // This is safest place to do the onlining of the historian in // the master. When we get to here, we know there is a .META. diff --git a/src/java/org/apache/hadoop/hbase/master/RegionManager.java b/src/java/org/apache/hadoop/hbase/master/RegionManager.java index be76b8b33f63..919d4d33ffe6 100644 --- a/src/java/org/apache/hadoop/hbase/master/RegionManager.java +++ b/src/java/org/apache/hadoop/hbase/master/RegionManager.java @@ -560,7 +560,7 @@ public void createRegion(HRegionInfo newRegion, HRegionInterface server, byte [] regionName = region.getRegionName(); BatchUpdate b = new BatchUpdate(regionName); b.put(COL_REGIONINFO, Writables.getBytes(info)); - server.batchUpdate(metaRegionName, b); + server.batchUpdate(metaRegionName, b, -1L); // 4. Close the new region to flush it to disk. Close its log file too. region.close(); diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java index 3363317f4a37..a15a7bc68f15 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java @@ -1,4 +1,4 @@ -/** + /** * Copyright 2007 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one @@ -1170,7 +1170,7 @@ public Cell[] get(byte [] row, byte [] column, long timestamp, * @throws IOException */ public Map<byte [], Cell> getFull(final byte [] row, - final Set<byte []> columns, final long ts) + final Set<byte []> columns, final long ts, final Integer lockid) throws IOException { // Check columns passed if (columns != null) { @@ -1179,7 +1179,7 @@ public Cell[] get(byte [] row, byte [] column, long timestamp, } } HStoreKey key = new HStoreKey(row, ts); - Integer lid = obtainRowLock(row); + Integer lid = getLock(lockid,row); HashSet<HStore> storeSet = new HashSet<HStore>(); try { TreeMap<byte [], Cell> result = @@ -1215,7 +1215,7 @@ public Cell[] get(byte [] row, byte [] column, long timestamp, return result; } finally { - releaseRowLock(lid); + if(lockid == null) releaseRowLock(lid); } } @@ -1347,7 +1347,7 @@ public InternalScanner getScanner(byte[][] cols, byte [] firstRow, * @param b * @throws IOException */ - public void batchUpdate(BatchUpdate b) + public void batchUpdate(BatchUpdate b, Integer lockid) throws IOException { checkReadOnly(); @@ -1363,7 +1363,8 @@ public void batchUpdate(BatchUpdate b) // See HRegionServer#RegionListener for how the expire on HRegionServer // invokes a HRegion#abort. byte [] row = b.getRow(); - Integer lid = obtainRowLock(row); + // If we did not pass an existing row lock, obtain a new one + Integer lid = getLock(lockid,row); long commitTime = (b.getTimestamp() == LATEST_TIMESTAMP) ? System.currentTimeMillis() : b.getTimestamp(); try { @@ -1408,7 +1409,7 @@ public void batchUpdate(BatchUpdate b) this.targetColumns.remove(Long.valueOf(lid)); throw e; } finally { - releaseRowLock(lid); + if(lockid == null) releaseRowLock(lid); } } @@ -1458,17 +1459,19 @@ private synchronized void doBlocking() { * @param row * @param column * @param ts Delete all entries that have this timestamp or older + * @param lockid Row lock * @throws IOException */ - public void deleteAll(final byte [] row, final byte [] column, final long ts) + public void deleteAll(final byte [] row, final byte [] column, final long ts, + final Integer lockid) throws IOException { checkColumn(column); checkReadOnly(); - Integer lid = obtainRowLock(row); + Integer lid = getLock(lockid,row); try { deleteMultiple(row, column, ts, ALL_VERSIONS); } finally { - releaseRowLock(lid); + if(lockid == null) releaseRowLock(lid); } } @@ -1476,12 +1479,14 @@ public void deleteAll(final byte [] row, final byte [] column, final long ts) * Delete all cells of the same age as the passed timestamp or older. * @param row * @param ts Delete all entries that have this timestamp or older + * @param lockid Row lock * @throws IOException */ - public void deleteAll(final byte [] row, final long ts) + public void deleteAll(final byte [] row, final long ts, + final Integer lockid) throws IOException { checkReadOnly(); - Integer lid = obtainRowLock(row); + Integer lid = getLock(lockid,row); try { for (HStore store : stores.values()){ List<HStoreKey> keys = store.getKeys(new HStoreKey(row, ts), @@ -1493,7 +1498,7 @@ public void deleteAll(final byte [] row, final long ts) update(edits); } } finally { - releaseRowLock(lid); + if(lockid == null) releaseRowLock(lid); } } @@ -1504,12 +1509,14 @@ public void deleteAll(final byte [] row, final long ts) * @param row The row to operate on * @param family The column family to match * @param timestamp Timestamp to match + * @param lockid Row lock * @throws IOException */ - public void deleteFamily(byte [] row, byte [] family, long timestamp) + public void deleteFamily(byte [] row, byte [] family, long timestamp, + final Integer lockid) throws IOException{ checkReadOnly(); - Integer lid = obtainRowLock(row); + Integer lid = getLock(lockid,row); try { // find the HStore for the column family HStore store = getStore(family); @@ -1522,7 +1529,7 @@ public void deleteFamily(byte [] row, byte [] family, long timestamp) } update(edits); } finally { - releaseRowLock(lid); + if(lockid == null) releaseRowLock(lid); } } @@ -1552,7 +1559,7 @@ private void deleteMultiple(final byte [] row, final byte [] column, update(edits); } } - + /** * @throws IOException Throws exception if region is in read-only mode. */ @@ -1778,6 +1785,41 @@ void releaseRowLock(final Integer lockid) { } } + /** + * See if row is currently locked. + * @param lockid + * @return boolean + */ + private boolean isRowLocked(final Integer lockid) { + synchronized (locksToRows) { + if(locksToRows.containsKey(lockid)) { + return true; + } else { + return false; + } + } + } + + /** + * Returns existing row lock if found, otherwise + * obtains a new row lock and returns it. + * @param lockid + * @return lockid + */ + private Integer getLock(Integer lockid, byte [] row) + throws IOException { + Integer lid = null; + if(lockid == null) { + lid = obtainRowLock(row); + } else { + if(!isRowLocked(lockid)) { + throw new IOException("Invalid row lock"); + } + lid = lockid; + } + return lid; + } + private void waitOnRowLocks() { synchronized (locksToRows) { while (this.locksToRows.size() > 0) { @@ -2134,7 +2176,8 @@ public static void addRegionToMETA(HRegion meta, HRegion r) public static void removeRegionFromMETA(final HRegionInterface srvr, final byte [] metaRegionName, final byte [] regionName) throws IOException { - srvr.deleteAll(metaRegionName, regionName, HConstants.LATEST_TIMESTAMP); + srvr.deleteAll(metaRegionName, regionName, HConstants.LATEST_TIMESTAMP, + (long)-1L); } /** @@ -2155,7 +2198,7 @@ public static void offlineRegionInMETA(final HRegionInterface srvr, b.delete(COL_STARTCODE); // If carrying splits, they'll be in place when we show up on new // server. - srvr.batchUpdate(metaRegionName, b); + srvr.batchUpdate(metaRegionName, b, (long)-1L); } /** diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java index 85be1d8be543..9024e5987ea4 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java @@ -69,6 +69,7 @@ import org.apache.hadoop.hbase.RegionHistorian; import org.apache.hadoop.hbase.RemoteExceptionHandler; import org.apache.hadoop.hbase.UnknownScannerException; +import org.apache.hadoop.hbase.UnknownRowLockException; import org.apache.hadoop.hbase.Leases.LeaseStillHeldException; import org.apache.hadoop.hbase.filter.RowFilterInterface; import org.apache.hadoop.hbase.io.BatchOperation; @@ -1048,7 +1049,7 @@ public Cell[] get(final byte [] regionName, final byte [] row, /** {@inheritDoc} */ public RowResult getRow(final byte [] regionName, final byte [] row, - final byte [][] columns, final long ts) + final byte [][] columns, final long ts, final long lockId) throws IOException { checkOpen(); requestCount.incrementAndGet(); @@ -1061,7 +1062,8 @@ public RowResult getRow(final byte [] regionName, final byte [] row, } HRegion region = getRegion(regionName); - Map<byte [], Cell> map = region.getFull(row, columnSet, ts); + Map<byte [], Cell> map = region.getFull(row, columnSet, ts, + getLockFromId(lockId)); HbaseMapWritable<byte [], Cell> result = new HbaseMapWritable<byte [], Cell>(); result.putAll(map); @@ -1126,7 +1128,7 @@ public RowResult next(final long scannerId) throws IOException { } /** {@inheritDoc} */ - public void batchUpdate(final byte [] regionName, BatchUpdate b) + public void batchUpdate(final byte [] regionName, BatchUpdate b, long lockId) throws IOException { checkOpen(); this.requestCount.incrementAndGet(); @@ -1134,7 +1136,7 @@ public void batchUpdate(final byte [] regionName, BatchUpdate b) validateValuesLength(b, region); try { cacheFlusher.reclaimMemcacheMemory(); - region.batchUpdate(b); + region.batchUpdate(b, getLockFromId(lockId)); } catch (OutOfMemoryError error) { abort(); LOG.fatal("Ran out of memory", error); @@ -1239,7 +1241,7 @@ public void close(final long scannerId) throws IOException { } Map<String, InternalScanner> scanners = - Collections.synchronizedMap(new HashMap<String, InternalScanner>()); + new ConcurrentHashMap<String, InternalScanner>(); /** * Instantiated as a scanner lease. @@ -1275,26 +1277,157 @@ public void leaseExpired() { /** {@inheritDoc} */ public void deleteAll(final byte [] regionName, final byte [] row, - final byte [] column, final long timestamp) + final byte [] column, final long timestamp, final long lockId) throws IOException { HRegion region = getRegion(regionName); - region.deleteAll(row, column, timestamp); + region.deleteAll(row, column, timestamp, getLockFromId(lockId)); } /** {@inheritDoc} */ public void deleteAll(final byte [] regionName, final byte [] row, - final long timestamp) + final long timestamp, final long lockId) throws IOException { HRegion region = getRegion(regionName); - region.deleteAll(row, timestamp); + region.deleteAll(row, timestamp, getLockFromId(lockId)); } /** {@inheritDoc} */ public void deleteFamily(byte [] regionName, byte [] row, byte [] family, - long timestamp) throws IOException{ - getRegion(regionName).deleteFamily(row, family, timestamp); + long timestamp, final long lockId) + throws IOException{ + getRegion(regionName).deleteFamily(row, family, timestamp, + getLockFromId(lockId)); } + /** {@inheritDoc} */ + public long lockRow(byte [] regionName, byte [] row) + throws IOException { + checkOpen(); + NullPointerException npe = null; + if(regionName == null) { + npe = new NullPointerException("regionName is null"); + } else if(row == null) { + npe = new NullPointerException("row to lock is null"); + } + if(npe != null) { + IOException io = new IOException("Invalid arguments to lockRow"); + io.initCause(npe); + throw io; + } + requestCount.incrementAndGet(); + try { + HRegion region = getRegion(regionName); + Integer r = region.obtainRowLock(row); + long lockId = addRowLock(r,region); + LOG.debug("Row lock " + lockId + " explicitly acquired by client"); + return lockId; + } catch (IOException e) { + LOG.error("Error obtaining row lock (fsOk: " + this.fsOk + ")", + RemoteExceptionHandler.checkIOException(e)); + checkFileSystem(); + throw e; + } + } + + protected long addRowLock(Integer r, HRegion region) throws LeaseStillHeldException { + long lockId = -1L; + lockId = rand.nextLong(); + String lockName = String.valueOf(lockId); + synchronized(rowlocks) { + rowlocks.put(lockName, r); + } + this.leases. + createLease(lockName, new RowLockListener(lockName, region)); + return lockId; + } + + /** + * Method to get the Integer lock identifier used internally + * from the long lock identifier used by the client. + * @param lockId long row lock identifier from client + * @return intId Integer row lock used internally in HRegion + * @throws IOException Thrown if this is not a valid client lock id. + */ + private Integer getLockFromId(long lockId) + throws IOException { + if(lockId == -1L) { + return null; + } + String lockName = String.valueOf(lockId); + Integer rl = null; + synchronized(rowlocks) { + rl = rowlocks.get(lockName); + } + if(rl == null) { + throw new IOException("Invalid row lock"); + } + this.leases.renewLease(lockName); + return rl; + } + + /** {@inheritDoc} */ + public void unlockRow(byte [] regionName, long lockId) + throws IOException { + checkOpen(); + NullPointerException npe = null; + if(regionName == null) { + npe = new NullPointerException("regionName is null"); + } else if(lockId == -1L) { + npe = new NullPointerException("lockId is null"); + } + if(npe != null) { + IOException io = new IOException("Invalid arguments to unlockRow"); + io.initCause(npe); + throw io; + } + requestCount.incrementAndGet(); + try { + HRegion region = getRegion(regionName); + String lockName = String.valueOf(lockId); + Integer r = null; + synchronized(rowlocks) { + r = rowlocks.remove(lockName); + } + if(r == null) { + throw new UnknownRowLockException(lockName); + } + region.releaseRowLock(r); + this.leases.cancelLease(lockName); + LOG.debug("Row lock " + lockId + " has been explicitly released by client"); + } catch (IOException e) { + checkFileSystem(); + throw e; + } + } + + Map<String, Integer> rowlocks = + new ConcurrentHashMap<String, Integer>(); + + /** + * Instantiated as a row lock lease. + * If the lease times out, the row lock is released + */ + private class RowLockListener implements LeaseListener { + private final String lockName; + private final HRegion region; + + RowLockListener(final String lockName, final HRegion region) { + this.lockName = lockName; + this.region = region; + } + + /** {@inheritDoc} */ + public void leaseExpired() { + LOG.info("Row Lock " + this.lockName + " lease expired"); + Integer r = null; + synchronized(rowlocks) { + r = rowlocks.remove(this.lockName); + } + if(r != null) { + region.releaseRowLock(r); + } + } + } /** * @return Info on this server. diff --git a/src/java/org/apache/hadoop/hbase/util/Merge.java b/src/java/org/apache/hadoop/hbase/util/Merge.java index 541fae3ab093..6598770af10a 100644 --- a/src/java/org/apache/hadoop/hbase/util/Merge.java +++ b/src/java/org/apache/hadoop/hbase/util/Merge.java @@ -308,7 +308,7 @@ private void removeRegionFromMeta(HRegion meta, HRegionInfo regioninfo) if (LOG.isDebugEnabled()) { LOG.debug("Removing region: " + regioninfo + " from " + meta); } - meta.deleteAll(regioninfo.getRegionName(), System.currentTimeMillis()); + meta.deleteAll(regioninfo.getRegionName(), System.currentTimeMillis(), null); } /* diff --git a/src/java/org/apache/hadoop/hbase/util/MetaUtils.java b/src/java/org/apache/hadoop/hbase/util/MetaUtils.java index c6f8458c465d..b84454447d40 100644 --- a/src/java/org/apache/hadoop/hbase/util/MetaUtils.java +++ b/src/java/org/apache/hadoop/hbase/util/MetaUtils.java @@ -407,7 +407,7 @@ public void updateMETARegionInfo(HRegion r, final HRegionInfo hri) } BatchUpdate b = new BatchUpdate(hri.getRegionName()); b.put(HConstants.COL_REGIONINFO, Writables.getBytes(hri)); - r.batchUpdate(b); + r.batchUpdate(b, null); if (LOG.isDebugEnabled()) { HRegionInfo h = Writables.getHRegionInfoOrNull( r.get(hri.getRegionName(), HConstants.COL_REGIONINFO).getValue()); diff --git a/src/java/org/apache/hadoop/hbase/util/migration/v5/HRegion.java b/src/java/org/apache/hadoop/hbase/util/migration/v5/HRegion.java index 7efbd7097a2a..d117fca0470b 100644 --- a/src/java/org/apache/hadoop/hbase/util/migration/v5/HRegion.java +++ b/src/java/org/apache/hadoop/hbase/util/migration/v5/HRegion.java @@ -2050,7 +2050,8 @@ public static void addRegionToMETA(HRegion meta, HRegion r) public static void removeRegionFromMETA(final HRegionInterface srvr, final byte [] metaRegionName, final byte [] regionName) throws IOException { - srvr.deleteAll(metaRegionName, regionName, HConstants.LATEST_TIMESTAMP); + srvr.deleteAll(metaRegionName, regionName, HConstants.LATEST_TIMESTAMP, + -1L); } /** @@ -2071,7 +2072,7 @@ public static void offlineRegionInMETA(final HRegionInterface srvr, b.delete(COL_STARTCODE); // If carrying splits, they'll be in place when we show up on new // server. - srvr.batchUpdate(metaRegionName, b); + srvr.batchUpdate(metaRegionName, b, -1L); } /**
6c9b915e74ffa69f81095dbbecc2d3c998cb2766
tapiji
Cleans up plugin configuration files. Cleans up build properties.
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.core/META-INF/MANIFEST.MF b/org.eclipse.babel.core/META-INF/MANIFEST.MF index 41079089..ddee7a2a 100644 --- a/org.eclipse.babel.core/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.core/META-INF/MANIFEST.MF @@ -3,17 +3,21 @@ Bundle-ManifestVersion: 2 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, - org.eclipse.babel.core.message, - org.eclipse.babel.core.message.checks, +Export-Package: org.eclipse.babel.core.configuration;uses:="org.eclipse.babel.core.message.resource.ser", + org.eclipse.babel.core.message; + 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, - org.eclipse.babel.core.message.resource, - org.eclipse.babel.core.message.resource.ser, - org.eclipse.babel.core.message.strategy, - org.eclipse.babel.core.message.tree, - org.eclipse.babel.core.message.tree.visitor, - org.eclipse.babel.core.util + 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.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.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, diff --git a/org.eclipse.babel.core/build.properties b/org.eclipse.babel.core/build.properties index 90a39e82..7291c352 100644 --- a/org.eclipse.babel.core/build.properties +++ b/org.eclipse.babel.core/build.properties @@ -4,6 +4,5 @@ bin.includes = META-INF/,\ .,\ bin/,\ plugin.xml -src.includes = META-INF/,\ - bin/,\ +src.includes = bin/,\ src/ diff --git a/org.eclipse.babel.editor.nls/build.properties b/org.eclipse.babel.editor.nls/build.properties index 1bf484f6..812de0d6 100644 --- a/org.eclipse.babel.editor.nls/build.properties +++ b/org.eclipse.babel.editor.nls/build.properties @@ -1,6 +1,5 @@ bin.includes = META-INF/,\ nl/,\ plugin_fr.properties -src.includes = META-INF/,\ - nl/,\ +src.includes = nl/,\ plugin_fr.properties diff --git a/org.eclipse.babel.editor/build.properties b/org.eclipse.babel.editor/build.properties index bd0f34d8..a4728f6b 100644 --- a/org.eclipse.babel.editor/build.properties +++ b/org.eclipse.babel.editor/build.properties @@ -7,10 +7,7 @@ bin.includes = META-INF/,\ bin/,\ plugin.properties,\ messages.properties -src.includes = META-INF/,\ - bin/,\ +src.includes = bin/,\ icons/,\ messages.properties,\ - plugin.properties,\ - plugin.xml,\ src/ diff --git a/org.eclipselabs.tapiji.tools.core/build.properties b/org.eclipselabs.tapiji.tools.core/build.properties index f163057e..e8dfe316 100644 --- a/org.eclipselabs.tapiji.tools.core/build.properties +++ b/org.eclipselabs.tapiji.tools.core/build.properties @@ -1,9 +1,4 @@ -source.. = src/,\ - schema/,\ - META-INF/,\ - icons/,\ - bin/ -output.. = bin/ +source.. = src/ bin.includes = plugin.xml,\ META-INF/,\ .,\ @@ -31,11 +26,9 @@ src.includes = src/,\ about.ini,\ about.mappings,\ about.properties,\ - META-INF/,\ TapiJI.png,\ Splash.bmp,\ TapiJI.gif,\ - plugin.xml,\ epl-v10.html jars.compile.order = .,\ resourcebundle.jar diff --git a/org.eclipselabs.tapiji.tools.java/build.properties b/org.eclipselabs.tapiji.tools.java/build.properties index 1fcd8783..5435750f 100644 --- a/org.eclipselabs.tapiji.tools.java/build.properties +++ b/org.eclipselabs.tapiji.tools.java/build.properties @@ -5,6 +5,4 @@ bin.includes = META-INF/,\ plugin.xml,\ epl-v10.html src.includes = src/,\ - plugin.xml,\ - epl-v10.html,\ - META-INF/ + epl-v10.html diff --git a/org.eclipselabs.tapiji.tools.jsf/build.properties b/org.eclipselabs.tapiji.tools.jsf/build.properties index 1fcd8783..5435750f 100644 --- a/org.eclipselabs.tapiji.tools.jsf/build.properties +++ b/org.eclipselabs.tapiji.tools.jsf/build.properties @@ -5,6 +5,4 @@ bin.includes = META-INF/,\ plugin.xml,\ epl-v10.html src.includes = src/,\ - plugin.xml,\ - epl-v10.html,\ - META-INF/ + epl-v10.html diff --git a/org.eclipselabs.tapiji.tools.rbmanager/build.properties b/org.eclipselabs.tapiji.tools.rbmanager/build.properties index f84becc0..f176c838 100644 --- a/org.eclipselabs.tapiji.tools.rbmanager/build.properties +++ b/org.eclipselabs.tapiji.tools.rbmanager/build.properties @@ -7,6 +7,4 @@ bin.includes = META-INF/,\ icons/ src.includes = icons/,\ src/,\ - plugin.xml,\ - bin/,\ - META-INF/ + bin/ \ No newline at end of file diff --git a/org.eclipselabs.tapiji.translator.rbe/build.properties b/org.eclipselabs.tapiji.translator.rbe/build.properties index 21cf96f9..90262f14 100644 --- a/org.eclipselabs.tapiji.translator.rbe/build.properties +++ b/org.eclipselabs.tapiji.translator.rbe/build.properties @@ -3,6 +3,5 @@ output.. = bin/ bin.includes = META-INF/,\ .,\ src/ -src.includes = META-INF/,\ - bin/,\ +src.includes = bin/,\ src/ diff --git a/org.eclipselabs.tapiji.translator/build.properties b/org.eclipselabs.tapiji.translator/build.properties index 40daa89e..bb724c0e 100644 --- a/org.eclipselabs.tapiji.translator/build.properties +++ b/org.eclipselabs.tapiji.translator/build.properties @@ -10,6 +10,5 @@ src.includes = splash.bmp,\ icons/,\ bin/,\ src/,\ - META-INF/,\ epl-v10.html
733faeffbd68719ac837d1aab954f4287573ca85
orientdb
fixes -1980: permissions follow role's- inheritance--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java index 06300fcae35..be24ed4209b 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java @@ -132,6 +132,13 @@ public boolean isAllowed(final Set<OIdentifiable> iAllowAll, final Set<OIdentifi // CHECK AGAINST SPECIFIC _ALLOW OPERATION if (iAllowOperation != null && iAllowOperation.contains(r.getDocument().getIdentity())) return true; + // CHECK inherited permissions from parent roles, fixes #1980: Record Level Security: permissions don't follow role's inheritance + ORole parentRole = r.getParentRole(); + while (parentRole!=null){ + if (iAllowAll.contains(parentRole.getDocument().getIdentity())) return true; + if (iAllowOperation != null && iAllowOperation.contains(parentRole.getDocument().getIdentity())) return true; + parentRole=parentRole.getParentRole(); + } } return false; }