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
61a020d24c35911fd8ac7b9a1e135bf930ddce45
Vala
glib-2.0: add binding for GLib.HashTable.lookup_extended Fixes bug 617358.
a
https://github.com/GNOME/vala/
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi index ffd6c4fbca..7ff63b0942 100644 --- a/vapi/glib-2.0.vapi +++ b/vapi/glib-2.0.vapi @@ -3375,6 +3375,7 @@ namespace GLib { public void insert (owned K key, owned V value); public void replace (owned K key, owned V value); public unowned V lookup (K key); + public bool lookup_extended (K lookup_key, out unowned K orig_key, out unowned V value); public bool remove (K key); public void remove_all (); public List<unowned K> get_keys ();
6f14330db96d599a0ec4a880786320d1b493c861
intellij-community
IDEA-35738 Cannot drag around label with empty- text--
c
https://github.com/JetBrains/intellij-community
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java b/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java index 7a0803b70538a..69ef61ec61211 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java @@ -186,12 +186,56 @@ private static void deleteEmptyGridCells(final RadContainer parent, final GridCo } } + private static final int EMPTY_COMPONENT_SIZE = 5; + + private static Component getDeepestEmptyComponentAt(JComponent parent, Point location) { + int size = parent.getComponentCount(); + + for (int i = 0; i < size; i++) { + Component child = parent.getComponent(i); + + if (child.isShowing()) { + if (child.getWidth() < EMPTY_COMPONENT_SIZE || child.getHeight() < EMPTY_COMPONENT_SIZE) { + Point childLocation = child.getLocationOnScreen(); + Rectangle bounds = new Rectangle(); + + bounds.x = childLocation.x; + bounds.y = childLocation.y; + bounds.width = child.getWidth(); + bounds.height = child.getHeight(); + bounds.grow(child.getWidth() < EMPTY_COMPONENT_SIZE ? EMPTY_COMPONENT_SIZE : 0, + child.getHeight() < EMPTY_COMPONENT_SIZE ? EMPTY_COMPONENT_SIZE : 0); + + if (bounds.contains(location)) { + return child; + } + } + + if (child instanceof JComponent) { + Component result = getDeepestEmptyComponentAt((JComponent)child, location); + + if (result != null) { + return result; + } + } + } + } + + return null; + } + /** * @param x in editor pane coordinates * @param y in editor pane coordinates */ public static RadComponent getRadComponentAt(final RadRootContainer rootContainer, final int x, final int y){ - Component c = SwingUtilities.getDeepestComponentAt(rootContainer.getDelegee(), x, y); + Point location = new Point(x, y); + SwingUtilities.convertPointToScreen(location, rootContainer.getDelegee()); + Component c = getDeepestEmptyComponentAt(rootContainer.getDelegee(), location); + + if (c == null) { + c = SwingUtilities.getDeepestComponentAt(rootContainer.getDelegee(), x, y); + } RadComponent result = null; @@ -310,9 +354,9 @@ public static ArrayList<RadComponent> getAllSelectedComponents(@NotNull final Gu final ArrayList<RadComponent> result = new ArrayList<RadComponent>(); iterate( editor.getRootContainer(), - new ComponentVisitor<RadComponent>(){ + new ComponentVisitor<RadComponent>() { public boolean visit(final RadComponent component) { - if(component.isSelected()){ + if (component.isSelected()) { result.add(component); } return true; @@ -793,26 +837,28 @@ public static void iterateStringDescriptors(final IComponent component, iterate(component, new ComponentVisitor<IComponent>() { public boolean visit(final IComponent component) { - for(IProperty prop: component.getModifiedProperties()) { + for (IProperty prop : component.getModifiedProperties()) { Object value = prop.getPropertyValue(component); if (value instanceof StringDescriptor) { - if (!visitor.visit(component, (StringDescriptor) value)) { + if (!visitor.visit(component, (StringDescriptor)value)) { return false; } } } if (component.getParentContainer() instanceof ITabbedPane) { - StringDescriptor tabTitle = ((ITabbedPane) component.getParentContainer()).getTabProperty(component, ITabbedPane.TAB_TITLE_PROPERTY); + StringDescriptor tabTitle = + ((ITabbedPane)component.getParentContainer()).getTabProperty(component, ITabbedPane.TAB_TITLE_PROPERTY); if (tabTitle != null && !visitor.visit(component, tabTitle)) { return false; } - StringDescriptor tabToolTip = ((ITabbedPane) component.getParentContainer()).getTabProperty(component, ITabbedPane.TAB_TOOLTIP_PROPERTY); + StringDescriptor tabToolTip = + ((ITabbedPane)component.getParentContainer()).getTabProperty(component, ITabbedPane.TAB_TOOLTIP_PROPERTY); if (tabToolTip != null && !visitor.visit(component, tabToolTip)) { return false; } } if (component instanceof IContainer) { - final StringDescriptor borderTitle = ((IContainer) component).getBorderTitle(); + final StringDescriptor borderTitle = ((IContainer)component).getBorderTitle(); if (borderTitle != null && !visitor.visit(component, borderTitle)) { return false; }
9ccbb766bd98a4958a38ddc840e00b7dfa6230d6
hbase
HBASE-8033 Break TestRestoreSnapshotFromClient- into TestRestoreSnapshotFromClient and TestCloneSnapshotFromClient (Ted Yu)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1454186 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hbase
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestCloneSnapshotFromClient.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestCloneSnapshotFromClient.java new file mode 100644 index 000000000000..1449865262a8 --- /dev/null +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestCloneSnapshotFromClient.java @@ -0,0 +1,269 @@ +/** + * 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.hbase.client; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hbase.HBaseTestingUtility; +import org.apache.hadoop.hbase.HColumnDescriptor; +import org.apache.hadoop.hbase.HConstants; +import org.apache.hadoop.hbase.HTableDescriptor; +import org.apache.hadoop.hbase.LargeTests; +import org.apache.hadoop.hbase.exceptions.SnapshotDoesNotExistException; +import org.apache.hadoop.hbase.master.MasterFileSystem; +import org.apache.hadoop.hbase.master.snapshot.SnapshotManager; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.MD5Hash; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +/** + * Test clone snapshots from the client + */ +@Category(LargeTests.class) +public class TestCloneSnapshotFromClient { + final Log LOG = LogFactory.getLog(getClass()); + + private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); + + private final byte[] FAMILY = Bytes.toBytes("cf"); + + private byte[] emptySnapshot; + private byte[] snapshotName0; + private byte[] snapshotName1; + private byte[] snapshotName2; + private int snapshot0Rows; + private int snapshot1Rows; + private byte[] tableName; + private HBaseAdmin admin; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + TEST_UTIL.getConfiguration().setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true); + TEST_UTIL.getConfiguration().setBoolean("hbase.online.schema.update.enable", true); + TEST_UTIL.getConfiguration().setInt("hbase.hstore.compactionThreshold", 10); + TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100); + TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250); + TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6); + TEST_UTIL.getConfiguration().setBoolean( + "hbase.master.enabletable.roundrobin", true); + TEST_UTIL.startMiniCluster(3); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + TEST_UTIL.shutdownMiniCluster(); + } + + /** + * Initialize the tests with a table filled with some data + * and two snapshots (snapshotName0, snapshotName1) of different states. + * The tableName, snapshotNames and the number of rows in the snapshot are initialized. + */ + @Before + public void setup() throws Exception { + this.admin = TEST_UTIL.getHBaseAdmin(); + + long tid = System.currentTimeMillis(); + tableName = Bytes.toBytes("testtb-" + tid); + emptySnapshot = Bytes.toBytes("emptySnaptb-" + tid); + snapshotName0 = Bytes.toBytes("snaptb0-" + tid); + snapshotName1 = Bytes.toBytes("snaptb1-" + tid); + snapshotName2 = Bytes.toBytes("snaptb2-" + tid); + + // create Table and disable it + createTable(tableName, FAMILY); + admin.disableTable(tableName); + + // take an empty snapshot + admin.snapshot(emptySnapshot, tableName); + + HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName); + try { + // enable table and insert data + admin.enableTable(tableName); + loadData(table, 500, FAMILY); + snapshot0Rows = TEST_UTIL.countRows(table); + admin.disableTable(tableName); + + // take a snapshot + admin.snapshot(snapshotName0, tableName); + + // enable table and insert more data + admin.enableTable(tableName); + loadData(table, 500, FAMILY); + snapshot1Rows = TEST_UTIL.countRows(table); + admin.disableTable(tableName); + + // take a snapshot of the updated table + admin.snapshot(snapshotName1, tableName); + + // re-enable table + admin.enableTable(tableName); + } finally { + table.close(); + } + } + + @After + public void tearDown() throws Exception { + if (admin.tableExists(tableName)) { + TEST_UTIL.deleteTable(tableName); + } + admin.deleteSnapshot(snapshotName0); + admin.deleteSnapshot(snapshotName1); + + // Ensure the archiver to be empty + MasterFileSystem mfs = TEST_UTIL.getMiniHBaseCluster().getMaster().getMasterFileSystem(); + mfs.getFileSystem().delete( + new Path(mfs.getRootDir(), HConstants.HFILE_ARCHIVE_DIRECTORY), true); + } + + @Test(expected=SnapshotDoesNotExistException.class) + public void testCloneNonExistentSnapshot() throws IOException, InterruptedException { + String snapshotName = "random-snapshot-" + System.currentTimeMillis(); + String tableName = "random-table-" + System.currentTimeMillis(); + admin.cloneSnapshot(snapshotName, tableName); + } + + @Test + public void testCloneSnapshot() throws IOException, InterruptedException { + byte[] clonedTableName = Bytes.toBytes("clonedtb-" + System.currentTimeMillis()); + testCloneSnapshot(clonedTableName, snapshotName0, snapshot0Rows); + testCloneSnapshot(clonedTableName, snapshotName1, snapshot1Rows); + testCloneSnapshot(clonedTableName, emptySnapshot, 0); + } + + private void testCloneSnapshot(final byte[] tableName, final byte[] snapshotName, + int snapshotRows) throws IOException, InterruptedException { + // create a new table from snapshot + admin.cloneSnapshot(snapshotName, tableName); + verifyRowCount(tableName, snapshotRows); + + admin.disableTable(tableName); + admin.deleteTable(tableName); + } + + /** + * Verify that tables created from the snapshot are still alive after source table deletion. + */ + @Test + public void testCloneLinksAfterDelete() throws IOException, InterruptedException { + // Clone a table from the first snapshot + byte[] clonedTableName = Bytes.toBytes("clonedtb1-" + System.currentTimeMillis()); + admin.cloneSnapshot(snapshotName0, clonedTableName); + verifyRowCount(clonedTableName, snapshot0Rows); + + // Take a snapshot of this cloned table. + admin.disableTable(clonedTableName); + admin.snapshot(snapshotName2, clonedTableName); + + // Clone the snapshot of the cloned table + byte[] clonedTableName2 = Bytes.toBytes("clonedtb2-" + System.currentTimeMillis()); + admin.cloneSnapshot(snapshotName2, clonedTableName2); + verifyRowCount(clonedTableName2, snapshot0Rows); + admin.disableTable(clonedTableName2); + + // Remove the original table + admin.disableTable(tableName); + admin.deleteTable(tableName); + waitCleanerRun(); + + // Verify the first cloned table + admin.enableTable(clonedTableName); + verifyRowCount(clonedTableName, snapshot0Rows); + + // Verify the second cloned table + admin.enableTable(clonedTableName2); + verifyRowCount(clonedTableName2, snapshot0Rows); + admin.disableTable(clonedTableName2); + + // Delete the first cloned table + admin.disableTable(clonedTableName); + admin.deleteTable(clonedTableName); + waitCleanerRun(); + + // Verify the second cloned table + admin.enableTable(clonedTableName2); + verifyRowCount(clonedTableName2, snapshot0Rows); + + // Clone a new table from cloned + byte[] clonedTableName3 = Bytes.toBytes("clonedtb3-" + System.currentTimeMillis()); + admin.cloneSnapshot(snapshotName2, clonedTableName3); + verifyRowCount(clonedTableName3, snapshot0Rows); + + // Delete the cloned tables + admin.disableTable(clonedTableName2); + admin.deleteTable(clonedTableName2); + admin.disableTable(clonedTableName3); + admin.deleteTable(clonedTableName3); + admin.deleteSnapshot(snapshotName2); + } + + // ========================================================================== + // Helpers + // ========================================================================== + private void createTable(final byte[] tableName, final byte[]... families) throws IOException { + HTableDescriptor htd = new HTableDescriptor(tableName); + for (byte[] family: families) { + HColumnDescriptor hcd = new HColumnDescriptor(family); + htd.addFamily(hcd); + } + byte[][] splitKeys = new byte[16][]; + byte[] hex = Bytes.toBytes("0123456789abcdef"); + for (int i = 0; i < 16; ++i) { + splitKeys[i] = new byte[] { hex[i] }; + } + admin.createTable(htd, splitKeys); + } + + public void loadData(final HTable table, int rows, byte[]... families) throws IOException { + byte[] qualifier = Bytes.toBytes("q"); + table.setAutoFlush(false); + while (rows-- > 0) { + byte[] value = Bytes.add(Bytes.toBytes(System.currentTimeMillis()), Bytes.toBytes(rows)); + byte[] key = Bytes.toBytes(MD5Hash.getMD5AsHex(value)); + Put put = new Put(key); + put.setWriteToWAL(false); + for (byte[] family: families) { + put.add(family, qualifier, value); + } + table.put(put); + } + table.flushCommits(); + } + + private void waitCleanerRun() throws InterruptedException { + TEST_UTIL.getMiniHBaseCluster().getMaster().getHFileCleaner().choreForTesting(); + } + + private void verifyRowCount(final byte[] tableName, long expectedRows) throws IOException { + HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName); + assertEquals(expectedRows, TEST_UTIL.countRows(table)); + table.close(); + } +} diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java index ab1ecd8ec07f..0cb764aeee26 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java @@ -17,9 +17,7 @@ */ package org.apache.hadoop.hbase.client; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; @@ -30,22 +28,25 @@ import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseTestingUtility; +import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; -import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.LargeTests; +import org.apache.hadoop.hbase.exceptions.NoSuchColumnFamilyException; import org.apache.hadoop.hbase.master.MasterFileSystem; import org.apache.hadoop.hbase.master.snapshot.SnapshotManager; -import org.apache.hadoop.hbase.exceptions.NoSuchColumnFamilyException; -import org.apache.hadoop.hbase.exceptions.SnapshotDoesNotExistException; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.hbase.util.MD5Hash; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.junit.experimental.categories.Category; /** - * Test clone/restore snapshots from the client + * Test restore snapshots from the client */ @Category(LargeTests.class) public class TestRestoreSnapshotFromClient { @@ -225,31 +226,6 @@ public void testRestoreSchemaChange() throws IOException { table.close(); } - @Test(expected=SnapshotDoesNotExistException.class) - public void testCloneNonExistentSnapshot() throws IOException, InterruptedException { - String snapshotName = "random-snapshot-" + System.currentTimeMillis(); - String tableName = "random-table-" + System.currentTimeMillis(); - admin.cloneSnapshot(snapshotName, tableName); - } - - @Test - public void testCloneSnapshot() throws IOException, InterruptedException { - byte[] clonedTableName = Bytes.toBytes("clonedtb-" + System.currentTimeMillis()); - testCloneSnapshot(clonedTableName, snapshotName0, snapshot0Rows); - testCloneSnapshot(clonedTableName, snapshotName1, snapshot1Rows); - testCloneSnapshot(clonedTableName, emptySnapshot, 0); - } - - private void testCloneSnapshot(final byte[] tableName, final byte[] snapshotName, - int snapshotRows) throws IOException, InterruptedException { - // create a new table from snapshot - admin.cloneSnapshot(snapshotName, tableName); - verifyRowCount(tableName, snapshotRows); - - admin.disableTable(tableName); - admin.deleteTable(tableName); - } - @Test public void testRestoreSnapshotOfCloned() throws IOException, InterruptedException { byte[] clonedTableName = Bytes.toBytes("clonedtb-" + System.currentTimeMillis()); @@ -266,62 +242,6 @@ public void testRestoreSnapshotOfCloned() throws IOException, InterruptedExcepti admin.deleteTable(clonedTableName); } - /** - * Verify that tables created from the snapshot are still alive after source table deletion. - */ - @Test - public void testCloneLinksAfterDelete() throws IOException, InterruptedException { - // Clone a table from the first snapshot - byte[] clonedTableName = Bytes.toBytes("clonedtb1-" + System.currentTimeMillis()); - admin.cloneSnapshot(snapshotName0, clonedTableName); - verifyRowCount(clonedTableName, snapshot0Rows); - - // Take a snapshot of this cloned table. - admin.disableTable(clonedTableName); - admin.snapshot(snapshotName2, clonedTableName); - - // Clone the snapshot of the cloned table - byte[] clonedTableName2 = Bytes.toBytes("clonedtb2-" + System.currentTimeMillis()); - admin.cloneSnapshot(snapshotName2, clonedTableName2); - verifyRowCount(clonedTableName2, snapshot0Rows); - admin.disableTable(clonedTableName2); - - // Remove the original table - admin.disableTable(tableName); - admin.deleteTable(tableName); - waitCleanerRun(); - - // Verify the first cloned table - admin.enableTable(clonedTableName); - verifyRowCount(clonedTableName, snapshot0Rows); - - // Verify the second cloned table - admin.enableTable(clonedTableName2); - verifyRowCount(clonedTableName2, snapshot0Rows); - admin.disableTable(clonedTableName2); - - // Delete the first cloned table - admin.disableTable(clonedTableName); - admin.deleteTable(clonedTableName); - waitCleanerRun(); - - // Verify the second cloned table - admin.enableTable(clonedTableName2); - verifyRowCount(clonedTableName2, snapshot0Rows); - - // Clone a new table from cloned - byte[] clonedTableName3 = Bytes.toBytes("clonedtb3-" + System.currentTimeMillis()); - admin.cloneSnapshot(snapshotName2, clonedTableName3); - verifyRowCount(clonedTableName3, snapshot0Rows); - - // Delete the cloned tables - admin.disableTable(clonedTableName2); - admin.deleteTable(clonedTableName2); - admin.disableTable(clonedTableName3); - admin.deleteTable(clonedTableName3); - admin.deleteSnapshot(snapshotName2); - } - // ========================================================================== // Helpers // ==========================================================================
d54477c34b1643fb68539bf6c235dc001582ec9c
intellij-community
Maven: test fixed by removing unnecessary and- obsolete assertion--
c
https://github.com/JetBrains/intellij-community
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 5c1fdbead33a3..7117306ba4430 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 @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.maven.compiler; -import com.intellij.compiler.CompilerConfiguration; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.fileTypes.FileTypeManager; @@ -911,7 +910,6 @@ public void testCustomEscapingFiltering() throws Exception { } public void testDoNotFilterButCopyBigFiles() throws Exception { - assertFalse(CompilerConfiguration.getInstance(myProject).isResourceFile("file.xyz")); assertEquals(FileTypeManager.getInstance().getFileTypeByFileName("file.xyz"), FileTypes.UNKNOWN); createProjectSubFile("resources/file.xyz").setBinaryContent(new byte[1024 * 1024 * 20]);
8738a12d94509246cbb435474e03fc4421dd2537
drools
JBRULES-447 - small fix for rule attributes--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@6003 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
c
https://github.com/kiegroup/drools
diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/model/Rule.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/model/Rule.java index d5a40702968..6b3ba6b5659 100644 --- a/drools-decisiontables/src/main/java/org/drools/decisiontable/model/Rule.java +++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/model/Rule.java @@ -100,13 +100,13 @@ public void renderDRL(final DRLOutput out) { out.writeLine( "\tsalience " + this._salience ); } if ( this._activationGroup != null ) { - out.writeLine( "\tactivation-group" + this._activationGroup ); + out.writeLine( "\tactivation-group " + this._activationGroup ); } if ( this._noLoop != null ) { - out.writeLine( "\tno-loop" + this._noLoop ); + out.writeLine( "\tno-loop " + this._noLoop ); } if ( this._duration != null ) { - out.writeLine( "\tduration" + this._duration ); + out.writeLine( "\tduration " + this._duration ); } out.writeLine( "\twhen" ); @@ -239,14 +239,6 @@ public void setNoLoop(final String value) // Set the no-loop attribute of the ru this._noLoop = value; } - public boolean getNoLoop() { - String value = "false"; - if ( this._noLoop.compareTo( "true" ) != 0 ) { - value = this._noLoop; - } - final Boolean b = new Boolean( value ); - return b.booleanValue(); - } /** * @return The row in the spreadsheet this represents.
24a996801b15e26ee749194977b5995d7b00c485
camel
CAMEL-2445 applied patch with thanks to Stan and- Jeff--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@906342 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 0f7e42c4e4c3d..e780e2a7f942e 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 @@ -27,6 +27,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import org.apache.camel.CamelException; import org.apache.camel.Exchange; import org.apache.camel.Navigate; import org.apache.camel.Processor; @@ -297,8 +298,12 @@ public void run() { try { try { sendExchanges(); - } catch (Exception e) { - getExceptionHandler().handleException(e); + } catch (Throwable t) { + if (t instanceof Exception) { + getExceptionHandler().handleException(t); + } else { + getExceptionHandler().handleException(new CamelException(t)); + } } } finally { queueLock.lock(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregatorExceptionTest.java b/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregatorExceptionTest.java new file mode 100644 index 0000000000000..1bea0a7436392 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregatorExceptionTest.java @@ -0,0 +1,61 @@ +/** + * 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.processor.aggregator; + +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; + +public class AggregatorExceptionTest extends ContextTestSupport { + + public void testAggregateAndOnException() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:error"); + + // can change this to 5 when BatchProcessor's exception handling works properly + mock.expectedMessageCount(0); + + for (int c = 0; c <= 10; c++) { + template.sendBodyAndHeader("seda:start", "Hi!", "id", 123); + } + assertMockEndpointsSatisfied(); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + + final String exceptionString = "This is an Error not an Exception"; + + //errorHandler(deadLetterChannel("mock:error")); + onException(Throwable.class).handled(true).to("mock:error"); + + from("seda:start") + .aggregate(header("id")) + .batchSize(2) + .process(new Processor() { + public void process(Exchange exchange) throws Exception { + throw new java.lang.NoSuchMethodError(exceptionString); + } + }); + } + }; + } +}
3c3d4b1658b3bd3c8aff620116f3a110bdc3d6d6
orientdb
Issue -1607 Fix blueprints tests and TX NPEs.--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java b/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java index 709c22b0294..99f7f0b3b10 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java +++ b/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java @@ -341,7 +341,7 @@ public boolean addResult(OSBTreeBucket.SBTreeEntry<Object, V> entry) { Collection<OIdentifiable> identifiables = transformer.transformFromValue(entry.value); for (OIdentifiable identifiable : identifiables) { if (identifiable.equals(value)) - keySetToRemove.add(value); + keySetToRemove.add(entry.key); } } return true; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java index c306ea4f81b..c15d49b0439 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java @@ -96,7 +96,7 @@ protected void startStorageTx(OTransaction clientTx) throws IOException { } protected void rollbackStorageTx() throws IOException { - if (writeAheadLog == null) + if (writeAheadLog == null || transaction == null) return; writeAheadLog.log(new OAtomicUnitEndRecord(transaction.getOperationUnitId(), true));
51e9da224f80254476a7dc446bca817b505381d8
jenkinsci$clearcase-plugin
Use a temporary file to decrease memory consumption of diffbl
p
https://github.com/jenkinsci/clearcase-plugin
diff --git a/src/main/java/hudson/plugins/clearcase/ClearTool.java b/src/main/java/hudson/plugins/clearcase/ClearTool.java index e5c1ac16..55b5cb61 100644 --- a/src/main/java/hudson/plugins/clearcase/ClearTool.java +++ b/src/main/java/hudson/plugins/clearcase/ClearTool.java @@ -74,8 +74,9 @@ public static enum DefaultPromotionLevel { * @param baseline2 * @param viewPath A view path name needed to retrieve versions from * @return + * @throws IOException if unable to do I/O operations */ - Reader diffbl(EnumSet<DiffBlOptions> options, String baseline1, String baseline2, String viewPath); + Reader diffbl(EnumSet<DiffBlOptions> options, String baseline1, String baseline2, String viewPath) throws IOException; /** * @param streamSelector diff --git a/src/main/java/hudson/plugins/clearcase/ClearToolExec.java b/src/main/java/hudson/plugins/clearcase/ClearToolExec.java index 1dfb86da..ac5786bb 100644 --- a/src/main/java/hudson/plugins/clearcase/ClearToolExec.java +++ b/src/main/java/hudson/plugins/clearcase/ClearToolExec.java @@ -34,9 +34,13 @@ import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.OutputStream; import java.io.Reader; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -91,7 +95,7 @@ public Reader describe(String format, String objectSelector) throws IOException, } @Override - public Reader diffbl(EnumSet<DiffBlOptions> type, String baseline1, String baseline2, String viewPath) { + public Reader diffbl(EnumSet<DiffBlOptions> type, String baseline1, String baseline2, String viewPath) throws IOException { ArgumentListBuilder cmd = new ArgumentListBuilder(); cmd.add("diffbl"); if (type != null) { @@ -102,18 +106,26 @@ public Reader diffbl(EnumSet<DiffBlOptions> type, String baseline1, String basel cmd.add(baseline1); cmd.add(baseline2); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // Output to a temporary file since the output can become quite large + File tmpFile = null; + try { + tmpFile = File.createTempFile("cleartool-diffbl", null); + } catch (IOException e) { + throw new IOException("Couldn't create a temporary file", e); + } + OutputStream out = new FileOutputStream(tmpFile); FilePath workingDirectory = launcher.getWorkspace(); if (viewPath != null) { workingDirectory = workingDirectory.child(viewPath); } try { - launcher.run(cmd.toCommandArray(), null, baos, workingDirectory); + launcher.run(cmd.toCommandArray(), null, out, workingDirectory); } catch (IOException e) { } catch (InterruptedException e) { } - return new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())); + out.close(); + return new InputStreamReader(new FileInputStream(tmpFile)); } @Override
431ccf96d2b8cfbea44518bc2ec9fa6937b421da
intellij-community
ui: use setter--
p
https://github.com/JetBrains/intellij-community
diff --git a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnAction.java b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnAction.java index dad449da8ba82..4d1a1ca35bcfe 100644 --- a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnAction.java +++ b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnAction.java @@ -16,7 +16,6 @@ package com.intellij.openapi.actionSystem; import com.intellij.openapi.Disposable; -import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.PossiblyDumbAware; @@ -202,7 +201,7 @@ public final void copyFrom(@NotNull AnAction sourceAction){ } public final void copyShortcutFrom(@NotNull AnAction sourceAction) { - myShortcutSet = sourceAction.myShortcutSet; + setShortcutSet(sourceAction.getShortcutSet()); }
6ebf6a1c3a48f4b3f18bfe4e42f86e1b3b8398a2
orientdb
HTTP static content now supports single file as- configuration--
a
https://github.com/orientechnologies/orientdb
diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetStaticContent.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetStaticContent.java index d1ce5c3bea7..6c36d1286f2 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetStaticContent.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetStaticContent.java @@ -38,11 +38,14 @@ public class OServerCommandGetStaticContent extends OServerCommandConfigurableAb "GET|*.swf", "GET|favicon.ico", "GET|robots.txt" }; private static final String CONFIG_HTTP_CACHE = "http.cache:"; + private static final String CONFIG_ROOT_PATH = "root.path"; + private static final String CONFIG_FILE_PATH = "file.path"; private Map<String, OStaticContentCachedEntry> cacheContents; private Map<String, String> cacheHttp = new HashMap<String, String>(); private String cacheHttpDefault = "Cache-Control: max-age=3000"; - private String wwwPath; + private String rootPath; + private String filePath; public OServerCommandGetStaticContent() { super(DEF_PATTERN); @@ -63,7 +66,11 @@ else if (filter.length() > 0) { cacheHttp.put(f, par.value); } } - } + } else if (par.name.startsWith(CONFIG_ROOT_PATH)) + rootPath = par.value; + else if (par.name.startsWith(CONFIG_FILE_PATH)) + filePath = par.value; + } } @@ -72,14 +79,23 @@ public boolean execute(final OHttpRequest iRequest) throws Exception { iRequest.data.commandInfo = "Get static content"; iRequest.data.commandDetail = iRequest.url; - if (wwwPath == null) { - wwwPath = iRequest.configuration.getValueAsString("orientdb.www.path", "src/site"); + if (filePath == null && rootPath == null) { + // GET GLOBAL CONFIG + rootPath = iRequest.configuration.getValueAsString("orientdb.www.path", "src/site"); + if (rootPath == null) { + OLogManager.instance().warn(this, + "No path configured. Specify the 'root.path', 'file.path' or the global 'orientdb.www.path' variable", rootPath); + return false; + } + } - final File wwwPathDirectory = new File(wwwPath); + if (filePath == null) { + // CHECK DIRECTORY + final File wwwPathDirectory = new File(rootPath); if (!wwwPathDirectory.exists()) - OLogManager.instance().warn(this, "orientdb.www.path variable points to '%s' but it doesn't exists", wwwPath); + OLogManager.instance().warn(this, "path variable points to '%s' but it doesn't exists", rootPath); if (!wwwPathDirectory.isDirectory()) - OLogManager.instance().warn(this, "orientdb.www.path variable points to '%s' but it isn't a directory", wwwPath); + OLogManager.instance().warn(this, "path variable points to '%s' but it isn't a directory", rootPath); } if (cacheContents == null && OGlobalConfiguration.SERVER_CACHE_FILE_STATIC.getValueAsBoolean()) @@ -91,18 +107,22 @@ public boolean execute(final OHttpRequest iRequest) throws Exception { String type = null; try { - final String url = getResource(iRequest); - - String filePath; - // REPLACE WWW WITH REAL PATH - if (url.startsWith("/www")) - filePath = wwwPath + url.substring("/www".length(), url.length()); - else - filePath = wwwPath + url; + String path; + if (filePath != null) + // SINGLE FILE + path = filePath; + else { + // GET FROM A DIRECTORY + final String url = getResource(iRequest); + if (url.startsWith("/www")) + path = rootPath + url.substring("/www".length(), url.length()); + else + path = rootPath + url; + } if (cacheContents != null) { synchronized (cacheContents) { - final OStaticContentCachedEntry cachedEntry = cacheContents.get(filePath); + final OStaticContentCachedEntry cachedEntry = cacheContents.get(path); if (cachedEntry != null) { is = new ByteArrayInputStream(cachedEntry.content); contentSize = cachedEntry.size; @@ -112,38 +132,38 @@ public boolean execute(final OHttpRequest iRequest) throws Exception { } if (is == null) { - File inputFile = new File(filePath); + File inputFile = new File(path); if (!inputFile.exists()) { - OLogManager.instance().debug(this, "Static resource not found: %s", filePath); + OLogManager.instance().debug(this, "Static resource not found: %s", path); sendBinaryContent(iRequest, 404, "File not found", null, null, 0); return false; } - if (inputFile.isDirectory()) { - inputFile = new File(filePath + "/index.htm"); + if (filePath == null && inputFile.isDirectory()) { + inputFile = new File(path + "/index.htm"); if (inputFile.exists()) - filePath = url + "/index.htm"; + path = path + "/index.htm"; else { - inputFile = new File(url + "/index.html"); + inputFile = new File(path + "/index.html"); if (inputFile.exists()) - filePath = url + "/index.html"; + path = path + "/index.html"; } } - if (filePath.endsWith(".htm") || filePath.endsWith(".html")) + if (path.endsWith(".htm") || path.endsWith(".html")) type = "text/html"; - else if (filePath.endsWith(".png")) + else if (path.endsWith(".png")) type = "image/png"; - else if (filePath.endsWith(".jpeg")) + else if (path.endsWith(".jpeg")) type = "image/jpeg"; - else if (filePath.endsWith(".js")) + else if (path.endsWith(".js")) type = "application/x-javascript"; - else if (filePath.endsWith(".css")) + else if (path.endsWith(".css")) type = "text/css"; - else if (filePath.endsWith(".ico")) + else if (path.endsWith(".ico")) type = "image/x-icon"; - else if (filePath.endsWith(".otf")) + else if (path.endsWith(".otf")) type = "font/opentype"; else type = "text/plain"; @@ -162,7 +182,7 @@ else if (filePath.endsWith(".otf")) cachedEntry.size = contentSize; cachedEntry.type = type; - cacheContents.put(url, cachedEntry); + cacheContents.put(path, cachedEntry); is = new ByteArrayInputStream(cachedEntry.content); }
de8f0efe60233436431930447d7672f2a1dc8878
hadoop
MAPREDUCE-3121. NodeManager should handle- disk-failures (Ravi Gummadi via mahadev) - Merging r1208131 from trunk.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1208135 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt index 23fc209db4ee7..e349d206ff33f 100644 --- a/hadoop-mapreduce-project/CHANGES.txt +++ b/hadoop-mapreduce-project/CHANGES.txt @@ -6,6 +6,8 @@ Release 0.23.1 - Unreleased NEW FEATURES + MAPREDUCE-3121. NodeManager should handle disk-failures (Ravi Gummadi via mahadev) + IMPROVEMENTS MAPREDUCE-3375. [Gridmix] Memory Emulation system tests. (Vinay Thota via amarrk) diff --git a/hadoop-mapreduce-project/conf/container-executor.cfg b/hadoop-mapreduce-project/conf/container-executor.cfg index 1c11734b48949..fe1d680529650 100644 --- a/hadoop-mapreduce-project/conf/container-executor.cfg +++ b/hadoop-mapreduce-project/conf/container-executor.cfg @@ -1,3 +1,3 @@ -yarn.nodemanager.local-dirs=#configured value of yarn.nodemanager.local-dirs. It can be a list of comma separated paths. -yarn.nodemanager.log-dirs=#configured value of yarn.nodemanager.log-dirs. yarn.nodemanager.linux-container-executor.group=#configured value of yarn.nodemanager.linux-container-executor.group +banned.users=#comma separated list of users who can not run applications +min.user.id=1000#Prevent other super-users diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java index 19f558c67261b..14d8644e6e0a7 100644 --- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java +++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java @@ -113,9 +113,10 @@ public void setup(JobConf conf) throws IOException { Map<LocalResource, Future<Path>> resourcesToPaths = Maps.newHashMap(); ExecutorService exec = Executors.newCachedThreadPool(); + Path destPath = localDirAllocator.getLocalPathForWrite(".", conf); for (LocalResource resource : localResources.values()) { Callable<Path> download = new FSDownload(localFSFileContext, ugi, conf, - localDirAllocator, resource, new Random()); + destPath, resource, new Random()); Future<Path> future = exec.submit(download); resourcesToPaths.put(resource, future); } diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java index 845d64f800b60..1120413eb7c0d 100644 --- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java +++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java @@ -56,7 +56,7 @@ public MiniMRYarnCluster(String testName) { } public MiniMRYarnCluster(String testName, int noOfNMs) { - super(testName, noOfNMs); + super(testName, noOfNMs, 4, 4); //TODO: add the history server historyServerWrapper = new JobHistoryServerWrapper(); addService(historyServerWrapper); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java index 472c959eda58d..fb99c1cc2270d 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java @@ -43,7 +43,8 @@ public class TestDistributedShell { public static void setup() throws InterruptedException, IOException { LOG.info("Starting up YARN cluster"); if (yarnCluster == null) { - yarnCluster = new MiniYARNCluster(TestDistributedShell.class.getName()); + yarnCluster = new MiniYARNCluster(TestDistributedShell.class.getName(), + 1, 1, 1); yarnCluster.init(conf); yarnCluster.start(); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java index 0779a5f7320a1..d4b8f9fc56c9e 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java @@ -351,13 +351,39 @@ public class YarnConfiguration extends Configuration { /** Class that calculates containers current resource utilization.*/ public static final String NM_CONTAINER_MON_RESOURCE_CALCULATOR = NM_PREFIX + "container-monitor.resource-calculator.class"; - + + /** + * Enable/Disable disks' health checker. Default is true. + * An expert level configuration property. + */ + public static final String NM_DISK_HEALTH_CHECK_ENABLE = + NM_PREFIX + "disk-health-checker.enable"; + /** Frequency of running disks' health checker.*/ + public static final String NM_DISK_HEALTH_CHECK_INTERVAL_MS = + NM_PREFIX + "disk-health-checker.interval-ms"; + /** By default, disks' health is checked every 2 minutes. */ + public static final long DEFAULT_NM_DISK_HEALTH_CHECK_INTERVAL_MS = + 2 * 60 * 1000; + + /** + * The minimum fraction of number of disks to be healthy for the nodemanager + * to launch new containers. This applies to nm-local-dirs and nm-log-dirs. + */ + public static final String NM_MIN_HEALTHY_DISKS_FRACTION = + NM_PREFIX + "disk-health-checker.min-healthy-disks"; + /** + * By default, at least 5% of disks are to be healthy to say that the node + * is healthy in terms of disks. + */ + public static final float DEFAULT_NM_MIN_HEALTHY_DISKS_FRACTION + = 0.25F; + /** Frequency of running node health script.*/ public static final String NM_HEALTH_CHECK_INTERVAL_MS = NM_PREFIX + "health-checker.interval-ms"; public static final long DEFAULT_NM_HEALTH_CHECK_INTERVAL_MS = 10 * 60 * 1000; - - /** Script time out period.*/ + + /** Health check script time out period.*/ public static final String NM_HEALTH_CHECK_SCRIPT_TIMEOUT_MS = NM_PREFIX + "health-checker.script.timeout-ms"; public static final long DEFAULT_NM_HEALTH_CHECK_SCRIPT_TIMEOUT_MS = diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java index b49ecc784cc46..0845c446670c9 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java @@ -31,6 +31,7 @@ import java.security.PrivilegedExceptionAction; import java.util.EnumSet; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -105,12 +106,12 @@ public String toString() { public static class LogValue { - private final String[] rootLogDirs; + private final List<String> rootLogDirs; private final ContainerId containerId; // TODO Maybe add a version string here. Instead of changing the version of // the entire k-v format - public LogValue(String[] rootLogDirs, ContainerId containerId) { + public LogValue(List<String> rootLogDirs, ContainerId containerId) { this.rootLogDirs = rootLogDirs; this.containerId = containerId; } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/FSDownload.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/FSDownload.java index cccb140d99b3a..24a23c8c0c25a 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/FSDownload.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/FSDownload.java @@ -33,7 +33,6 @@ import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; -import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Options.Rename; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.UserGroupInformation; @@ -56,7 +55,10 @@ public class FSDownload implements Callable<Path> { private final UserGroupInformation userUgi; private Configuration conf; private LocalResource resource; - private LocalDirAllocator dirs; + + /** The local FS dir path under which this resource is to be localized to */ + private Path destDirPath; + private static final FsPermission cachePerms = new FsPermission( (short) 0755); static final FsPermission PUBLIC_FILE_PERMS = new FsPermission((short) 0555); @@ -65,10 +67,11 @@ public class FSDownload implements Callable<Path> { static final FsPermission PUBLIC_DIR_PERMS = new FsPermission((short) 0755); static final FsPermission PRIVATE_DIR_PERMS = new FsPermission((short) 0700); + public FSDownload(FileContext files, UserGroupInformation ugi, Configuration conf, - LocalDirAllocator dirs, LocalResource resource, Random rand) { + Path destDirPath, LocalResource resource, Random rand) { this.conf = conf; - this.dirs = dirs; + this.destDirPath = destDirPath; this.files = files; this.userUgi = ugi; this.resource = resource; @@ -136,15 +139,13 @@ public Path call() throws Exception { } Path tmp; - Path dst = - dirs.getLocalPathForWrite(".", getEstimatedSize(resource), - conf); do { - tmp = new Path(dst, String.valueOf(rand.nextLong())); + tmp = new Path(destDirPath, String.valueOf(rand.nextLong())); } while (files.util().exists(tmp)); - dst = tmp; - files.mkdir(dst, cachePerms, false); - final Path dst_work = new Path(dst + "_tmp"); + destDirPath = tmp; + + files.mkdir(destDirPath, cachePerms, false); + final Path dst_work = new Path(destDirPath + "_tmp"); files.mkdir(dst_work, cachePerms, false); Path dFinal = files.makeQualified(new Path(dst_work, sCopy.getName())); @@ -158,9 +159,9 @@ public Path run() throws Exception { }); unpack(new File(dTmp.toUri()), new File(dFinal.toUri())); changePermissions(dFinal.getFileSystem(conf), dFinal); - files.rename(dst_work, dst, Rename.OVERWRITE); + files.rename(dst_work, destDirPath, Rename.OVERWRITE); } catch (Exception e) { - try { files.delete(dst, true); } catch (IOException ignore) { } + try { files.delete(destDirPath, true); } catch (IOException ignore) { } throw e; } finally { try { @@ -170,9 +171,8 @@ public Path run() throws Exception { rand = null; conf = null; resource = null; - dirs = null; } - return files.makeQualified(new Path(dst, sCopy.getName())); + return files.makeQualified(new Path(destDirPath, sCopy.getName())); } /** @@ -221,17 +221,4 @@ public Void run() throws Exception { } } - private static long getEstimatedSize(LocalResource rsrc) { - if (rsrc.getSize() < 0) { - return -1; - } - switch (rsrc.getType()) { - case ARCHIVE: - return 5 * rsrc.getSize(); - case FILE: - default: - return rsrc.getSize(); - } - } - } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/TestFSDownload.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/TestFSDownload.java index b7237bdefc2e7..fe1f3ac003125 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/TestFSDownload.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/TestFSDownload.java @@ -146,13 +146,14 @@ public void testDownload() throws IOException, URISyntaxException, vis = LocalResourceVisibility.APPLICATION; break; } - - LocalResource rsrc = createFile(files, new Path(basedir, "" + i), - sizes[i], rand, vis); + Path p = new Path(basedir, "" + i); + LocalResource rsrc = createFile(files, p, sizes[i], rand, vis); rsrcVis.put(rsrc, vis); + Path destPath = dirs.getLocalPathForWrite( + basedir.toString(), sizes[i], conf); FSDownload fsd = new FSDownload(files, UserGroupInformation.getCurrentUser(), conf, - dirs, rsrc, new Random(sharedSeed)); + destPath, rsrc, new Random(sharedSeed)); pending.put(rsrc, exec.submit(fsd)); } @@ -249,13 +250,15 @@ public void testDirDownload() throws IOException, InterruptedException { vis = LocalResourceVisibility.APPLICATION; break; } - - LocalResource rsrc = createJar(files, new Path(basedir, "dir" + i - + ".jar"), vis); + + Path p = new Path(basedir, "dir" + i + ".jar"); + LocalResource rsrc = createJar(files, p, vis); rsrcVis.put(rsrc, vis); + Path destPath = dirs.getLocalPathForWrite( + basedir.toString(), conf); FSDownload fsd = new FSDownload(files, UserGroupInformation.getCurrentUser(), conf, - dirs, rsrc, new Random(sharedSeed)); + destPath, rsrc, new Random(sharedSeed)); pending.put(rsrc, exec.submit(fsd)); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/resources/yarn-default.xml b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/resources/yarn-default.xml index ac6bce2dda355..fdb7cb6c5b7df 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/resources/yarn-default.xml +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/resources/yarn-default.xml @@ -388,6 +388,22 @@ <value></value> </property> + <property> + <description>Frequency of running disk health checker code.</description> + <name>yarn.nodemanager.disk-health-checker.interval-ms</name> + <value>120000</value> + </property> + + <property> + <description>The minimum fraction of number of disks to be healthy for the + nodemanager to launch new containers. This correspond to both + yarn-nodemanager.local-dirs and yarn.nodemanager.log-dirs. i.e. If there + are less number of healthy local-dirs (or log-dirs) available, then + new containers will not be launched on this node.</description> + <name>yarn.nodemanager.disk-health-checker.min-healthy-disks</name> + <value>0.25</value> + </property> + <property> <description>The path to the Linux container executor.</description> <name>yarn.nodemanager.linux-container-executor.path</name> diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java index 6c3667ae5f941..e6a47da89c971 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java @@ -45,6 +45,7 @@ public abstract class ContainerExecutor implements Configurable { FsPermission.createImmutable((short) 0700); private Configuration conf; + private ConcurrentMap<ContainerId, Path> pidFiles = new ConcurrentHashMap<ContainerId, Path>(); @@ -68,7 +69,7 @@ public Configuration getConf() { * @throws IOException */ public abstract void init() throws IOException; - + /** * Prepare the environment for containers in this application to execute. * For $x in local.dirs @@ -82,12 +83,14 @@ public Configuration getConf() { * @param appId id of the application * @param nmPrivateContainerTokens path to localized credentials, rsrc by NM * @param nmAddr RPC address to contact NM + * @param localDirs nm-local-dirs + * @param logDirs nm-log-dirs * @throws IOException For most application init failures * @throws InterruptedException If application init thread is halted by NM */ public abstract void startLocalizer(Path nmPrivateContainerTokens, InetSocketAddress nmAddr, String user, String appId, String locId, - List<Path> localDirs) + List<String> localDirs, List<String> logDirs) throws IOException, InterruptedException; @@ -100,12 +103,15 @@ public abstract void startLocalizer(Path nmPrivateContainerTokens, * @param user the user of the container * @param appId the appId of the container * @param containerWorkDir the work dir for the container + * @param localDirs nm-local-dirs to be used for this container + * @param logDirs nm-log-dirs to be used for this container * @return the return status of the launch * @throws IOException */ public abstract int launchContainer(Container container, Path nmPrivateContainerScriptPath, Path nmPrivateTokensPath, - String user, String appId, Path containerWorkDir) throws IOException; + String user, String appId, Path containerWorkDir, List<String> localDirs, + List<String> logDirs) throws IOException; public abstract boolean signalContainer(String user, String pid, Signal signal) @@ -116,7 +122,8 @@ public abstract void deleteAsUser(String user, Path subDir, Path... basedirs) public enum ExitCode { FORCE_KILLED(137), - TERMINATED(143); + TERMINATED(143), + DISKS_FAILED(-101); private final int code; private ExitCode(int exitCode) { diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java index 9c252b142d44a..bd953174aa0cc 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java @@ -26,6 +26,7 @@ import java.io.IOException; import java.io.PrintStream; import java.net.InetSocketAddress; +import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; @@ -39,7 +40,6 @@ import org.apache.hadoop.util.Shell.ExitCodeException; import org.apache.hadoop.util.Shell.ShellCommandExecutor; import org.apache.hadoop.yarn.api.records.ContainerId; -import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerDiagnosticsUpdateEvent; @@ -77,16 +77,17 @@ public void init() throws IOException { @Override public void startLocalizer(Path nmPrivateContainerTokensPath, InetSocketAddress nmAddr, String user, String appId, String locId, - List<Path> localDirs) throws IOException, InterruptedException { + List<String> localDirs, List<String> logDirs) + throws IOException, InterruptedException { ContainerLocalizer localizer = - new ContainerLocalizer(this.lfs, user, appId, locId, - localDirs, RecordFactoryProvider.getRecordFactory(getConf())); + new ContainerLocalizer(lfs, user, appId, locId, getPaths(localDirs), + RecordFactoryProvider.getRecordFactory(getConf())); createUserLocalDirs(localDirs, user); createUserCacheDirs(localDirs, user); createAppDirs(localDirs, user, appId); - createAppLogDirs(appId); + createAppLogDirs(appId, logDirs); // TODO: Why pick first app dir. The same in LCE why not random? Path appStorageDir = getFirstApplicationDir(localDirs, user, appId); @@ -104,8 +105,8 @@ public void startLocalizer(Path nmPrivateContainerTokensPath, @Override public int launchContainer(Container container, Path nmPrivateContainerScriptPath, Path nmPrivateTokensPath, - String userName, String appId, Path containerWorkDir) - throws IOException { + String userName, String appId, Path containerWorkDir, + List<String> localDirs, List<String> logDirs) throws IOException { ContainerId containerId = container.getContainerID(); @@ -115,10 +116,7 @@ public int launchContainer(Container container, ConverterUtils.toString( container.getContainerID().getApplicationAttemptId(). getApplicationId()); - String[] sLocalDirs = getConf().getStrings( - YarnConfiguration.NM_LOCAL_DIRS, - YarnConfiguration.DEFAULT_NM_LOCAL_DIRS); - for (String sLocalDir : sLocalDirs) { + for (String sLocalDir : localDirs) { Path usersdir = new Path(sLocalDir, ContainerLocalizer.USERCACHE); Path userdir = new Path(usersdir, userName); Path appCacheDir = new Path(userdir, ContainerLocalizer.APPCACHE); @@ -128,7 +126,7 @@ public int launchContainer(Container container, } // Create the container log-dirs on all disks - createContainerLogDirs(appIdStr, containerIdStr); + createContainerLogDirs(appIdStr, containerIdStr, logDirs); // copy launch script to work dir Path launchDst = @@ -299,9 +297,9 @@ public void deleteAsUser(String user, Path subDir, Path... baseDirs) * $logdir/$user/$appId */ private static final short LOGDIR_PERM = (short)0710; - private Path getFirstApplicationDir(List<Path> localDirs, String user, + private Path getFirstApplicationDir(List<String> localDirs, String user, String appId) { - return getApplicationDir(localDirs.get(0), user, appId); + return getApplicationDir(new Path(localDirs.get(0)), user, appId); } private Path getApplicationDir(Path base, String user, String appId) { @@ -328,14 +326,14 @@ private Path getFileCacheDir(Path base, String user) { * <li>$local.dir/usercache/$user</li> * </ul> */ - private void createUserLocalDirs(List<Path> localDirs, String user) + private void createUserLocalDirs(List<String> localDirs, String user) throws IOException { boolean userDirStatus = false; FsPermission userperms = new FsPermission(USER_PERM); - for (Path localDir : localDirs) { + for (String localDir : localDirs) { // create $local.dir/usercache/$user and its immediate parent try { - lfs.mkdir(getUserCacheDir(localDir, user), userperms, true); + lfs.mkdir(getUserCacheDir(new Path(localDir), user), userperms, true); } catch (IOException e) { LOG.warn("Unable to create the user directory : " + localDir, e); continue; @@ -357,7 +355,7 @@ private void createUserLocalDirs(List<Path> localDirs, String user) * <li>$local.dir/usercache/$user/filecache</li> * </ul> */ - private void createUserCacheDirs(List<Path> localDirs, String user) + private void createUserCacheDirs(List<String> localDirs, String user) throws IOException { LOG.info("Initializing user " + user); @@ -366,9 +364,10 @@ private void createUserCacheDirs(List<Path> localDirs, String user) FsPermission appCachePerms = new FsPermission(APPCACHE_PERM); FsPermission fileperms = new FsPermission(FILECACHE_PERM); - for (Path localDir : localDirs) { + for (String localDir : localDirs) { // create $local.dir/usercache/$user/appcache - final Path appDir = getAppcacheDir(localDir, user); + Path localDirPath = new Path(localDir); + final Path appDir = getAppcacheDir(localDirPath, user); try { lfs.mkdir(appDir, appCachePerms, true); appcacheDirStatus = true; @@ -376,7 +375,7 @@ private void createUserCacheDirs(List<Path> localDirs, String user) LOG.warn("Unable to create app cache directory : " + appDir, e); } // create $local.dir/usercache/$user/filecache - final Path distDir = getFileCacheDir(localDir, user); + final Path distDir = getFileCacheDir(localDirPath, user); try { lfs.mkdir(distDir, fileperms, true); distributedCacheDirStatus = true; @@ -403,12 +402,12 @@ private void createUserCacheDirs(List<Path> localDirs, String user) * </ul> * @param localDirs */ - private void createAppDirs(List<Path> localDirs, String user, String appId) + private void createAppDirs(List<String> localDirs, String user, String appId) throws IOException { boolean initAppDirStatus = false; FsPermission appperms = new FsPermission(APPDIR_PERM); - for (Path localDir : localDirs) { - Path fullAppDir = getApplicationDir(localDir, user, appId); + for (String localDir : localDirs) { + Path fullAppDir = getApplicationDir(new Path(localDir), user, appId); // create $local.dir/usercache/$user/appcache/$appId try { lfs.mkdir(fullAppDir, appperms, true); @@ -427,15 +426,12 @@ private void createAppDirs(List<Path> localDirs, String user, String appId) /** * Create application log directories on all disks. */ - private void createAppLogDirs(String appId) + private void createAppLogDirs(String appId, List<String> logDirs) throws IOException { - String[] rootLogDirs = - getConf() - .getStrings(YarnConfiguration.NM_LOG_DIRS, YarnConfiguration.DEFAULT_NM_LOG_DIRS); - + boolean appLogDirStatus = false; FsPermission appLogDirPerms = new FsPermission(LOGDIR_PERM); - for (String rootLogDir : rootLogDirs) { + for (String rootLogDir : logDirs) { // create $log.dir/$appid Path appLogDir = new Path(rootLogDir, appId); try { @@ -455,15 +451,12 @@ private void createAppLogDirs(String appId) /** * Create application log directories on all disks. */ - private void createContainerLogDirs(String appId, String containerId) - throws IOException { - String[] rootLogDirs = - getConf() - .getStrings(YarnConfiguration.NM_LOG_DIRS, YarnConfiguration.DEFAULT_NM_LOG_DIRS); - + private void createContainerLogDirs(String appId, String containerId, + List<String> logDirs) throws IOException { + boolean containerLogDirStatus = false; FsPermission containerLogDirPerms = new FsPermission(LOGDIR_PERM); - for (String rootLogDir : rootLogDirs) { + for (String rootLogDir : logDirs) { // create $log.dir/$appid/$containerid Path appLogDir = new Path(rootLogDir, appId); Path containerLogDir = new Path(appLogDir, containerId); @@ -483,4 +476,15 @@ private void createContainerLogDirs(String appId, String containerId) + containerId); } } + + /** + * @return the list of paths of given local directories + */ + private static List<Path> getPaths(List<String> dirs) { + List<Path> paths = new ArrayList<Path>(dirs.size()); + for (int i = 0; i < dirs.size(); i++) { + paths.add(new Path(dirs.get(i))); + } + return paths; + } } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DirectoryCollection.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DirectoryCollection.java new file mode 100644 index 0000000000000..67ed4618a0e4c --- /dev/null +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DirectoryCollection.java @@ -0,0 +1,96 @@ +/** +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.hadoop.yarn.server.nodemanager; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.util.DiskChecker; +import org.apache.hadoop.util.DiskChecker.DiskErrorException; + +/** + * Manages a list of local storage directories. + */ +class DirectoryCollection { + private static final Log LOG = LogFactory.getLog(DirectoryCollection.class); + + // Good local storage directories + private List<String> localDirs; + private List<String> failedDirs; + private int numFailures; + + public DirectoryCollection(String[] dirs) { + localDirs = new ArrayList<String>(); + localDirs.addAll(Arrays.asList(dirs)); + failedDirs = new ArrayList<String>(); + } + + /** + * @return the current valid directories + */ + synchronized List<String> getGoodDirs() { + return localDirs; + } + + /** + * @return the failed directories + */ + synchronized List<String> getFailedDirs() { + return failedDirs; + } + + /** + * @return total the number of directory failures seen till now + */ + synchronized int getNumFailures() { + return numFailures; + } + + /** + * Check the health of current set of local directories, updating the list + * of valid directories if necessary. + * @return <em>true</em> if there is a new disk-failure identified in + * this checking. <em>false</em> otherwise. + */ + synchronized boolean checkDirs() { + int oldNumFailures = numFailures; + ListIterator<String> it = localDirs.listIterator(); + while (it.hasNext()) { + final String dir = it.next(); + try { + DiskChecker.checkDir(new File(dir)); + } catch (DiskErrorException de) { + LOG.warn("Directory " + dir + " error " + + de.getMessage() + ", removing from the list of valid directories."); + it.remove(); + failedDirs.add(dir); + numFailures++; + } + } + if (numFailures > oldNumFailures) { + return true; + } + return false; + } +} diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java index 2ecf2b302e351..28f1247bb32eb 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java @@ -126,13 +126,18 @@ public void init() throws IOException { @Override public void startLocalizer(Path nmPrivateContainerTokensPath, InetSocketAddress nmAddr, String user, String appId, String locId, - List<Path> localDirs) throws IOException, InterruptedException { + List<String> localDirs, List<String> logDirs) + throws IOException, InterruptedException { + List<String> command = new ArrayList<String>( Arrays.asList(containerExecutorExe, user, Integer.toString(Commands.INITIALIZE_CONTAINER.getValue()), appId, - nmPrivateContainerTokensPath.toUri().getPath().toString())); + nmPrivateContainerTokensPath.toUri().getPath().toString(), + StringUtils.join(",", localDirs), + StringUtils.join(",", logDirs))); + File jvm = // use same jvm as parent new File(new File(System.getProperty("java.home"), "bin"), "java"); command.add(jvm.toString()); @@ -148,8 +153,8 @@ public void startLocalizer(Path nmPrivateContainerTokensPath, command.add(locId); command.add(nmAddr.getHostName()); command.add(Integer.toString(nmAddr.getPort())); - for (Path p : localDirs) { - command.add(p.toUri().getPath().toString()); + for (String dir : localDirs) { + command.add(dir); } String[] commandArray = command.toArray(new String[command.size()]); ShellCommandExecutor shExec = new ShellCommandExecutor(commandArray); @@ -174,7 +179,8 @@ public void startLocalizer(Path nmPrivateContainerTokensPath, @Override public int launchContainer(Container container, Path nmPrivateCotainerScriptPath, Path nmPrivateTokensPath, - String user, String appId, Path containerWorkDir) throws IOException { + String user, String appId, Path containerWorkDir, + List<String> localDirs, List<String> logDirs) throws IOException { ContainerId containerId = container.getContainerID(); String containerIdStr = ConverterUtils.toString(containerId); @@ -189,8 +195,10 @@ public int launchContainer(Container container, .toString(Commands.LAUNCH_CONTAINER.getValue()), appId, containerIdStr, containerWorkDir.toString(), nmPrivateCotainerScriptPath.toUri().getPath().toString(), - nmPrivateTokensPath.toUri().getPath().toString(), pidFilePath - .toString())); + nmPrivateTokensPath.toUri().getPath().toString(), + pidFilePath.toString(), + StringUtils.join(",", localDirs), + StringUtils.join(",", logDirs))); String[] commandArray = command.toArray(new String[command.size()]); shExec = new ShellCommandExecutor(commandArray, null, // NM's cwd container.getLaunchContext().getEnvironment()); // sanitized env diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LocalDirsHandlerService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LocalDirsHandlerService.java new file mode 100644 index 0000000000000..1e143f6676498 --- /dev/null +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LocalDirsHandlerService.java @@ -0,0 +1,297 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.nodemanager; + +import java.io.IOException; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.LocalDirAllocator; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.util.StringUtils; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.service.AbstractService; + +/** + * The class which provides functionality of checking the health of the local + * directories of a node. This specifically manages nodemanager-local-dirs and + * nodemanager-log-dirs by periodically checking their health. + */ +public class LocalDirsHandlerService extends AbstractService { + + private static Log LOG = LogFactory.getLog(LocalDirsHandlerService.class); + + /** Timer used to schedule disk health monitoring code execution */ + private Timer dirsHandlerScheduler; + private long diskHealthCheckInterval; + private boolean isDiskHealthCheckerEnabled; + /** + * Minimum fraction of disks to be healthy for the node to be healthy in + * terms of disks. This applies to nm-local-dirs and nm-log-dirs. + */ + private float minNeededHealthyDisksFactor; + + private MonitoringTimerTask monitoringTimerTask; + + /** Local dirs to store localized files in */ + private DirectoryCollection localDirs = null; + + /** storage for container logs*/ + private DirectoryCollection logDirs = null; + + /** + * Everybody should go through this LocalDirAllocator object for read/write + * of any local path corresponding to {@link YarnConfiguration#NM_LOCAL_DIRS} + * instead of creating his/her own LocalDirAllocator objects + */ + private LocalDirAllocator localDirsAllocator; + /** + * Everybody should go through this LocalDirAllocator object for read/write + * of any local path corresponding to {@link YarnConfiguration#NM_LOG_DIRS} + * instead of creating his/her own LocalDirAllocator objects + */ + private LocalDirAllocator logDirsAllocator; + + /** when disk health checking code was last run */ + private long lastDisksCheckTime; + + /** + * Class which is used by the {@link Timer} class to periodically execute the + * disks' health checker code. + */ + private final class MonitoringTimerTask extends TimerTask { + + public MonitoringTimerTask(Configuration conf) { + localDirs = new DirectoryCollection( + conf.getTrimmedStrings(YarnConfiguration.NM_LOCAL_DIRS)); + logDirs = new DirectoryCollection( + conf.getTrimmedStrings(YarnConfiguration.NM_LOG_DIRS)); + localDirsAllocator = + new LocalDirAllocator(YarnConfiguration.NM_LOCAL_DIRS); + logDirsAllocator = new LocalDirAllocator(YarnConfiguration.NM_LOG_DIRS); + } + + @Override + public void run() { + boolean newFailure = false; + if (localDirs.checkDirs()) { + newFailure = true; + } + if (logDirs.checkDirs()) { + newFailure = true; + } + + if (newFailure) { + LOG.info("Disk(s) failed. " + getDisksHealthReport()); + updateDirsInConfiguration(); + if (!areDisksHealthy()) { + // Just log. + LOG.error("Most of the disks failed. " + getDisksHealthReport()); + } + } + lastDisksCheckTime = System.currentTimeMillis(); + } + } + + public LocalDirsHandlerService() { + super(LocalDirsHandlerService.class.getName()); + } + + /** + * Method which initializes the timertask and its interval time. + */ + @Override + public void init(Configuration config) { + // Clone the configuration as we may do modifications to dirs-list + Configuration conf = new Configuration(config); + diskHealthCheckInterval = conf.getLong( + YarnConfiguration.NM_DISK_HEALTH_CHECK_INTERVAL_MS, + YarnConfiguration.DEFAULT_NM_DISK_HEALTH_CHECK_INTERVAL_MS); + monitoringTimerTask = new MonitoringTimerTask(conf); + isDiskHealthCheckerEnabled = conf.getBoolean( + YarnConfiguration.NM_DISK_HEALTH_CHECK_ENABLE, true); + minNeededHealthyDisksFactor = conf.getFloat( + YarnConfiguration.NM_MIN_HEALTHY_DISKS_FRACTION, + YarnConfiguration.DEFAULT_NM_MIN_HEALTHY_DISKS_FRACTION); + lastDisksCheckTime = System.currentTimeMillis(); + super.init(conf); + } + + /** + * Method used to start the disk health monitoring, if enabled. + */ + @Override + public void start() { + if (isDiskHealthCheckerEnabled) { + dirsHandlerScheduler = new Timer("DiskHealthMonitor-Timer", true); + // Start the timer task for disk health checking immediately and + // then run periodically at interval time. + dirsHandlerScheduler.scheduleAtFixedRate(monitoringTimerTask, 0, + diskHealthCheckInterval); + } + super.start(); + } + + /** + * Method used to terminate the disk health monitoring service. + */ + @Override + public void stop() { + if (dirsHandlerScheduler != null) { + dirsHandlerScheduler.cancel(); + } + super.stop(); + } + + /** + * @return the good/valid local directories based on disks' health + */ + public List<String> getLocalDirs() { + return localDirs.getGoodDirs(); + } + + /** + * @return the good/valid log directories based on disks' health + */ + public List<String> getLogDirs() { + return logDirs.getGoodDirs(); + } + + /** + * @return the health report of nm-local-dirs and nm-log-dirs + */ + public String getDisksHealthReport() { + if (!isDiskHealthCheckerEnabled) { + return ""; + } + + StringBuilder report = new StringBuilder(); + List<String> failedLocalDirsList = localDirs.getFailedDirs(); + List<String> failedLogDirsList = logDirs.getFailedDirs(); + int numLocalDirs = localDirs.getGoodDirs().size() + + failedLocalDirsList.size(); + int numLogDirs = logDirs.getGoodDirs().size() + failedLogDirsList.size(); + if (!failedLocalDirsList.isEmpty()) { + report.append(failedLocalDirsList.size() + "/" + numLocalDirs + + " local-dirs turned bad: " + + StringUtils.join(",", failedLocalDirsList) + ";"); + } + if (!failedLogDirsList.isEmpty()) { + report.append(failedLogDirsList.size() + "/" + numLogDirs + + " log-dirs turned bad: " + + StringUtils.join(",", failedLogDirsList)); + } + return report.toString(); + } + + /** + * The minimum fraction of number of disks needed to be healthy for a node to + * be considered healthy in terms of disks is configured using + * {@link YarnConfiguration#NM_MIN_HEALTHY_DISKS_FRACTION}, with a default + * value of {@link YarnConfiguration#DEFAULT_NM_MIN_HEALTHY_DISKS_FRACTION}. + * @return <em>false</em> if either (a) more than the allowed percentage of + * nm-local-dirs failed or (b) more than the allowed percentage of + * nm-log-dirs failed. + */ + public boolean areDisksHealthy() { + if (!isDiskHealthCheckerEnabled) { + return true; + } + + int goodDirs = getLocalDirs().size(); + int failedDirs = localDirs.getFailedDirs().size(); + int totalConfiguredDirs = goodDirs + failedDirs; + if (goodDirs/(float)totalConfiguredDirs < minNeededHealthyDisksFactor) { + return false; // Not enough healthy local-dirs + } + + goodDirs = getLogDirs().size(); + failedDirs = logDirs.getFailedDirs().size(); + totalConfiguredDirs = goodDirs + failedDirs; + if (goodDirs/(float)totalConfiguredDirs < minNeededHealthyDisksFactor) { + return false; // Not enough healthy log-dirs + } + + return true; + } + + public long getLastDisksCheckTime() { + return lastDisksCheckTime; + } + + /** + * Set good local dirs and good log dirs in the configuration so that the + * LocalDirAllocator objects will use this updated configuration only. + */ + private void updateDirsInConfiguration() { + Configuration conf = getConfig(); + List<String> localDirs = getLocalDirs(); + conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, + localDirs.toArray(new String[localDirs.size()])); + List<String> logDirs = getLogDirs(); + synchronized(conf) { + conf.setStrings(YarnConfiguration.NM_LOG_DIRS, + logDirs.toArray(new String[logDirs.size()])); + } + } + + public Path getLocalPathForWrite(String pathStr) throws IOException { + Configuration conf = getConfig(); + Path path = null; + synchronized (conf) { + path = localDirsAllocator.getLocalPathForWrite(pathStr, conf); + } + return path; + } + + public Path getLocalPathForWrite(String pathStr, long size, + boolean checkWrite) throws IOException { + Configuration conf = getConfig(); + Path path = null; + synchronized (conf) { + path = localDirsAllocator.getLocalPathForWrite(pathStr, size, conf, + checkWrite); + } + return path; + } + + public Path getLogPathForWrite(String pathStr, boolean checkWrite) + throws IOException { + Configuration conf = getConfig(); + Path path = null; + synchronized (conf) { + path = logDirsAllocator.getLocalPathForWrite(pathStr, + LocalDirAllocator.SIZE_UNKNOWN, conf, checkWrite); + } + return path; + } + + public Path getLogPathToRead(String pathStr) throws IOException { + Configuration conf = getConfig(); + Path path = null; + synchronized (conf) { + path = logDirsAllocator.getLocalPathToRead(pathStr, conf); + } + return path; + } +} diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeHealthCheckerService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeHealthCheckerService.java new file mode 100644 index 0000000000000..78e5a53685158 --- /dev/null +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeHealthCheckerService.java @@ -0,0 +1,97 @@ +/** +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.hadoop.yarn.server.nodemanager; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.yarn.service.CompositeService; + +/** + * The class which provides functionality of checking the health of the node and + * reporting back to the service for which the health checker has been asked to + * report. + */ +public class NodeHealthCheckerService extends CompositeService { + + private NodeHealthScriptRunner nodeHealthScriptRunner; + private LocalDirsHandlerService dirsHandler; + + static final String SEPARATOR = ";"; + + public NodeHealthCheckerService() { + super(NodeHealthCheckerService.class.getName()); + dirsHandler = new LocalDirsHandlerService(); + } + + @Override + public void init(Configuration conf) { + if (NodeHealthScriptRunner.shouldRun(conf)) { + nodeHealthScriptRunner = new NodeHealthScriptRunner(); + addService(nodeHealthScriptRunner); + } + addService(dirsHandler); + super.init(conf); + } + + /** + * @return the reporting string of health of the node + */ + String getHealthReport() { + String scriptReport = (nodeHealthScriptRunner == null) ? "" + : nodeHealthScriptRunner.getHealthReport(); + if (scriptReport.equals("")) { + return dirsHandler.getDisksHealthReport(); + } else { + return scriptReport.concat(SEPARATOR + dirsHandler.getDisksHealthReport()); + } + } + + /** + * @return <em>true</em> if the node is healthy + */ + boolean isHealthy() { + boolean scriptHealthStatus = (nodeHealthScriptRunner == null) ? true + : nodeHealthScriptRunner.isHealthy(); + return scriptHealthStatus && dirsHandler.areDisksHealthy(); + } + + /** + * @return when the last time the node health status is reported + */ + long getLastHealthReportTime() { + long diskCheckTime = dirsHandler.getLastDisksCheckTime(); + long lastReportTime = (nodeHealthScriptRunner == null) + ? diskCheckTime + : Math.max(nodeHealthScriptRunner.getLastReportedTime(), diskCheckTime); + return lastReportTime; + } + + /** + * @return the disk handler + */ + public LocalDirsHandlerService getDiskHandler() { + return dirsHandler; + } + + /** + * @return the node health script runner + */ + NodeHealthScriptRunner getNodeHealthScriptRunner() { + return nodeHealthScriptRunner; + } +} diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/NodeHealthCheckerService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeHealthScriptRunner.java similarity index 88% rename from hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/NodeHealthCheckerService.java rename to hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeHealthScriptRunner.java index b02e8b13ad5dc..0898bb284c214 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/NodeHealthCheckerService.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeHealthScriptRunner.java @@ -16,7 +16,7 @@ * limitations under the License. */ -package org.apache.hadoop; +package org.apache.hadoop.yarn.server.nodemanager; import java.io.File; import java.io.IOException; @@ -31,19 +31,18 @@ import org.apache.hadoop.util.Shell.ExitCodeException; import org.apache.hadoop.util.Shell.ShellCommandExecutor; import org.apache.hadoop.util.StringUtils; -import org.apache.hadoop.yarn.api.records.NodeHealthStatus; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.service.AbstractService; /** * - * The class which provides functionality of checking the health of the node and - * reporting back to the service for which the health checker has been asked to - * report. + * The class which provides functionality of checking the health of the node + * using the configured node health script and reporting back to the service + * for which the health checker has been asked to report. */ -public class NodeHealthCheckerService extends AbstractService { +public class NodeHealthScriptRunner extends AbstractService { - private static Log LOG = LogFactory.getLog(NodeHealthCheckerService.class); + private static Log LOG = LogFactory.getLog(NodeHealthScriptRunner.class); /** Absolute path to the health script. */ private String nodeHealthScript; @@ -74,7 +73,6 @@ public class NodeHealthCheckerService extends AbstractService { private TimerTask timer; - private enum HealthCheckerExitStatus { SUCCESS, TIMED_OUT, @@ -187,18 +185,13 @@ private boolean hasErrors(String output) { } } - public NodeHealthCheckerService() { - super(NodeHealthCheckerService.class.getName()); + public NodeHealthScriptRunner() { + super(NodeHealthScriptRunner.class.getName()); this.lastReportedTime = System.currentTimeMillis(); this.isHealthy = true; this.healthReport = ""; } - public NodeHealthCheckerService(Configuration conf) { - this(); - init(conf); - } - /* * Method which initializes the values for the script path and interval time. */ @@ -257,12 +250,12 @@ public void stop() { * * @return true if node is healthy */ - private boolean isHealthy() { + public boolean isHealthy() { return isHealthy; } /** - * Sets if the node is healhty or not. + * Sets if the node is healhty or not considering disks' health also. * * @param isHealthy * if or not node is healthy @@ -277,13 +270,14 @@ private synchronized void setHealthy(boolean isHealthy) { * * @return output from health script */ - private String getHealthReport() { + public String getHealthReport() { return healthReport; } /** - * Sets the health report from the node health script. - * + * Sets the health report from the node health script. Also set the disks' + * health info obtained from DiskHealthCheckerService. + * * @param healthReport */ private synchronized void setHealthReport(String healthReport) { @@ -295,7 +289,7 @@ private synchronized void setHealthReport(String healthReport) { * * @return timestamp when node health script was last run */ - private long getLastReportedTime() { + public long getLastReportedTime() { return lastReportedTime; } @@ -340,27 +334,12 @@ private synchronized void setHealthStatus(boolean isHealthy, String output, this.setHealthStatus(isHealthy, output); this.setLastReportedTime(time); } - - /** - * Method to populate the fields for the {@link NodeHealthStatus} - * - * @param healthStatus - */ - public synchronized void setHealthStatus(NodeHealthStatus healthStatus) { - healthStatus.setIsNodeHealthy(this.isHealthy()); - healthStatus.setHealthReport(this.getHealthReport()); - healthStatus.setLastHealthReportTime(this.getLastReportedTime()); - } - + /** - * Test method to directly access the timer which node - * health checker would use. - * - * - * @return Timer task + * Used only by tests to access the timer task directly + * @return the timer task */ - //XXX:Not to be used directly. - TimerTask getTimer() { + TimerTask getTimerTask() { return timer; } } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java index 94971d365e73f..439b5e37a5740 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java @@ -25,7 +25,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.hadoop.NodeHealthCheckerService; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.security.SecurityUtil; @@ -59,6 +58,8 @@ public class NodeManager extends CompositeService implements protected final NodeManagerMetrics metrics = NodeManagerMetrics.create(); protected ContainerTokenSecretManager containerTokenSecretManager; private ApplicationACLsManager aclsManager; + private NodeHealthCheckerService nodeHealthChecker; + private LocalDirsHandlerService dirsHandler; public NodeManager() { super(NodeManager.class.getName()); @@ -78,14 +79,16 @@ protected NodeResourceMonitor createNodeResourceMonitor() { protected ContainerManagerImpl createContainerManager(Context context, ContainerExecutor exec, DeletionService del, NodeStatusUpdater nodeStatusUpdater, ContainerTokenSecretManager - containerTokenSecretManager, ApplicationACLsManager aclsManager) { + containerTokenSecretManager, ApplicationACLsManager aclsManager, + LocalDirsHandlerService dirsHandler) { return new ContainerManagerImpl(context, exec, del, nodeStatusUpdater, - metrics, containerTokenSecretManager, aclsManager); + metrics, containerTokenSecretManager, aclsManager, dirsHandler); } protected WebServer createWebServer(Context nmContext, - ResourceView resourceView, ApplicationACLsManager aclsManager) { - return new WebServer(nmContext, resourceView, aclsManager); + ResourceView resourceView, ApplicationACLsManager aclsManager, + LocalDirsHandlerService dirsHandler) { + return new WebServer(nmContext, resourceView, aclsManager, dirsHandler); } protected void doSecureLogin() throws IOException { @@ -121,16 +124,12 @@ public void init(Configuration conf) { // NodeManager level dispatcher AsyncDispatcher dispatcher = new AsyncDispatcher(); - NodeHealthCheckerService healthChecker = null; - if (NodeHealthCheckerService.shouldRun(conf)) { - healthChecker = new NodeHealthCheckerService(); - addService(healthChecker); - } + nodeHealthChecker = new NodeHealthCheckerService(); + addService(nodeHealthChecker); + dirsHandler = nodeHealthChecker.getDiskHandler(); - NodeStatusUpdater nodeStatusUpdater = - createNodeStatusUpdater(context, dispatcher, healthChecker, - this.containerTokenSecretManager); - + NodeStatusUpdater nodeStatusUpdater = createNodeStatusUpdater(context, + dispatcher, nodeHealthChecker, this.containerTokenSecretManager); nodeStatusUpdater.register(this); NodeResourceMonitor nodeResourceMonitor = createNodeResourceMonitor(); @@ -138,11 +137,11 @@ public void init(Configuration conf) { ContainerManagerImpl containerManager = createContainerManager(context, exec, del, nodeStatusUpdater, - this.containerTokenSecretManager, this.aclsManager); + this.containerTokenSecretManager, this.aclsManager, dirsHandler); addService(containerManager); Service webServer = createWebServer(context, containerManager - .getContainersMonitor(), this.aclsManager); + .getContainersMonitor(), this.aclsManager, dirsHandler); addService(webServer); dispatcher.register(ContainerManagerEventType.class, containerManager); @@ -215,7 +214,14 @@ public NodeHealthStatus getNodeHealthStatus() { } } - + + /** + * @return the node health checker + */ + public NodeHealthCheckerService getNodeHealthChecker() { + return nodeHealthChecker; + } + @Override public void stateChanged(Service service) { // Shutdown the Nodemanager when the NodeStatusUpdater is stopped. diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java index 94396088cac2f..6da70f150233f 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java @@ -27,7 +27,6 @@ import org.apache.avro.AvroRuntimeException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.hadoop.NodeHealthCheckerService; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.UserGroupInformation; @@ -222,11 +221,14 @@ private NodeStatus getNodeStatus() { + numActiveContainers + " containers"); NodeHealthStatus nodeHealthStatus = this.context.getNodeHealthStatus(); - if (this.healthChecker != null) { - this.healthChecker.setHealthStatus(nodeHealthStatus); + nodeHealthStatus.setHealthReport(healthChecker.getHealthReport()); + nodeHealthStatus.setIsNodeHealthy(healthChecker.isHealthy()); + nodeHealthStatus.setLastHealthReportTime( + healthChecker.getLastHealthReportTime()); + if (LOG.isDebugEnabled()) { + LOG.debug("Node's health-status : " + nodeHealthStatus.getIsNodeHealthy() + + ", " + nodeHealthStatus.getHealthReport()); } - LOG.debug("Node's health-status : " + nodeHealthStatus.getIsNodeHealthy() - + ", " + nodeHealthStatus.getHealthReport()); nodeStatus.setNodeHealthStatus(nodeHealthStatus); return nodeStatus; diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java index 5e3eb26cb5dbe..615b825c4f377 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java @@ -68,6 +68,7 @@ import org.apache.hadoop.yarn.server.nodemanager.ContainerManagerEvent; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.NMAuditLogger; import org.apache.hadoop.yarn.server.nodemanager.NMAuditLogger.AuditConstants; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater; @@ -120,7 +121,8 @@ public class ContainerManagerImpl extends CompositeService implements private ContainerTokenSecretManager containerTokenSecretManager; private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); - + + protected LocalDirsHandlerService dirsHandler; protected final AsyncDispatcher dispatcher; private final ApplicationACLsManager aclsManager; @@ -129,9 +131,12 @@ public class ContainerManagerImpl extends CompositeService implements public ContainerManagerImpl(Context context, ContainerExecutor exec, DeletionService deletionContext, NodeStatusUpdater nodeStatusUpdater, NodeManagerMetrics metrics, ContainerTokenSecretManager - containerTokenSecretManager, ApplicationACLsManager aclsManager) { + containerTokenSecretManager, ApplicationACLsManager aclsManager, + LocalDirsHandlerService dirsHandler) { super(ContainerManagerImpl.class.getName()); this.context = context; + this.dirsHandler = dirsHandler; + dispatcher = new AsyncDispatcher(); this.deletionService = deletionContext; this.metrics = metrics; @@ -190,9 +195,10 @@ protected LogHandler createLogHandler(Configuration conf, Context context, if (conf.getBoolean(YarnConfiguration.NM_LOG_AGGREGATION_ENABLED, YarnConfiguration.DEFAULT_NM_LOG_AGGREGATION_ENABLED)) { return new LogAggregationService(this.dispatcher, context, - deletionService); + deletionService, dirsHandler); } else { - return new NonAggregatingLogHandler(this.dispatcher, deletionService); + return new NonAggregatingLogHandler(this.dispatcher, deletionService, + dirsHandler); } } @@ -203,12 +209,12 @@ public ContainersMonitor getContainersMonitor() { protected ResourceLocalizationService createResourceLocalizationService( ContainerExecutor exec, DeletionService deletionContext) { return new ResourceLocalizationService(this.dispatcher, exec, - deletionContext); + deletionContext, dirsHandler); } protected ContainersLauncher createContainersLauncher(Context context, ContainerExecutor exec) { - return new ContainersLauncher(context, this.dispatcher, exec); + return new ContainersLauncher(context, this.dispatcher, exec, dirsHandler); } @Override diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerExitEvent.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerExitEvent.java index b9416886f691e..7a2fc2f41626a 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerExitEvent.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerExitEvent.java @@ -22,14 +22,20 @@ public class ContainerExitEvent extends ContainerEvent { private int exitCode; + private final String diagnosticInfo; public ContainerExitEvent(ContainerId cID, ContainerEventType eventType, - int exitCode) { + int exitCode, String diagnosticInfo) { super(cID, eventType); this.exitCode = exitCode; + this.diagnosticInfo = diagnosticInfo; } public int getExitCode() { return this.exitCode; } + + public String getDiagnosticInfo() { + return diagnosticInfo; + } } diff --git a/hadoop-mapreduce-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-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java index f7fd522f811ab..15de5d2749b0b 100644 --- a/hadoop-mapreduce-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-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java @@ -50,6 +50,7 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.DelayedProcessKiller; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.ExitCode; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.Signal; @@ -78,7 +79,6 @@ public class ContainerLaunch implements Callable<Integer> { private final Application app; private final Container container; private final Configuration conf; - private final LocalDirAllocator logDirsSelector; private volatile AtomicBoolean shouldLaunchContainer = new AtomicBoolean(false); private volatile AtomicBoolean completed = new AtomicBoolean(false); @@ -88,14 +88,17 @@ public class ContainerLaunch implements Callable<Integer> { private Path pidFilePath = null; + private final LocalDirsHandlerService dirsHandler; + public ContainerLaunch(Configuration configuration, Dispatcher dispatcher, - ContainerExecutor exec, Application app, Container container) { + ContainerExecutor exec, Application app, Container container, + LocalDirsHandlerService dirsHandler) { this.conf = configuration; this.app = app; this.exec = exec; this.container = container; this.dispatcher = dispatcher; - this.logDirsSelector = new LocalDirAllocator(YarnConfiguration.NM_LOG_DIRS); + this.dirsHandler = dirsHandler; this.sleepDelayBeforeSigKill = conf.getLong(YarnConfiguration.NM_SLEEP_DELAY_BEFORE_SIGKILL_MS, YarnConfiguration.DEFAULT_NM_SLEEP_DELAY_BEFORE_SIGKILL_MS); @@ -121,9 +124,8 @@ public Integer call() { List<String> newCmds = new ArrayList<String>(command.size()); String appIdStr = app.getAppId().toString(); Path containerLogDir = - this.logDirsSelector.getLocalPathForWrite(ContainerLaunch - .getRelativeContainerLogDir(appIdStr, containerIdStr), - LocalDirAllocator.SIZE_UNKNOWN, this.conf, false); + dirsHandler.getLogPathForWrite(ContainerLaunch + .getRelativeContainerLogDir(appIdStr, containerIdStr), false); for (String str : command) { // TODO: Should we instead work via symlinks without this grammar? newCmds.add(str.replace(ApplicationConstants.LOG_DIR_EXPANSION_VAR, @@ -144,47 +146,49 @@ public Integer call() { // /////////////////////////// End of variable expansion FileContext lfs = FileContext.getLocalFSFileContext(); - LocalDirAllocator lDirAllocator = - new LocalDirAllocator(YarnConfiguration.NM_LOCAL_DIRS); // TODO Path nmPrivateContainerScriptPath = - lDirAllocator.getLocalPathForWrite( + dirsHandler.getLocalPathForWrite( getContainerPrivateDir(appIdStr, containerIdStr) + Path.SEPARATOR - + CONTAINER_SCRIPT, this.conf); + + CONTAINER_SCRIPT); Path nmPrivateTokensPath = - lDirAllocator.getLocalPathForWrite( + dirsHandler.getLocalPathForWrite( getContainerPrivateDir(appIdStr, containerIdStr) + Path.SEPARATOR + String.format(ContainerLocalizer.TOKEN_FILE_NAME_FMT, - containerIdStr), this.conf); + containerIdStr)); DataOutputStream containerScriptOutStream = null; DataOutputStream tokensOutStream = null; // Select the working directory for the container Path containerWorkDir = - lDirAllocator.getLocalPathForWrite(ContainerLocalizer.USERCACHE + dirsHandler.getLocalPathForWrite(ContainerLocalizer.USERCACHE + Path.SEPARATOR + user + Path.SEPARATOR + ContainerLocalizer.APPCACHE + Path.SEPARATOR + appIdStr + Path.SEPARATOR + containerIdStr, - LocalDirAllocator.SIZE_UNKNOWN, this.conf, false); + LocalDirAllocator.SIZE_UNKNOWN, false); String pidFileSuffix = String.format(ContainerLaunch.PID_FILE_NAME_FMT, containerIdStr); // pid file should be in nm private dir so that it is not // accessible by users - pidFilePath = lDirAllocator.getLocalPathForWrite( + pidFilePath = dirsHandler.getLocalPathForWrite( ResourceLocalizationService.NM_PRIVATE_DIR + Path.SEPARATOR - + pidFileSuffix, - this.conf); + + pidFileSuffix); + List<String> localDirs = dirsHandler.getLocalDirs(); + List<String> logDirs = dirsHandler.getLogDirs(); + + if (!dirsHandler.areDisksHealthy()) { + ret = ExitCode.DISKS_FAILED.getExitCode(); + throw new IOException("Most of the disks failed. " + + dirsHandler.getDisksHealthReport()); + } try { // /////////// Write out the container-script in the nmPrivate space. - String[] localDirs = - this.conf.getStrings(YarnConfiguration.NM_LOCAL_DIRS, - YarnConfiguration.DEFAULT_NM_LOCAL_DIRS); - List<Path> appDirs = new ArrayList<Path>(localDirs.length); + List<Path> appDirs = new ArrayList<Path>(localDirs.size()); for (String localDir : localDirs) { Path usersdir = new Path(localDir, ContainerLocalizer.USERCACHE); Path userdir = new Path(usersdir, user); @@ -234,30 +238,34 @@ public Integer call() { } else { exec.activateContainer(containerID, pidFilePath); - ret = - exec.launchContainer(container, nmPrivateContainerScriptPath, - nmPrivateTokensPath, user, appIdStr, containerWorkDir); + ret = exec.launchContainer(container, nmPrivateContainerScriptPath, + nmPrivateTokensPath, user, appIdStr, containerWorkDir, + localDirs, logDirs); } } catch (Throwable e) { - LOG.warn("Failed to launch container", e); + LOG.warn("Failed to launch container.", e); dispatcher.getEventHandler().handle(new ContainerExitEvent( launchContext.getContainerId(), - ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, ret)); + ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, ret, + e.getMessage())); return ret; } finally { completed.set(true); exec.deactivateContainer(containerID); } - LOG.debug("Container " + containerIdStr + " completed with exit code " - + ret); + if (LOG.isDebugEnabled()) { + LOG.debug("Container " + containerIdStr + " completed with exit code " + + ret); + } if (ret == ExitCode.FORCE_KILLED.getExitCode() || ret == ExitCode.TERMINATED.getExitCode()) { // If the process was killed, Send container_cleanedup_after_kill and // just break out of this method. dispatcher.getEventHandler().handle( new ContainerExitEvent(launchContext.getContainerId(), - ContainerEventType.CONTAINER_KILLED_ON_REQUEST, ret)); + ContainerEventType.CONTAINER_KILLED_ON_REQUEST, ret, + "Container exited with a non-zero exit code " + ret)); return ret; } @@ -265,7 +273,8 @@ public Integer call() { LOG.warn("Container exited with a non-zero exit code " + ret); this.dispatcher.getEventHandler().handle(new ContainerExitEvent( launchContext.getContainerId(), - ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, ret)); + ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, ret, + "Container exited with a non-zero exit code " + ret)); return ret; } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainersLauncher.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainersLauncher.java index 8f8bfc76885ae..1e3c18b971e9b 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainersLauncher.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainersLauncher.java @@ -33,10 +33,10 @@ import org.apache.hadoop.fs.UnsupportedFileSystemException; import org.apache.hadoop.yarn.YarnException; import org.apache.hadoop.yarn.api.records.ContainerId; -import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; @@ -59,6 +59,8 @@ public class ContainersLauncher extends AbstractService private final Context context; private final ContainerExecutor exec; private final Dispatcher dispatcher; + + private LocalDirsHandlerService dirsHandler; private final ExecutorService containerLauncher = Executors.newCachedThreadPool( new ThreadFactoryBuilder() @@ -80,11 +82,12 @@ public RunningContainer(Future<Integer> submit, public ContainersLauncher(Context context, Dispatcher dispatcher, - ContainerExecutor exec) { + ContainerExecutor exec, LocalDirsHandlerService dirsHandler) { super("containers-launcher"); this.exec = exec; this.context = context; this.dispatcher = dispatcher; + this.dirsHandler = dirsHandler; } @Override @@ -114,15 +117,19 @@ public void handle(ContainersLauncherEvent event) { Application app = context.getApplications().get( containerId.getApplicationAttemptId().getApplicationId()); - ContainerLaunch launch = - new ContainerLaunch(getConfig(), dispatcher, exec, app, - event.getContainer()); + + ContainerLaunch launch = new ContainerLaunch(getConfig(), dispatcher, + exec, app, event.getContainer(), dirsHandler); running.put(containerId, new RunningContainer(containerLauncher.submit(launch), launch)); break; case CLEANUP_CONTAINER: RunningContainer rContainerDatum = running.remove(containerId); + if (rContainerDatum == null) { + // Container not launched. So nothing needs to be done. + return; + } Future<Integer> rContainer = rContainerDatum.runningcontainer; if (rContainer != null && !rContainer.isDone()) { diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ContainerLocalizer.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ContainerLocalizer.java index 392128733fbef..4e03fa2a5a185 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ContainerLocalizer.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ContainerLocalizer.java @@ -45,12 +45,10 @@ import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.Credentials; -import org.apache.hadoop.security.SecurityInfo; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.records.LocalResource; -import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnRemoteException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; @@ -61,7 +59,6 @@ import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.ResourceStatusType; -import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.security.LocalizerSecurityInfo; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.security.LocalizerTokenIdentifier; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.security.LocalizerTokenSecretManager; import org.apache.hadoop.yarn.util.ConverterUtils; @@ -186,16 +183,30 @@ ExecutorService createDownloadThreadPool() { } Callable<Path> download(LocalDirAllocator lda, LocalResource rsrc, - UserGroupInformation ugi) { - return new FSDownload(lfs, ugi, conf, lda, rsrc, new Random()); + UserGroupInformation ugi) throws IOException { + Path destPath = lda.getLocalPathForWrite(".", getEstimatedSize(rsrc), conf); + return new FSDownload(lfs, ugi, conf, destPath, rsrc, new Random()); + } + + static long getEstimatedSize(LocalResource rsrc) { + if (rsrc.getSize() < 0) { + return -1; + } + switch (rsrc.getType()) { + case ARCHIVE: + return 5 * rsrc.getSize(); + case FILE: + default: + return rsrc.getSize(); + } } void sleep(int duration) throws InterruptedException { TimeUnit.SECONDS.sleep(duration); } - private void localizeFiles(LocalizationProtocol nodemanager, ExecutorService exec, - UserGroupInformation ugi) { + private void localizeFiles(LocalizationProtocol nodemanager, + ExecutorService exec, UserGroupInformation ugi) throws IOException { while (true) { try { LocalizerStatus status = createStatus(); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java index 9ec83cdbc5553..744c2b1990098 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java @@ -57,7 +57,6 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -68,7 +67,6 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.fs.FileContext; -import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.net.NetUtils; @@ -81,6 +79,7 @@ import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.api.LocalizationProtocol; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalResourceStatus; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerAction; @@ -125,19 +124,18 @@ public class ResourceLocalizationService extends CompositeService private InetSocketAddress localizationServerAddress; private long cacheTargetSize; private long cacheCleanupPeriod; - private List<Path> logDirs; - private List<Path> localDirs; - private List<Path> sysDirs; + private final ContainerExecutor exec; protected final Dispatcher dispatcher; private final DeletionService delService; private LocalizerTracker localizerTracker; private RecordFactory recordFactory; - private final LocalDirAllocator localDirsSelector; private final ScheduledExecutorService cacheCleanup; private final LocalResourcesTracker publicRsrc; - + + private LocalDirsHandlerService dirsHandler; + /** * Map of LocalResourceTrackers keyed by username, for private * resources. @@ -153,12 +151,15 @@ public class ResourceLocalizationService extends CompositeService new ConcurrentHashMap<String,LocalResourcesTracker>(); public ResourceLocalizationService(Dispatcher dispatcher, - ContainerExecutor exec, DeletionService delService) { + ContainerExecutor exec, DeletionService delService, + LocalDirsHandlerService dirsHandler) { + super(ResourceLocalizationService.class.getName()); this.exec = exec; this.dispatcher = dispatcher; this.delService = delService; - this.localDirsSelector = new LocalDirAllocator(YarnConfiguration.NM_LOCAL_DIRS); + this.dirsHandler = dirsHandler; + this.publicRsrc = new LocalResourcesTrackerImpl(null, dispatcher); this.cacheCleanup = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder() @@ -177,41 +178,31 @@ FileContext getLocalFileContext(Configuration conf) { @Override public void init(Configuration conf) { this.recordFactory = RecordFactoryProvider.getRecordFactory(conf); + try { // TODO queue deletions here, rather than NM init? FileContext lfs = getLocalFileContext(conf); - String[] sLocalDirs = - conf.getStrings(YarnConfiguration.NM_LOCAL_DIRS, YarnConfiguration.DEFAULT_NM_LOCAL_DIRS); - - localDirs = new ArrayList<Path>(sLocalDirs.length); - logDirs = new ArrayList<Path>(sLocalDirs.length); - sysDirs = new ArrayList<Path>(sLocalDirs.length); - for (String sLocaldir : sLocalDirs) { - Path localdir = new Path(sLocaldir); - localDirs.add(localdir); + List<String> localDirs = dirsHandler.getLocalDirs(); + for (String localDir : localDirs) { // $local/usercache - Path userdir = new Path(localdir, ContainerLocalizer.USERCACHE); - lfs.mkdir(userdir, null, true); + Path userDir = new Path(localDir, ContainerLocalizer.USERCACHE); + lfs.mkdir(userDir, null, true); // $local/filecache - Path filedir = new Path(localdir, ContainerLocalizer.FILECACHE); - lfs.mkdir(filedir, null, true); + Path fileDir = new Path(localDir, ContainerLocalizer.FILECACHE); + lfs.mkdir(fileDir, null, true); // $local/nmPrivate - Path sysdir = new Path(localdir, NM_PRIVATE_DIR); - lfs.mkdir(sysdir, NM_PRIVATE_PERM, true); - sysDirs.add(sysdir); + Path sysDir = new Path(localDir, NM_PRIVATE_DIR); + lfs.mkdir(sysDir, NM_PRIVATE_PERM, true); } - String[] sLogdirs = conf.getStrings(YarnConfiguration.NM_LOG_DIRS, YarnConfiguration.DEFAULT_NM_LOG_DIRS); - for (String sLogdir : sLogdirs) { - Path logdir = new Path(sLogdir); - logDirs.add(logdir); - lfs.mkdir(logdir, null, true); + + List<String> logDirs = dirsHandler.getLogDirs(); + for (String logDir : logDirs) { + lfs.mkdir(new Path(logDir), null, true); } } catch (IOException e) { throw new YarnException("Failed to initialize LocalizationService", e); } - localDirs = Collections.unmodifiableList(localDirs); - logDirs = Collections.unmodifiableList(logDirs); - sysDirs = Collections.unmodifiableList(sysDirs); + cacheTargetSize = conf.getLong(YarnConfiguration.NM_LOCALIZER_CACHE_TARGET_SIZE_MB, YarnConfiguration.DEFAULT_NM_LOCALIZER_CACHE_TARGET_SIZE_MB) << 20; cacheCleanupPeriod = @@ -391,7 +382,7 @@ private void handleCleanupContainerResources( String containerIDStr = c.toString(); String appIDStr = ConverterUtils.toString( c.getContainerID().getApplicationAttemptId().getApplicationId()); - for (Path localDir : localDirs) { + for (String localDir : dirsHandler.getLocalDirs()) { // Delete the user-owned container-dir Path usersdir = new Path(localDir, ContainerLocalizer.USERCACHE); @@ -428,7 +419,7 @@ private void handleDestroyApplicationResources(Application application) { // Delete the application directories userName = application.getUser(); appIDStr = application.toString(); - for (Path localDir : localDirs) { + for (String localDir : dirsHandler.getLocalDirs()) { // Delete the user-owned app-dir Path usersdir = new Path(localDir, ContainerLocalizer.USERCACHE); @@ -574,12 +565,9 @@ private static ExecutorService createLocalizerExecutor(Configuration conf) { class PublicLocalizer extends Thread { - static final String PUBCACHE_CTXT = "public.cache.dirs"; - final FileContext lfs; final Configuration conf; final ExecutorService threadPool; - final LocalDirAllocator publicDirs; final CompletionService<Path> queue; final Map<Future<Path>,LocalizerResourceRequestEvent> pending; // TODO hack to work around broken signaling @@ -601,13 +589,23 @@ class PublicLocalizer extends Thread { this.conf = conf; this.pending = pending; this.attempts = attempts; - String[] publicFilecache = new String[localDirs.size()]; - for (int i = 0, n = localDirs.size(); i < n; ++i) { - publicFilecache[i] = - new Path(localDirs.get(i), ContainerLocalizer.FILECACHE).toString(); - } - conf.setStrings(PUBCACHE_CTXT, publicFilecache); - this.publicDirs = new LocalDirAllocator(PUBCACHE_CTXT); +// List<String> localDirs = dirsHandler.getLocalDirs(); +// String[] publicFilecache = new String[localDirs.size()]; +// for (int i = 0, n = localDirs.size(); i < n; ++i) { +// publicFilecache[i] = +// new Path(localDirs.get(i), ContainerLocalizer.FILECACHE).toString(); +// } +// conf.setStrings(PUBCACHE_CTXT, publicFilecache); + +// this.publicDirDestPath = new LocalDirAllocator(PUBCACHE_CTXT).getLocalPathForWrite(pathStr, conf); +// List<String> localDirs = dirsHandler.getLocalDirs(); +// String[] publicFilecache = new String[localDirs.size()]; +// int i = 0; +// for (String localDir : localDirs) { +// publicFilecache[i++] = +// new Path(localDir, ContainerLocalizer.FILECACHE).toString(); +// } + this.threadPool = threadPool; this.queue = new ExecutorCompletionService<Path>(threadPool); } @@ -619,11 +617,19 @@ public void addResource(LocalizerResourceRequestEvent request) { synchronized (attempts) { List<LocalizerResourceRequestEvent> sigh = attempts.get(key); if (null == sigh) { - pending.put(queue.submit(new FSDownload( - lfs, null, conf, publicDirs, - request.getResource().getRequest(), new Random())), - request); - attempts.put(key, new LinkedList<LocalizerResourceRequestEvent>()); + LocalResource resource = request.getResource().getRequest(); + try { + Path publicDirDestPath = dirsHandler.getLocalPathForWrite( + "." + Path.SEPARATOR + ContainerLocalizer.FILECACHE, + ContainerLocalizer.getEstimatedSize(resource), true); + pending.put(queue.submit(new FSDownload( + lfs, null, conf, publicDirDestPath, resource, new Random())), + request); + attempts.put(key, new LinkedList<LocalizerResourceRequestEvent>()); + } catch (IOException e) { + LOG.error("Local path for public localization is not found. " + + " May be disks failed.", e); + } } else { sigh.add(request); } @@ -844,24 +850,30 @@ LocalizerHeartbeatResponse update( public void run() { Path nmPrivateCTokensPath = null; try { - // Use LocalDirAllocator to get nmPrivateDir + // Get nmPrivateDir nmPrivateCTokensPath = - localDirsSelector.getLocalPathForWrite( - NM_PRIVATE_DIR - + Path.SEPARATOR + dirsHandler.getLocalPathForWrite( + NM_PRIVATE_DIR + Path.SEPARATOR + String.format(ContainerLocalizer.TOKEN_FILE_NAME_FMT, - localizerId), getConfig()); + localizerId)); // 0) init queue, etc. // 1) write credentials to private dir writeCredentials(nmPrivateCTokensPath); // 2) exec initApplication and wait - exec.startLocalizer(nmPrivateCTokensPath, localizationServerAddress, - context.getUser(), - ConverterUtils.toString( - context.getContainerId(). - getApplicationAttemptId().getApplicationId()), - localizerId, localDirs); + List<String> localDirs = dirsHandler.getLocalDirs(); + List<String> logDirs = dirsHandler.getLogDirs(); + if (dirsHandler.areDisksHealthy()) { + exec.startLocalizer(nmPrivateCTokensPath, localizationServerAddress, + context.getUser(), + ConverterUtils.toString( + context.getContainerId(). + getApplicationAttemptId().getApplicationId()), + localizerId, localDirs, logDirs); + } else { + throw new IOException("All disks failed. " + + dirsHandler.getDisksHealthReport()); + } // TODO handle ExitCodeException separately? } catch (Exception e) { LOG.info("Localizer failed", e); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java index c41162bbec05e..5cfcc0d2ea110 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.security.PrivilegedExceptionAction; +import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -31,6 +32,7 @@ import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ContainerId; @@ -40,10 +42,12 @@ import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogValue; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType; import org.apache.hadoop.yarn.util.ConverterUtils; + public class AppLogAggregatorImpl implements AppLogAggregator { private static final Log LOG = LogFactory @@ -51,6 +55,7 @@ public class AppLogAggregatorImpl implements AppLogAggregator { private static final int THREAD_SLEEP_TIME = 1000; private static final String TMP_FILE_SUFFIX = ".tmp"; + private final LocalDirsHandlerService dirsHandler; private final Dispatcher dispatcher; private final ApplicationId appId; private final String applicationId; @@ -58,7 +63,6 @@ public class AppLogAggregatorImpl implements AppLogAggregator { private final Configuration conf; private final DeletionService delService; private final UserGroupInformation userUgi; - private final String[] rootLogDirs; private final Path remoteNodeLogFileForApp; private final Path remoteNodeTmpLogFileForApp; private final ContainerLogsRetentionPolicy retentionPolicy; @@ -72,7 +76,7 @@ public class AppLogAggregatorImpl implements AppLogAggregator { public AppLogAggregatorImpl(Dispatcher dispatcher, DeletionService deletionService, Configuration conf, ApplicationId appId, - UserGroupInformation userUgi, String[] localRootLogDirs, + UserGroupInformation userUgi, LocalDirsHandlerService dirsHandler, Path remoteNodeLogFileForApp, ContainerLogsRetentionPolicy retentionPolicy, Map<ApplicationAccessType, String> appAcls) { @@ -82,7 +86,7 @@ public AppLogAggregatorImpl(Dispatcher dispatcher, this.appId = appId; this.applicationId = ConverterUtils.toString(appId); this.userUgi = userUgi; - this.rootLogDirs = localRootLogDirs; + this.dirsHandler = dirsHandler; this.remoteNodeLogFileForApp = remoteNodeLogFileForApp; this.remoteNodeTmpLogFileForApp = getRemoteNodeTmpLogFileForApp(); this.retentionPolicy = retentionPolicy; @@ -115,9 +119,11 @@ private void uploadLogsForContainer(ContainerId containerId) { } } - LOG.info("Uploading logs for container " + containerId); + LOG.info("Uploading logs for container " + containerId + + ". Current good log dirs are " + + StringUtils.join(",", dirsHandler.getLogDirs())); LogKey logKey = new LogKey(containerId); - LogValue logValue = new LogValue(this.rootLogDirs, containerId); + LogValue logValue = new LogValue(dirsHandler.getLogDirs(), containerId); try { this.writer.append(logKey, logValue); } catch (IOException e) { @@ -150,9 +156,10 @@ public void run() { } // Remove the local app-log-dirs - Path[] localAppLogDirs = new Path[this.rootLogDirs.length]; + List<String> rootLogDirs = dirsHandler.getLogDirs(); + Path[] localAppLogDirs = new Path[rootLogDirs.size()]; int index = 0; - for (String rootLogDir : this.rootLogDirs) { + for (String rootLogDir : rootLogDirs) { localAppLogDirs[index] = new Path(rootLogDir, this.applicationId); index++; } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/LogAggregationService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/LogAggregationService.java index 95885d4e07e9d..173bc95943a2c 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/LogAggregationService.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/LogAggregationService.java @@ -47,6 +47,7 @@ import org.apache.hadoop.yarn.logaggregation.LogAggregationUtils; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.LogHandler; import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppFinishedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppStartedEvent; @@ -85,7 +86,7 @@ public class LogAggregationService extends AbstractService implements private final DeletionService deletionService; private final Dispatcher dispatcher; - private String[] localRootLogDirs; + private LocalDirsHandlerService dirsHandler; Path remoteRootLogDir; String remoteRootLogDirSuffix; private NodeId nodeId; @@ -95,11 +96,12 @@ public class LogAggregationService extends AbstractService implements private final ExecutorService threadPool; public LogAggregationService(Dispatcher dispatcher, Context context, - DeletionService deletionService) { + DeletionService deletionService, LocalDirsHandlerService dirsHandler) { super(LogAggregationService.class.getName()); this.dispatcher = dispatcher; this.context = context; this.deletionService = deletionService; + this.dirsHandler = dirsHandler; this.appLogAggregators = new ConcurrentHashMap<ApplicationId, AppLogAggregator>(); this.threadPool = Executors.newCachedThreadPool( @@ -109,9 +111,6 @@ public LogAggregationService(Dispatcher dispatcher, Context context, } public synchronized void init(Configuration conf) { - this.localRootLogDirs = - conf.getStrings(YarnConfiguration.NM_LOG_DIRS, - YarnConfiguration.DEFAULT_NM_LOG_DIRS); this.remoteRootLogDir = new Path(conf.get(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR)); @@ -291,9 +290,10 @@ private void initApp(final ApplicationId appId, String user, // New application AppLogAggregator appLogAggregator = - new AppLogAggregatorImpl(this.dispatcher, this.deletionService, getConfig(), appId, - userUgi, this.localRootLogDirs, - getRemoteNodeLogFileForApp(appId, user), logRetentionPolicy, appAcls); + new AppLogAggregatorImpl(this.dispatcher, this.deletionService, + getConfig(), appId, userUgi, dirsHandler, + getRemoteNodeLogFileForApp(appId, user), logRetentionPolicy, + appAcls); if (this.appLogAggregators.putIfAbsent(appId, appLogAggregator) != null) { throw new YarnException("Duplicate initApp for " + appId); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/NonAggregatingLogHandler.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/NonAggregatingLogHandler.java index e0f843e245a00..a90912e6885ec 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/NonAggregatingLogHandler.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/NonAggregatingLogHandler.java @@ -17,6 +17,7 @@ */ package org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledThreadPoolExecutor; @@ -31,6 +32,7 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppFinishedEvent; @@ -53,15 +55,16 @@ public class NonAggregatingLogHandler extends AbstractService implements private final DeletionService delService; private final Map<ApplicationId, String> appOwners; - private String[] rootLogDirs; + private final LocalDirsHandlerService dirsHandler; private long deleteDelaySeconds; private ScheduledThreadPoolExecutor sched; public NonAggregatingLogHandler(Dispatcher dispatcher, - DeletionService delService) { + DeletionService delService, LocalDirsHandlerService dirsHandler) { super(NonAggregatingLogHandler.class.getName()); this.dispatcher = dispatcher; this.delService = delService; + this.dirsHandler = dirsHandler; this.appOwners = new ConcurrentHashMap<ApplicationId, String>(); } @@ -70,9 +73,6 @@ public void init(Configuration conf) { // Default 3 hours. this.deleteDelaySeconds = conf.getLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 3 * 60 * 60); - this.rootLogDirs = - conf.getStrings(YarnConfiguration.NM_LOG_DIRS, - YarnConfiguration.DEFAULT_NM_LOG_DIRS); sched = createScheduledThreadPoolExecutor(conf); super.init(conf); } @@ -145,10 +145,11 @@ public LogDeleterRunnable(String user, ApplicationId applicationId) { @Override @SuppressWarnings("unchecked") public void run() { - Path[] localAppLogDirs = - new Path[NonAggregatingLogHandler.this.rootLogDirs.length]; + List<String> rootLogDirs = + NonAggregatingLogHandler.this.dirsHandler.getLogDirs(); + Path[] localAppLogDirs = new Path[rootLogDirs.size()]; int index = 0; - for (String rootLogDir : NonAggregatingLogHandler.this.rootLogDirs) { + for (String rootLogDir : rootLogDirs) { localAppLogDirs[index] = new Path(rootLogDir, applicationId.toString()); index++; } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java index faf0cbc47feae..b39bb33b1e6e4 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java @@ -34,15 +34,14 @@ import java.util.List; import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; -import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.nodemanager.Context; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerState; @@ -87,17 +86,18 @@ protected Class<? extends SubView> content() { public static class ContainersLogsBlock extends HtmlBlock implements YarnWebParams { private final Configuration conf; - private final LocalDirAllocator logsSelector; private final Context nmContext; private final ApplicationACLsManager aclsManager; + private final LocalDirsHandlerService dirsHandler; @Inject public ContainersLogsBlock(Configuration conf, Context context, - ApplicationACLsManager aclsManager) { + ApplicationACLsManager aclsManager, + LocalDirsHandlerService dirsHandler) { this.conf = conf; - this.logsSelector = new LocalDirAllocator(YarnConfiguration.NM_LOG_DIRS); this.nmContext = context; this.aclsManager = aclsManager; + this.dirsHandler = dirsHandler; } @Override @@ -198,11 +198,10 @@ private void printLogs(Block html, ContainerId containerId, File logFile = null; try { logFile = - new File(this.logsSelector - .getLocalPathToRead( - ContainerLaunch.getRelativeContainerLogDir( - applicationId.toString(), containerId.toString()) - + Path.SEPARATOR + $(CONTAINER_LOG_TYPE), this.conf) + new File(this.dirsHandler.getLogPathToRead( + ContainerLaunch.getRelativeContainerLogDir( + applicationId.toString(), containerId.toString()) + + Path.SEPARATOR + $(CONTAINER_LOG_TYPE)) .toUri().getPath()); } catch (Exception e) { html.h1("Cannot find this log on the local disk."); @@ -272,8 +271,8 @@ private void printLogs(Block html, ContainerId containerId, } } else { // Just print out the log-types - List<File> containerLogsDirs = - getContainerLogDirs(this.conf, containerId); + List<File> containerLogsDirs = getContainerLogDirs(containerId, + dirsHandler); boolean foundLogFile = false; for (File containerLogsDir : containerLogsDirs) { for (File logFile : containerLogsDir.listFiles()) { @@ -293,11 +292,10 @@ private void printLogs(Block html, ContainerId containerId, return; } - static List<File> - getContainerLogDirs(Configuration conf, ContainerId containerId) { - String[] logDirs = conf.getStrings(YarnConfiguration.NM_LOG_DIRS, - YarnConfiguration.DEFAULT_NM_LOG_DIRS); - List<File> containerLogDirs = new ArrayList<File>(logDirs.length); + static List<File> getContainerLogDirs(ContainerId containerId, + LocalDirsHandlerService dirsHandler) { + List<String> logDirs = dirsHandler.getLogDirs(); + List<File> containerLogDirs = new ArrayList<File>(logDirs.size()); for (String logDir : logDirs) { String appIdStr = ConverterUtils.toString( diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/WebServer.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/WebServer.java index 2573015877731..f0d87414fee90 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/WebServer.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/WebServer.java @@ -26,6 +26,7 @@ import org.apache.hadoop.yarn.YarnException; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.nodemanager.Context; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.ResourceView; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.service.AbstractService; @@ -42,10 +43,11 @@ public class WebServer extends AbstractService { private WebApp webApp; public WebServer(Context nmContext, ResourceView resourceView, - ApplicationACLsManager aclsManager) { + ApplicationACLsManager aclsManager, + LocalDirsHandlerService dirsHandler) { super(WebServer.class.getName()); this.nmContext = nmContext; - this.nmWebApp = new NMWebApp(resourceView, aclsManager); + this.nmWebApp = new NMWebApp(resourceView, aclsManager, dirsHandler); } @Override @@ -81,17 +83,21 @@ public static class NMWebApp extends WebApp implements YarnWebParams { private final ResourceView resourceView; private final ApplicationACLsManager aclsManager; + private final LocalDirsHandlerService dirsHandler; public NMWebApp(ResourceView resourceView, - ApplicationACLsManager aclsManager) { + ApplicationACLsManager aclsManager, + LocalDirsHandlerService dirsHandler) { this.resourceView = resourceView; this.aclsManager = aclsManager; + this.dirsHandler = dirsHandler; } @Override public void setup() { bind(ResourceView.class).toInstance(this.resourceView); bind(ApplicationACLsManager.class).toInstance(this.aclsManager); + bind(LocalDirsHandlerService.class).toInstance(dirsHandler); route("/", NMController.class, "info"); route("/node", NMController.class, "node"); route("/allApplications", NMController.class, "allApplications"); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.c b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.c index d85715be7a0e2..aa72303351294 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.c +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.c @@ -261,8 +261,15 @@ char * get_value(const char* key) { * Value delimiter is assumed to be a comma. */ char ** get_values(const char * key) { - char ** toPass = NULL; char *value = get_value(key); + return extract_values(value); +} + +/** + * Extracts array of values from the comma separated list of values. + */ +char ** extract_values(char *value) { + char ** toPass = NULL; char *tempTok = NULL; char *tempstr = NULL; int size = 0; @@ -276,8 +283,7 @@ char ** get_values(const char * key) { toPass[size++] = tempTok; if(size == toPassSize) { toPassSize += MAX_SIZE; - toPass = (char **) realloc(toPass,(sizeof(char *) * - (MAX_SIZE * toPassSize))); + toPass = (char **) realloc(toPass,(sizeof(char *) * toPassSize)); } tempTok = strtok_r(NULL, ",", &tempstr); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.h b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.h index 16ca23d6da835..b0d4814b310b6 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.h +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/configuration.h @@ -34,6 +34,9 @@ char *get_value(const char* key); //comma seperated strings. char ** get_values(const char* key); +// Extracts array of values from the comma separated list of values. +char ** extract_values(char *value); + // free the memory returned by get_values void free_values(char** values); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.c b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.c index 73d160ae66b15..c4bde44a26589 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.c +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.c @@ -357,7 +357,7 @@ int mkdirs(const char* path, mode_t perm) { * It creates the container work and log directories. */ static int create_container_directories(const char* user, const char *app_id, - const char *container_id) { + const char *container_id, char* const* local_dir, char* const* log_dir) { // create dirs as 0750 const mode_t perms = S_IRWXU | S_IRGRP | S_IXGRP; if (app_id == NULL || container_id == NULL || user == NULL) { @@ -367,20 +367,11 @@ static int create_container_directories(const char* user, const char *app_id, } int result = -1; - - char **local_dir = get_values(NM_SYS_DIR_KEY); - - if (local_dir == NULL) { - fprintf(LOGFILE, "%s is not configured.\n", NM_SYS_DIR_KEY); - return -1; - } - - char **local_dir_ptr; + char* const* local_dir_ptr; for(local_dir_ptr = local_dir; *local_dir_ptr != NULL; ++local_dir_ptr) { char *container_dir = get_container_work_directory(*local_dir_ptr, user, app_id, container_id); if (container_dir == NULL) { - free_values(local_dir); return -1; } if (mkdirs(container_dir, perms) == 0) { @@ -390,7 +381,6 @@ static int create_container_directories(const char* user, const char *app_id, free(container_dir); } - free_values(local_dir); if (result != 0) { return result; } @@ -404,19 +394,11 @@ static int create_container_directories(const char* user, const char *app_id, } else { sprintf(combined_name, "%s/%s", app_id, container_id); - char **log_dir = get_values(NM_LOG_DIR_KEY); - if (log_dir == NULL) { - free(combined_name); - fprintf(LOGFILE, "%s is not configured.\n", NM_LOG_DIR_KEY); - return -1; - } - - char **log_dir_ptr; + char* const* log_dir_ptr; for(log_dir_ptr = log_dir; *log_dir_ptr != NULL; ++log_dir_ptr) { char *container_log_dir = get_app_log_directory(*log_dir_ptr, combined_name); if (container_log_dir == NULL) { free(combined_name); - free_values(log_dir); return -1; } else if (mkdirs(container_log_dir, perms) != 0) { free(container_log_dir); @@ -426,7 +408,6 @@ static int create_container_directories(const char* user, const char *app_id, } } free(combined_name); - free_values(log_dir); } return result; } @@ -660,17 +641,12 @@ static int copy_file(int input, const char* in_filename, /** * Function to initialize the user directories of a user. */ -int initialize_user(const char *user) { - char **local_dir = get_values(NM_SYS_DIR_KEY); - if (local_dir == NULL) { - fprintf(LOGFILE, "%s is not configured.\n", NM_SYS_DIR_KEY); - return INVALID_NM_ROOT_DIRS; - } +int initialize_user(const char *user, char* const* local_dirs) { char *user_dir; - char **local_dir_ptr = local_dir; + char* const* local_dir_ptr; int failed = 0; - for(local_dir_ptr = local_dir; *local_dir_ptr != 0; ++local_dir_ptr) { + for(local_dir_ptr = local_dirs; *local_dir_ptr != 0; ++local_dir_ptr) { user_dir = get_user_directory(*local_dir_ptr, user); if (user_dir == NULL) { fprintf(LOGFILE, "Couldn't get userdir directory for %s.\n", user); @@ -682,32 +658,29 @@ int initialize_user(const char *user) { } free(user_dir); } - free_values(local_dir); return failed ? INITIALIZE_USER_FAILED : 0; } /** * Function to prepare the application directories for the container. */ -int initialize_app(const char *user, const char *app_id, - const char* nmPrivate_credentials_file, char* const* args) { +int initialize_app(const char *user, const char *app_id, + const char* nmPrivate_credentials_file, + char* const* local_dirs, char* const* log_roots, + char* const* args) { if (app_id == NULL || user == NULL) { fprintf(LOGFILE, "Either app_id is null or the user passed is null.\n"); return INVALID_ARGUMENT_NUMBER; } // create the user directory on all disks - int result = initialize_user(user); + int result = initialize_user(user, local_dirs); if (result != 0) { return result; } ////////////// create the log directories for the app on all disks - char **log_roots = get_values(NM_LOG_DIR_KEY); - if (log_roots == NULL) { - return INVALID_CONFIG_FILE; - } - char **log_root; + char* const* log_root; char *any_one_app_log_dir = NULL; for(log_root=log_roots; *log_root != NULL; ++log_root) { char *app_log_dir = get_app_log_directory(*log_root, app_id); @@ -722,7 +695,7 @@ int initialize_app(const char *user, const char *app_id, free(app_log_dir); } } - free_values(log_roots); + if (any_one_app_log_dir == NULL) { fprintf(LOGFILE, "Did not create any app-log directories\n"); return -1; @@ -743,15 +716,9 @@ int initialize_app(const char *user, const char *app_id, // 750 mode_t permissions = S_IRWXU | S_IRGRP | S_IXGRP; - char **nm_roots = get_values(NM_SYS_DIR_KEY); - - if (nm_roots == NULL) { - return INVALID_CONFIG_FILE; - } - - char **nm_root; + char* const* nm_root; char *primary_app_dir = NULL; - for(nm_root=nm_roots; *nm_root != NULL; ++nm_root) { + for(nm_root=local_dirs; *nm_root != NULL; ++nm_root) { char *app_dir = get_app_directory(*nm_root, user, app_id); if (app_dir == NULL) { // try the next one @@ -763,7 +730,7 @@ int initialize_app(const char *user, const char *app_id, free(app_dir); } } - free_values(nm_roots); + if (primary_app_dir == NULL) { fprintf(LOGFILE, "Did not create any app directories\n"); return -1; @@ -805,9 +772,10 @@ int initialize_app(const char *user, const char *app_id, } int launch_container_as_user(const char *user, const char *app_id, - const char *container_id, const char *work_dir, - const char *script_name, const char *cred_file, - const char* pid_file) { + const char *container_id, const char *work_dir, + const char *script_name, const char *cred_file, + const char* pid_file, char* const* local_dirs, + char* const* log_dirs) { int exit_code = -1; char *script_file_dest = NULL; char *cred_file_dest = NULL; @@ -854,7 +822,8 @@ int launch_container_as_user(const char *user, const char *app_id, goto cleanup; } - if (create_container_directories(user, app_id, container_id) != 0) { + if (create_container_directories(user, app_id, container_id, local_dirs, + log_dirs) != 0) { fprintf(LOGFILE, "Could not create container dirs"); goto cleanup; } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.h b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.h index 3f0e8a5aa2c9d..baf677a319ff7 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.h +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/container-executor.h @@ -61,8 +61,6 @@ enum errorcodes { #define NM_APP_DIR_PATTERN USER_DIR_PATTERN "/appcache/%s" #define CONTAINER_DIR_PATTERN NM_APP_DIR_PATTERN "/%s" #define CONTAINER_SCRIPT "launch_container.sh" -#define NM_SYS_DIR_KEY "yarn.nodemanager.local-dirs" -#define NM_LOG_DIR_KEY "yarn.nodemanager.log-dirs" #define CREDENTIALS_FILENAME "container_tokens" #define MIN_USERID_KEY "min.user.id" #define BANNED_USERS_KEY "banned.users" @@ -92,12 +90,13 @@ int check_executor_permissions(char *executable_file); // initialize the application directory int initialize_app(const char *user, const char *app_id, - const char *credentials, char* const* args); + const char *credentials, char* const* local_dirs, + char* const* log_dirs, char* const* args); /* * Function used to launch a container as the provided user. It does the following : * 1) Creates container work dir and log dir to be accessible by the child - * 2) Copies the script file from the TT to the work directory + * 2) Copies the script file from the NM to the work directory * 3) Sets up the environment * 4) Does an execlp on the same in order to replace the current image with * container image. @@ -109,12 +108,15 @@ int initialize_app(const char *user, const char *app_id, * @param cred_file the credentials file that needs to be compied to the * working directory. * @param pid_file file where pid of process should be written to + * @param local_dirs nodemanager-local-directories to be used + * @param log_dirs nodemanager-log-directories to be used * @return -1 or errorcode enum value on error (should never return on success). */ int launch_container_as_user(const char * user, const char *app_id, const char *container_id, const char *work_dir, const char *script_name, const char *cred_file, - const char *pid_file); + const char *pid_file, char* const* local_dirs, + char* const* log_dirs); /** * Function used to signal a container launched by the user. @@ -181,7 +183,7 @@ int mkdirs(const char* path, mode_t perm); /** * Function to initialize the user directories of a user. */ -int initialize_user(const char *user); +int initialize_user(const char *user, char* const* local_dirs); /** * Create a top level directory for the user. diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/main.c b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/main.c index 40fbad83653fc..d039f05ea438f 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/main.c +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/impl/main.c @@ -43,10 +43,11 @@ void display_usage(FILE *stream) { fprintf(stream, "Usage: container-executor user command command-args\n"); fprintf(stream, "Commands:\n"); - fprintf(stream, " initialize container: %2d appid tokens cmd app...\n", - INITIALIZE_CONTAINER); + fprintf(stream, " initialize container: %2d appid tokens " \ + "nm-local-dirs nm-log-dirs cmd app...\n", INITIALIZE_CONTAINER); fprintf(stream, - " launch container: %2d appid containerid workdir container-script tokens pidfile\n", + " launch container: %2d appid containerid workdir "\ + "container-script tokens pidfile nm-local-dirs nm-log-dirs\n", LAUNCH_CONTAINER); fprintf(stream, " signal container: %2d container-pid signal\n", SIGNAL_CONTAINER); @@ -96,6 +97,7 @@ int main(int argc, char **argv) { char *orig_conf_file = STRINGIFY(HADOOP_CONF_DIR) "/" CONF_FILENAME; char *conf_file = realpath(orig_conf_file, NULL); + char *local_dirs, *log_dirs; if (conf_file == NULL) { fprintf(ERRORFILE, "Configuration file %s not found.\n", orig_conf_file); @@ -158,20 +160,23 @@ int main(int argc, char **argv) { switch (command) { case INITIALIZE_CONTAINER: - if (argc < 6) { - fprintf(ERRORFILE, "Too few arguments (%d vs 6) for initialize container\n", + if (argc < 8) { + fprintf(ERRORFILE, "Too few arguments (%d vs 8) for initialize container\n", argc); fflush(ERRORFILE); return INVALID_ARGUMENT_NUMBER; } app_id = argv[optind++]; cred_file = argv[optind++]; + local_dirs = argv[optind++];// good local dirs as a comma separated list + log_dirs = argv[optind++];// good log dirs as a comma separated list exit_code = initialize_app(user_detail->pw_name, app_id, cred_file, - argv + optind); + extract_values(local_dirs), + extract_values(log_dirs), argv + optind); break; case LAUNCH_CONTAINER: - if (argc < 9) { - fprintf(ERRORFILE, "Too few arguments (%d vs 9) for launch container\n", + if (argc != 11) { + fprintf(ERRORFILE, "Too few arguments (%d vs 11) for launch container\n", argc); fflush(ERRORFILE); return INVALID_ARGUMENT_NUMBER; @@ -182,13 +187,17 @@ int main(int argc, char **argv) { script_file = argv[optind++]; cred_file = argv[optind++]; pid_file = argv[optind++]; - exit_code = launch_container_as_user(user_detail->pw_name, app_id, container_id, - current_dir, script_file, cred_file, pid_file); + local_dirs = argv[optind++];// good local dirs as a comma separated list + log_dirs = argv[optind++];// good log dirs as a comma separated list + exit_code = launch_container_as_user(user_detail->pw_name, app_id, + container_id, current_dir, script_file, cred_file, + pid_file, extract_values(local_dirs), + extract_values(log_dirs)); break; case SIGNAL_CONTAINER: - if (argc < 5) { - fprintf(ERRORFILE, "Too few arguments (%d vs 5) for signal container\n", - argc); + if (argc != 5) { + fprintf(ERRORFILE, "Wrong number of arguments (%d vs 5) for " \ + "signal container\n", argc); fflush(ERRORFILE); return INVALID_ARGUMENT_NUMBER; } else { diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/test/test-container-executor.c b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/test/test-container-executor.c index 7c62f1ba183a3..b7796586a4d34 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/test/test-container-executor.c +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/native/container-executor/test/test-container-executor.c @@ -28,10 +28,17 @@ #include <sys/stat.h> #include <sys/wait.h> -#define TEST_ROOT "/tmp/test-container-controller" +#define TEST_ROOT "/tmp/test-container-executor" #define DONT_TOUCH_FILE "dont-touch-me" +#define NM_LOCAL_DIRS TEST_ROOT "/local-1," TEST_ROOT "/local-2," \ + TEST_ROOT "/local-3," TEST_ROOT "/local-4," TEST_ROOT "/local-5" +#define NM_LOG_DIRS TEST_ROOT "/logdir_1," TEST_ROOT "/logdir_2," \ + TEST_ROOT "/logdir_3," TEST_ROOT "/logdir_4" +#define ARRAY_SIZE 1000 static char* username = NULL; +static char* local_dirs = NULL; +static char* log_dirs = NULL; /** * Run the command using the effective user id. @@ -84,40 +91,33 @@ void run(const char *cmd) { int write_config_file(char *file_name) { FILE *file; - int i = 0; file = fopen(file_name, "w"); if (file == NULL) { printf("Failed to open %s.\n", file_name); return EXIT_FAILURE; } - fprintf(file, "yarn.nodemanager.local-dirs=" TEST_ROOT "/local-1"); - for(i=2; i < 5; ++i) { - fprintf(file, "," TEST_ROOT "/local-%d", i); - } - fprintf(file, "\n"); - fprintf(file, "yarn.nodemanager.log-dirs=" TEST_ROOT "/logs\n"); + fprintf(file, "banned.users=bannedUser\n"); + fprintf(file, "min.user.id=1000\n"); fclose(file); return 0; } -void create_nm_roots() { - char** nm_roots = get_values(NM_SYS_DIR_KEY); +void create_nm_roots(char ** nm_roots) { char** nm_root; for(nm_root=nm_roots; *nm_root != NULL; ++nm_root) { if (mkdir(*nm_root, 0755) != 0) { printf("FAIL: Can't create directory %s - %s\n", *nm_root, - strerror(errno)); + strerror(errno)); exit(1); } char buffer[100000]; sprintf(buffer, "%s/usercache", *nm_root); if (mkdir(buffer, 0755) != 0) { printf("FAIL: Can't create directory %s - %s\n", buffer, - strerror(errno)); + strerror(errno)); exit(1); } } - free_values(nm_roots); } void test_get_user_directory() { @@ -209,7 +209,7 @@ void test_check_configuration_permissions() { } void test_delete_container() { - if (initialize_user(username)) { + if (initialize_user(username, extract_values(local_dirs))) { printf("FAIL: failed to initialize user %s\n", username); exit(1); } @@ -504,7 +504,8 @@ void test_init_app() { exit(1); } else if (child == 0) { char *final_pgm[] = {"touch", "my-touch-file", 0}; - if (initialize_app(username, "app_4", TEST_ROOT "/creds.txt", final_pgm) != 0) { + if (initialize_app(username, "app_4", TEST_ROOT "/creds.txt", final_pgm, + extract_values(local_dirs), extract_values(log_dirs)) != 0) { printf("FAIL: failed in child\n"); exit(42); } @@ -598,7 +599,8 @@ void test_run_container() { exit(1); } else if (child == 0) { if (launch_container_as_user(username, "app_4", "container_1", - container_dir, script_name, TEST_ROOT "/creds.txt", pid_file) != 0) { + container_dir, script_name, TEST_ROOT "/creds.txt", pid_file, + extract_values(local_dirs), extract_values(log_dirs)) != 0) { printf("FAIL: failed in child\n"); exit(42); } @@ -677,7 +679,12 @@ int main(int argc, char **argv) { } read_config(TEST_ROOT "/test.cfg"); - create_nm_roots(); + local_dirs = (char *) malloc (sizeof(char) * ARRAY_SIZE); + strcpy(local_dirs, NM_LOCAL_DIRS); + log_dirs = (char *) malloc (sizeof(char) * ARRAY_SIZE); + strcpy(log_dirs, NM_LOG_DIRS); + + create_nm_roots(extract_values(local_dirs)); if (getuid() == 0 && argc == 2) { username = argv[1]; diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java index 74d99796914a0..bf429da73471f 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java @@ -60,16 +60,18 @@ public DummyContainerManager(Context context, ContainerExecutor exec, DeletionService deletionContext, NodeStatusUpdater nodeStatusUpdater, NodeManagerMetrics metrics, ContainerTokenSecretManager containerTokenSecretManager, - ApplicationACLsManager applicationACLsManager) { + ApplicationACLsManager applicationACLsManager, + LocalDirsHandlerService dirsHandler) { super(context, exec, deletionContext, nodeStatusUpdater, metrics, - containerTokenSecretManager, applicationACLsManager); + containerTokenSecretManager, applicationACLsManager, dirsHandler); } @Override @SuppressWarnings("unchecked") - protected ResourceLocalizationService createResourceLocalizationService(ContainerExecutor exec, - DeletionService deletionContext) { - return new ResourceLocalizationService(super.dispatcher, exec, deletionContext) { + protected ResourceLocalizationService createResourceLocalizationService( + ContainerExecutor exec, DeletionService deletionContext) { + return new ResourceLocalizationService(super.dispatcher, exec, + deletionContext, super.dirsHandler) { @Override public void handle(LocalizationEvent event) { switch (event.getType()) { @@ -125,7 +127,8 @@ public void handle(LocalizationEvent event) { @SuppressWarnings("unchecked") protected ContainersLauncher createContainersLauncher(Context context, ContainerExecutor exec) { - return new ContainersLauncher(context, super.dispatcher, exec) { + return new ContainersLauncher(context, super.dispatcher, exec, + super.dirsHandler) { @Override public void handle(ContainersLauncherEvent event) { Container container = event.getContainer(); @@ -139,7 +142,8 @@ public void handle(ContainersLauncherEvent event) { case CLEANUP_CONTAINER: dispatcher.getEventHandler().handle( new ContainerExitEvent(containerId, - ContainerEventType.CONTAINER_KILLED_ON_REQUEST, 0)); + ContainerEventType.CONTAINER_KILLED_ON_REQUEST, 0, + "Container exited with exit code 0.")); break; } } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java index 8b4b01a5da24c..9a358f6b84d35 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java @@ -21,7 +21,6 @@ import java.io.File; import java.io.IOException; -import org.apache.hadoop.NodeHealthCheckerService; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest; @@ -80,9 +79,12 @@ public void testSuccessfulContainerLaunch() throws InterruptedException, ContainerExecutor exec = new DefaultContainerExecutor(); exec.setConf(conf); + DeletionService del = new DeletionService(exec); Dispatcher dispatcher = new AsyncDispatcher(); - NodeHealthCheckerService healthChecker = null; + NodeHealthCheckerService healthChecker = new NodeHealthCheckerService(); + healthChecker.init(conf); + LocalDirsHandlerService dirsHandler = healthChecker.getDiskHandler(); NodeManagerMetrics metrics = NodeManagerMetrics.create(); ContainerTokenSecretManager containerTokenSecretManager = new ContainerTokenSecretManager(); NodeStatusUpdater nodeStatusUpdater = @@ -100,7 +102,8 @@ protected void startStatusUpdater() { DummyContainerManager containerManager = new DummyContainerManager( context, exec, del, nodeStatusUpdater, metrics, - containerTokenSecretManager, new ApplicationACLsManager(conf)); + containerTokenSecretManager, new ApplicationACLsManager(conf), + dirsHandler); containerManager.init(conf); containerManager.start(); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutor.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutor.java index 5eb146db2c04e..ba18a3d2f4053 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutor.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutor.java @@ -37,6 +37,7 @@ import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.conf.YarnConfiguration; @@ -63,8 +64,6 @@ * config values. * <br><pre><code> * > cat /etc/hadoop/container-executor.cfg - * yarn.nodemanager.local-dirs=/tmp/hadoop/nm-local/ - * yarn.nodemanager.log-dirs=/tmp/hadoop/nm-log * yarn.nodemanager.linux-container-executor.group=mapred * #depending on the user id of the application.submitter option * min.user.id=1 @@ -72,7 +71,7 @@ * > sudo chmod 444 /etc/hadoop/container-executor.cfg * </code></pre> * - * <li>iMove the binary and set proper permissions on it. It needs to be owned + * <li>Move the binary and set proper permissions on it. It needs to be owned * by root, the group needs to be the group configured in container-executor.cfg, * and it needs the setuid bit set. (The build will also overwrite it so you * need to move it to a place that you can support it. @@ -98,14 +97,22 @@ public class TestLinuxContainerExecutor { private LinuxContainerExecutor exec = null; private String appSubmitter = null; + private LocalDirsHandlerService dirsHandler; @Before public void setup() throws Exception { - FileContext.getLocalFSFileContext().mkdir( - new Path(workSpace.getAbsolutePath()), null, true); + FileContext files = FileContext.getLocalFSFileContext(); + Path workSpacePath = new Path(workSpace.getAbsolutePath()); + files.mkdir(workSpacePath, null, true); workSpace.setReadable(true, false); workSpace.setExecutable(true, false); workSpace.setWritable(true, false); + File localDir = new File(workSpace.getAbsoluteFile(), "localDir"); + files.mkdir(new Path(localDir.getAbsolutePath()), + new FsPermission("777"), false); + File logDir = new File(workSpace.getAbsoluteFile(), "logDir"); + files.mkdir(new Path(logDir.getAbsolutePath()), + new FsPermission("777"), false); String exec_path = System.getProperty("container-executor.path"); if(exec_path != null && !exec_path.isEmpty()) { Configuration conf = new Configuration(false); @@ -114,6 +121,10 @@ public void setup() throws Exception { conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, exec_path); exec = new LinuxContainerExecutor(); exec.setConf(conf); + conf.set(YarnConfiguration.NM_LOCAL_DIRS, localDir.getAbsolutePath()); + conf.set(YarnConfiguration.NM_LOG_DIRS, logDir.getAbsolutePath()); + dirsHandler = new LocalDirsHandlerService(); + dirsHandler.init(conf); } appSubmitter = System.getProperty("application.submitter"); if(appSubmitter == null || appSubmitter.isEmpty()) { @@ -189,7 +200,8 @@ private int runAndBlock(ContainerId cId, String ... cmd) throws IOException { exec.activateContainer(cId, pidFile); return exec.launchContainer(container, scriptPath, tokensPath, - appSubmitter, appId, workDir); + appSubmitter, appId, workDir, dirsHandler.getLocalDirs(), + dirsHandler.getLogDirs()); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java index 4827d83192577..9b98290d9092c 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java @@ -35,6 +35,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; +import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.conf.YarnConfiguration; @@ -51,6 +52,7 @@ public class TestLinuxContainerExecutorWithMocks { private LinuxContainerExecutor mockExec = null; private final File mockParamFile = new File("./params.txt"); + private LocalDirsHandlerService dirsHandler; private void deleteMockParamFile() { if(mockParamFile.exists()) { @@ -80,6 +82,8 @@ public void setup() { Configuration conf = new Configuration(); conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath); mockExec = new LinuxContainerExecutor(); + dirsHandler = new LocalDirsHandlerService(); + dirsHandler.init(conf); mockExec.setConf(conf); } @@ -114,10 +118,13 @@ public void testContainerLaunch() throws IOException { mockExec.activateContainer(cId, pidFile); int ret = mockExec.launchContainer(container, scriptPath, tokensPath, - appSubmitter, appId, workDir); + appSubmitter, appId, workDir, dirsHandler.getLocalDirs(), + dirsHandler.getLogDirs()); assertEquals(0, ret); assertEquals(Arrays.asList(appSubmitter, cmd, appId, containerId, - workDir.toString(), "/bin/echo", "/dev/null", pidFile.toString()), + workDir.toString(), "/bin/echo", "/dev/null", pidFile.toString(), + StringUtils.join(",", dirsHandler.getLocalDirs()), + StringUtils.join(",", dirsHandler.getLogDirs())), readMockParams()); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/test/java/org/apache/hadoop/TestNodeHealthService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeHealthService.java similarity index 69% rename from hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/test/java/org/apache/hadoop/TestNodeHealthService.java rename to hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeHealthService.java index 54c3033ba2673..6b64f80e31f97 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/test/java/org/apache/hadoop/TestNodeHealthService.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeHealthService.java @@ -16,7 +16,7 @@ * limitations under the License. */ -package org.apache.hadoop; +package org.apache.hadoop.yarn.server.nodemanager; import java.io.File; import java.io.FileOutputStream; @@ -88,24 +88,31 @@ private void writeNodeHealthScriptFile(String scriptStr, boolean setExecutable) public void testNodeHealthScriptShouldRun() throws IOException { // Node health script should not start if there is no property called // node health script path. - Assert.assertFalse("By default Health checker should not have started", - NodeHealthCheckerService.shouldRun(new Configuration())); + Assert.assertFalse("By default Health script should not have started", + NodeHealthScriptRunner.shouldRun(new Configuration())); Configuration conf = getConfForNodeHealthScript(); // Node health script should not start if the node health script does not // exists - Assert.assertFalse("Node health script should start", NodeHealthCheckerService - .shouldRun(conf)); + Assert.assertFalse("Node health script should start", + NodeHealthScriptRunner.shouldRun(conf)); // Create script path. conf.writeXml(new FileOutputStream(nodeHealthConfigFile)); conf.addResource(nodeHealthConfigFile.getName()); writeNodeHealthScriptFile("", false); // Node health script should not start if the node health script is not // executable. - Assert.assertFalse("Node health script should start", NodeHealthCheckerService - .shouldRun(conf)); + Assert.assertFalse("Node health script should start", + NodeHealthScriptRunner.shouldRun(conf)); writeNodeHealthScriptFile("", true); - Assert.assertTrue("Node health script should start", NodeHealthCheckerService - .shouldRun(conf)); + Assert.assertTrue("Node health script should start", + NodeHealthScriptRunner.shouldRun(conf)); + } + + private void setHealthStatus(NodeHealthStatus healthStatus, boolean isHealthy, + String healthReport, long lastHealthReportTime) { + healthStatus.setHealthReport(healthReport); + healthStatus.setIsNodeHealthy(isHealthy); + healthStatus.setLastHealthReportTime(lastHealthReportTime); } @Test @@ -120,54 +127,67 @@ public void testNodeHealthScript() throws Exception { conf.writeXml(new FileOutputStream(nodeHealthConfigFile)); conf.addResource(nodeHealthConfigFile.getName()); - NodeHealthCheckerService nodeHealthChecker = new NodeHealthCheckerService( - conf); - TimerTask timer = nodeHealthChecker.getTimer(); writeNodeHealthScriptFile(normalScript, true); - timer.run(); + NodeHealthCheckerService nodeHealthChecker = new NodeHealthCheckerService(); + nodeHealthChecker.init(conf); + NodeHealthScriptRunner nodeHealthScriptRunner = + nodeHealthChecker.getNodeHealthScriptRunner(); + TimerTask timerTask = nodeHealthScriptRunner.getTimerTask(); - nodeHealthChecker.setHealthStatus(healthStatus); + timerTask.run(); + + setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(), + nodeHealthChecker.getHealthReport(), + nodeHealthChecker.getLastHealthReportTime()); LOG.info("Checking initial healthy condition"); // Check proper report conditions. Assert.assertTrue("Node health status reported unhealthy", healthStatus .getIsNodeHealthy()); Assert.assertTrue("Node health status reported unhealthy", healthStatus - .getHealthReport().isEmpty()); + .getHealthReport().equals(nodeHealthChecker.getHealthReport())); // write out error file. // Healthy to unhealthy transition writeNodeHealthScriptFile(errorScript, true); // Run timer - timer.run(); + timerTask.run(); // update health status - nodeHealthChecker.setHealthStatus(healthStatus); + setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(), + nodeHealthChecker.getHealthReport(), + nodeHealthChecker.getLastHealthReportTime()); LOG.info("Checking Healthy--->Unhealthy"); Assert.assertFalse("Node health status reported healthy", healthStatus .getIsNodeHealthy()); - Assert.assertFalse("Node health status reported healthy", healthStatus - .getHealthReport().isEmpty()); + Assert.assertTrue("Node health status reported healthy", healthStatus + .getHealthReport().equals(nodeHealthChecker.getHealthReport())); // Check unhealthy to healthy transitions. writeNodeHealthScriptFile(normalScript, true); - timer.run(); - nodeHealthChecker.setHealthStatus(healthStatus); + timerTask.run(); + setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(), + nodeHealthChecker.getHealthReport(), + nodeHealthChecker.getLastHealthReportTime()); LOG.info("Checking UnHealthy--->healthy"); // Check proper report conditions. Assert.assertTrue("Node health status reported unhealthy", healthStatus .getIsNodeHealthy()); Assert.assertTrue("Node health status reported unhealthy", healthStatus - .getHealthReport().isEmpty()); + .getHealthReport().equals(nodeHealthChecker.getHealthReport())); // Healthy to timeout transition. writeNodeHealthScriptFile(timeOutScript, true); - timer.run(); - nodeHealthChecker.setHealthStatus(healthStatus); + timerTask.run(); + setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(), + nodeHealthChecker.getHealthReport(), + nodeHealthChecker.getLastHealthReportTime()); LOG.info("Checking Healthy--->timeout"); Assert.assertFalse("Node health status reported healthy even after timeout", healthStatus.getIsNodeHealthy()); - Assert.assertEquals("Node time out message not propogated", healthStatus - .getHealthReport(), - NodeHealthCheckerService.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG); + Assert.assertTrue("Node script time out message not propogated", + healthStatus.getHealthReport().equals( + NodeHealthScriptRunner.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG + + NodeHealthCheckerService.SEPARATOR + + nodeHealthChecker.getDiskHandler().getDisksHealthReport())); } } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java index a0a5c557954f5..c1462746ff1c4 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java @@ -29,7 +29,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.hadoop.NodeHealthCheckerService; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; @@ -440,10 +439,11 @@ protected ContainerManagerImpl createContainerManager(Context context, ContainerExecutor exec, DeletionService del, NodeStatusUpdater nodeStatusUpdater, ContainerTokenSecretManager containerTokenSecretManager, - ApplicationACLsManager aclsManager) { + ApplicationACLsManager aclsManager, + LocalDirsHandlerService diskhandler) { return new ContainerManagerImpl(context, exec, del, nodeStatusUpdater, metrics, containerTokenSecretManager, - aclsManager) { + aclsManager, diskhandler) { @Override public void start() { // Simulating failure of starting RPC server diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java index 6cd6f8c691ebe..6d1ad8ed57b56 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java @@ -45,7 +45,9 @@ import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.LocalRMInterface; +import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService; import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdaterImpl; @@ -94,6 +96,8 @@ public BaseContainerManagerTest() throws UnsupportedFileSystemException { protected ContainerExecutor exec; protected DeletionService delSrvc; protected String user = "nobody"; + protected NodeHealthCheckerService nodeHealthChecker; + protected LocalDirsHandlerService dirsHandler; protected NodeStatusUpdater nodeStatusUpdater = new NodeStatusUpdaterImpl( context, new AsyncDispatcher(), null, metrics, this.containerTokenSecretManager) { @@ -147,9 +151,12 @@ public void delete(String user, Path subDir, Path[] baseDirs) { delSrvc.init(conf); exec = createContainerExecutor(); + nodeHealthChecker = new NodeHealthCheckerService(); + nodeHealthChecker.init(conf); + dirsHandler = nodeHealthChecker.getDiskHandler(); containerManager = new ContainerManagerImpl(context, exec, delSrvc, nodeStatusUpdater, metrics, this.containerTokenSecretManager, - new ApplicationACLsManager(conf)); + new ApplicationACLsManager(conf), dirsHandler); containerManager.init(conf); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java index c096598cc9467..c341548b1dd39 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java @@ -383,11 +383,12 @@ public void testLocalFilesCleanup() throws InterruptedException, // Real del service delSrvc = new DeletionService(exec); delSrvc.init(conf); + ContainerTokenSecretManager containerTokenSecretManager = new ContainerTokenSecretManager(); containerManager = new ContainerManagerImpl(context, exec, delSrvc, nodeStatusUpdater, metrics, containerTokenSecretManager, - new ApplicationACLsManager(conf)); + new ApplicationACLsManager(conf), dirsHandler); containerManager.init(conf); containerManager.start(); diff --git a/hadoop-mapreduce-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-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java index c3b42166285f9..e4b7aa47a7af7 100644 --- a/hadoop-mapreduce-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-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java @@ -25,6 +25,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.IOException; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.AbstractMap.SimpleEntry; @@ -649,7 +650,8 @@ public void containerSuccessful() { public void containerFailed(int exitCode) { c.handle(new ContainerExitEvent(cId, - ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, exitCode)); + ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, exitCode, + "Container completed with exit code " + exitCode)); drainDispatcherEvents(); } @@ -659,9 +661,10 @@ public void killContainer() { } public void containerKilledOnRequest() { + int exitCode = ExitCode.FORCE_KILLED.getExitCode(); c.handle(new ContainerExitEvent(cId, - ContainerEventType.CONTAINER_KILLED_ON_REQUEST, ExitCode.FORCE_KILLED - .getExitCode())); + ContainerEventType.CONTAINER_KILLED_ON_REQUEST, exitCode, + "Container completed with exit code " + exitCode)); drainDispatcherEvents(); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java index fe7710bacbb92..9886d37c73b43 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java @@ -59,6 +59,8 @@ import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; +import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalResourceStatus; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerAction; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse; @@ -109,19 +111,23 @@ public void testLocalizationInit() throws Exception { doNothing().when(spylfs).mkdir( isA(Path.class), isA(FsPermission.class), anyBoolean()); + List<Path> localDirs = new ArrayList<Path>(); + String[] sDirs = new String[4]; + for (int i = 0; i < 4; ++i) { + localDirs.add(lfs.makeQualified(new Path(basedir, i + ""))); + sDirs[i] = localDirs.get(i).toString(); + } + conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs); + LocalDirsHandlerService diskhandler = new LocalDirsHandlerService(); + diskhandler.init(conf); + ResourceLocalizationService locService = - spy(new ResourceLocalizationService(dispatcher, exec, delService)); + spy(new ResourceLocalizationService(dispatcher, exec, delService, + diskhandler)); doReturn(lfs) .when(locService).getLocalFileContext(isA(Configuration.class)); try { dispatcher.start(); - List<Path> localDirs = new ArrayList<Path>(); - String[] sDirs = new String[4]; - for (int i = 0; i < 4; ++i) { - localDirs.add(lfs.makeQualified(new Path(basedir, i + ""))); - sDirs[i] = localDirs.get(i).toString(); - } - conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs); // initialize ResourceLocalizationService locService.init(conf); @@ -176,12 +182,16 @@ public void testResourceRelease() throws Exception { dispatcher.register(LocalizerEventType.class, localizerBus); ContainerExecutor exec = mock(ContainerExecutor.class); + LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService(); + dirsHandler.init(conf); + DeletionService delService = new DeletionService(exec); delService.init(null); delService.start(); ResourceLocalizationService rawService = - new ResourceLocalizationService(dispatcher, exec, delService); + new ResourceLocalizationService(dispatcher, exec, delService, + dirsHandler); ResourceLocalizationService spyService = spy(rawService); doReturn(ignore).when(spyService).createServer(); doReturn(mockLocallilzerTracker).when(spyService).createLocalizerTracker( @@ -356,13 +366,17 @@ public void testLocalizationHeartbeat() throws Exception { dispatcher.register(ContainerEventType.class, containerBus); ContainerExecutor exec = mock(ContainerExecutor.class); + LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService(); + dirsHandler.init(conf); + DeletionService delServiceReal = new DeletionService(exec); DeletionService delService = spy(delServiceReal); delService.init(null); delService.start(); ResourceLocalizationService rawService = - new ResourceLocalizationService(dispatcher, exec, delService); + new ResourceLocalizationService(dispatcher, exec, delService, + dirsHandler); ResourceLocalizationService spyService = spy(rawService); doReturn(ignore).when(spyService).createServer(); doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class)); @@ -414,8 +428,9 @@ public boolean matches(Object o) { String appStr = ConverterUtils.toString(appId); String ctnrStr = c.getContainerID().toString(); ArgumentCaptor<Path> tokenPathCaptor = ArgumentCaptor.forClass(Path.class); - verify(exec).startLocalizer(tokenPathCaptor.capture(), isA(InetSocketAddress.class), - eq("user0"), eq(appStr), eq(ctnrStr), isA(List.class)); + verify(exec).startLocalizer(tokenPathCaptor.capture(), + isA(InetSocketAddress.class), eq("user0"), eq(appStr), eq(ctnrStr), + isA(List.class), isA(List.class)); Path localizationTokenPath = tokenPathCaptor.getValue(); // heartbeat from localizer diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java index a4202a9462dcd..a1853b307b0f8 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java @@ -122,7 +122,8 @@ public void testLocalFileDeletionAfterUpload() throws IOException { dispatcher.register(ApplicationEventType.class, appEventHandler); LogAggregationService logAggregationService = - new LogAggregationService(dispatcher, this.context, this.delSrvc); + new LogAggregationService(dispatcher, this.context, this.delSrvc, + super.dirsHandler); logAggregationService.init(this.conf); logAggregationService.start(); @@ -189,7 +190,8 @@ public void testNoContainerOnNode() { dispatcher.register(ApplicationEventType.class, appEventHandler); LogAggregationService logAggregationService = - new LogAggregationService(dispatcher, this.context, this.delSrvc); + new LogAggregationService(dispatcher, this.context, this.delSrvc, + super.dirsHandler); logAggregationService.init(this.conf); logAggregationService.start(); @@ -237,7 +239,8 @@ public void testMultipleAppsLogAggregation() throws IOException { dispatcher.register(ApplicationEventType.class, appEventHandler); LogAggregationService logAggregationService = - new LogAggregationService(dispatcher, this.context, this.delSrvc); + new LogAggregationService(dispatcher, this.context, this.delSrvc, + super.dirsHandler); logAggregationService.init(this.conf); logAggregationService.start(); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/TestNonAggregatingLogHandler.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/TestNonAggregatingLogHandler.java index 5fa7bcb3b1c3f..a5e5eb06bc819 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/TestNonAggregatingLogHandler.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/loghandler/TestNonAggregatingLogHandler.java @@ -37,6 +37,7 @@ import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.logaggregation.ContainerLogsRetentionPolicy; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppFinishedEvent; @@ -74,13 +75,16 @@ public void testLogDeletion() { EventHandler<ApplicationEvent> appEventHandler = mock(EventHandler.class); dispatcher.register(ApplicationEventType.class, appEventHandler); + LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService(); + dirsHandler.init(conf); + ApplicationId appId1 = BuilderUtils.newApplicationId(1234, 1); ApplicationAttemptId appAttemptId1 = BuilderUtils.newApplicationAttemptId(appId1, 1); ContainerId container11 = BuilderUtils.newContainerId(appAttemptId1, 1); NonAggregatingLogHandler logHandler = - new NonAggregatingLogHandler(dispatcher, delService); + new NonAggregatingLogHandler(dispatcher, delService, dirsHandler); logHandler.init(conf); logHandler.start(); @@ -146,13 +150,17 @@ public void testDelayedDelete() { EventHandler<ApplicationEvent> appEventHandler = mock(EventHandler.class); dispatcher.register(ApplicationEventType.class, appEventHandler); + LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService(); + dirsHandler.init(conf); + ApplicationId appId1 = BuilderUtils.newApplicationId(1234, 1); ApplicationAttemptId appAttemptId1 = BuilderUtils.newApplicationAttemptId(appId1, 1); ContainerId container11 = BuilderUtils.newContainerId(appAttemptId1, 1); NonAggregatingLogHandler logHandler = - new NonAggregatingLogHandlerWithMockExecutor(dispatcher, delService); + new NonAggregatingLogHandlerWithMockExecutor(dispatcher, delService, + dirsHandler); logHandler.init(conf); logHandler.start(); @@ -182,8 +190,8 @@ private class NonAggregatingLogHandlerWithMockExecutor extends private ScheduledThreadPoolExecutor mockSched; public NonAggregatingLogHandlerWithMockExecutor(Dispatcher dispatcher, - DeletionService delService) { - super(dispatcher, delService); + DeletionService delService, LocalDirsHandlerService dirsHandler) { + super(dispatcher, delService, dirsHandler); } @Override diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java index 5eea6d8380df3..ebba63fcc0de3 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java @@ -27,6 +27,7 @@ import java.io.Writer; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; @@ -37,6 +38,8 @@ import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.nodemanager.Context; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; +import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService; import org.apache.hadoop.yarn.server.nodemanager.NodeManager; import org.apache.hadoop.yarn.server.nodemanager.ResourceView; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application; @@ -47,6 +50,7 @@ import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.util.BuilderUtils; import org.apache.hadoop.yarn.util.ConverterUtils; +import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -54,10 +58,19 @@ public class TestNMWebServer { private static final File testRootDir = new File("target", TestNMWebServer.class.getSimpleName()); + private static File testLogDir = new File("target", + TestNMWebServer.class.getSimpleName() + "LogDir"); @Before public void setup() { testRootDir.mkdirs(); + testLogDir.mkdir(); + } + + @After + public void tearDown() { + FileUtil.fullyDelete(testRootDir); + FileUtil.fullyDelete(testLogDir); } @Test @@ -74,9 +87,14 @@ public long getPmemAllocatedForContainers() { } }; Configuration conf = new Configuration(); - WebServer server = new WebServer(nmContext, resourceView, - new ApplicationACLsManager(conf)); conf.set(YarnConfiguration.NM_LOCAL_DIRS, testRootDir.getAbsolutePath()); + conf.set(YarnConfiguration.NM_LOG_DIRS, testLogDir.getAbsolutePath()); + NodeHealthCheckerService healthChecker = new NodeHealthCheckerService(); + healthChecker.init(conf); + LocalDirsHandlerService dirsHandler = healthChecker.getDiskHandler(); + + WebServer server = new WebServer(nmContext, resourceView, + new ApplicationACLsManager(conf), dirsHandler); server.init(conf); server.start(); @@ -119,20 +137,20 @@ public ContainerState getContainerState() { containerId.getApplicationAttemptId().getApplicationId(); nmContext.getApplications().get(applicationId).getContainers() .put(containerId, container); - writeContainerLogs(conf, nmContext, containerId); + writeContainerLogs(nmContext, containerId, dirsHandler); } // TODO: Pull logs and test contents. // Thread.sleep(1000000); } - private void writeContainerLogs(Configuration conf, Context nmContext, - ContainerId containerId) + private void writeContainerLogs(Context nmContext, + ContainerId containerId, LocalDirsHandlerService dirsHandler) throws IOException { // ContainerLogDir should be created File containerLogDir = - ContainerLogsPage.ContainersLogsBlock.getContainerLogDirs(conf, - containerId).get(0); + ContainerLogsPage.ContainersLogsBlock.getContainerLogDirs(containerId, + dirsHandler).get(0); containerLogDir.mkdirs(); for (String fileType : new String[] { "stdout", "stderr", "syslog" }) { Writer writer = new FileWriter(new File(containerLogDir, fileType)); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java index 53a891366fcda..ae35de0ac1331 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java @@ -23,7 +23,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.hadoop.NodeHealthCheckerService; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; @@ -41,6 +40,7 @@ import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerResponse; import org.apache.hadoop.yarn.server.nodemanager.Context; +import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService; import org.apache.hadoop.yarn.server.nodemanager.NodeManager; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdaterImpl; @@ -51,7 +51,6 @@ import org.apache.hadoop.yarn.server.security.ContainerTokenSecretManager; import org.apache.hadoop.yarn.service.AbstractService; import org.apache.hadoop.yarn.service.CompositeService; -import org.apache.hadoop.yarn.service.Service.STATE; public class MiniYARNCluster extends CompositeService { @@ -69,13 +68,23 @@ public class MiniYARNCluster extends CompositeService { private File testWorkDir; - public MiniYARNCluster(String testName) { - //default number of nodeManagers = 1 - this(testName, 1); - } + // Number of nm-local-dirs per nodemanager + private int numLocalDirs; + // Number of nm-log-dirs per nodemanager + private int numLogDirs; + + /** + * @param testName name of the test + * @param noOfNodeManagers the number of node managers in the cluster + * @param numLocalDirs the number of nm-local-dirs per nodemanager + * @param numLogDirs the number of nm-log-dirs per nodemanager + */ + public MiniYARNCluster(String testName, int noOfNodeManagers, + int numLocalDirs, int numLogDirs) { - public MiniYARNCluster(String testName, int noOfNodeManagers) { super(testName); + this.numLocalDirs = numLocalDirs; + this.numLogDirs = numLogDirs; this.testWorkDir = new File("target", testName); try { FileContext.getLocalFSFileContext().delete( @@ -166,25 +175,39 @@ public synchronized void init(Configuration conf) { super.init(config); } + /** + * Create local/log directories + * @param dirType type of directories i.e. local dirs or log dirs + * @param numDirs number of directories + * @return the created directories as a comma delimited String + */ + private String prepareDirs(String dirType, int numDirs) { + File []dirs = new File[numDirs]; + String dirsString = ""; + for (int i = 0; i < numDirs; i++) { + dirs[i]= new File(testWorkDir, MiniYARNCluster.this.getName() + + "-" + dirType + "Dir-nm-" + index + "_" + i); + dirs[i].mkdir(); + LOG.info("Created " + dirType + "Dir in " + dirs[i].getAbsolutePath()); + String delimiter = (i > 0) ? "," : ""; + dirsString = dirsString.concat(delimiter + dirs[i].getAbsolutePath()); + } + return dirsString; + } + public synchronized void start() { try { - File localDir = new File(testWorkDir, MiniYARNCluster.this.getName() - + "-localDir-nm-" + index); - localDir.mkdir(); - LOG.info("Created localDir in " + localDir.getAbsolutePath()); - getConfig().set(YarnConfiguration.NM_LOCAL_DIRS, - localDir.getAbsolutePath()); - File logDir = - new File(testWorkDir, MiniYARNCluster.this.getName() - + "-logDir-nm-" + index); + // create nm-local-dirs and configure them for the nodemanager + String localDirsString = prepareDirs("local", numLocalDirs); + getConfig().set(YarnConfiguration.NM_LOCAL_DIRS, localDirsString); + // create nm-log-dirs and configure them for the nodemanager + String logDirsString = prepareDirs("log", numLogDirs); + getConfig().set(YarnConfiguration.NM_LOG_DIRS, logDirsString); + File remoteLogDir = new File(testWorkDir, MiniYARNCluster.this.getName() + "-remoteLogDir-nm-" + index); - logDir.mkdir(); remoteLogDir.mkdir(); - LOG.info("Created logDir in " + logDir.getAbsolutePath()); - getConfig().set(YarnConfiguration.NM_LOG_DIRS, - logDir.getAbsolutePath()); getConfig().set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, remoteLogDir.getAbsolutePath()); // By default AM + 2 containers diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java index 9fe914d87603b..765234665f9e1 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java @@ -117,7 +117,7 @@ public static void setup() throws AccessControlException, conf.setLong(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS, 100000L); UserGroupInformation.setConfiguration(conf); yarnCluster = new MiniYARNCluster(TestContainerManagerSecurity.class - .getName()); + .getName(), 1, 1, 1); yarnCluster.init(conf); yarnCluster.start(); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestDiskFailures.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestDiskFailures.java new file mode 100644 index 0000000000000..67755f189aeb2 --- /dev/null +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestDiskFailures.java @@ -0,0 +1,247 @@ +/** + * 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; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileContext; +import org.apache.hadoop.fs.FileUtil; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.UnsupportedFileSystemException; +import org.apache.hadoop.security.AccessControlException; +import org.apache.hadoop.util.StringUtils; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.server.MiniYARNCluster; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; +import org.apache.hadoop.yarn.server.nodemanager.NodeManager; +import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import junit.framework.Assert; + +/** + * Verify if NodeManager's in-memory good local dirs list and good log dirs list + * get updated properly when disks(nm-local-dirs and nm-log-dirs) fail. Also + * verify if the overall health status of the node gets updated properly when + * specified percentage of disks fail. + */ +public class TestDiskFailures { + + private static final Log LOG = LogFactory.getLog(TestDiskFailures.class); + + private static final long DISK_HEALTH_CHECK_INTERVAL = 1000;//1 sec + + private static FileContext localFS = null; + private static final File testDir = new File("target", + TestDiskFailures.class.getName()).getAbsoluteFile(); + private static final File localFSDirBase = new File(testDir, + TestDiskFailures.class.getName() + "-localDir"); + private static final int numLocalDirs = 4; + private static final int numLogDirs = 4; + + private static MiniYARNCluster yarnCluster; + LocalDirsHandlerService dirsHandler; + + @BeforeClass + public static void setup() throws AccessControlException, + FileNotFoundException, UnsupportedFileSystemException, IOException { + localFS = FileContext.getLocalFSFileContext(); + localFS.delete(new Path(localFSDirBase.getAbsolutePath()), true); + localFSDirBase.mkdirs(); + // Do not start cluster here + } + + @AfterClass + public static void teardown() { + if (yarnCluster != null) { + yarnCluster.stop(); + yarnCluster = null; + } + FileUtil.fullyDelete(localFSDirBase); + } + + /** + * Make local-dirs fail/inaccessible and verify if NodeManager can + * recognize the disk failures properly and can update the list of + * local-dirs accordingly with good disks. Also verify the overall + * health status of the node. + * @throws IOException + */ + @Test + public void testLocalDirsFailures() throws IOException { + testDirsFailures(true); + } + + /** + * Make log-dirs fail/inaccessible and verify if NodeManager can + * recognize the disk failures properly and can update the list of + * log-dirs accordingly with good disks. Also verify the overall health + * status of the node. + * @throws IOException + */ + @Test + public void testLogDirsFailures() throws IOException { + testDirsFailures(false); + } + + private void testDirsFailures(boolean localORLogDirs) throws IOException { + String dirType = localORLogDirs ? "local" : "log"; + String dirsProperty = localORLogDirs ? YarnConfiguration.NM_LOCAL_DIRS + : YarnConfiguration.NM_LOG_DIRS; + + Configuration conf = new Configuration(); + // set disk health check interval to a small value (say 1 sec). + conf.setLong(YarnConfiguration.NM_DISK_HEALTH_CHECK_INTERVAL_MS, + DISK_HEALTH_CHECK_INTERVAL); + + // If 2 out of the total 4 local-dirs fail OR if 2 Out of the total 4 + // log-dirs fail, then the node's health status should become unhealthy. + conf.setFloat(YarnConfiguration.NM_MIN_HEALTHY_DISKS_FRACTION, 0.60F); + + if (yarnCluster != null) { + yarnCluster.stop(); + FileUtil.fullyDelete(localFSDirBase); + localFSDirBase.mkdirs(); + } + LOG.info("Starting up YARN cluster"); + yarnCluster = new MiniYARNCluster(TestDiskFailures.class.getName(), + 1, numLocalDirs, numLogDirs); + yarnCluster.init(conf); + yarnCluster.start(); + + NodeManager nm = yarnCluster.getNodeManager(0); + LOG.info("Configured nm-" + dirType + "-dirs=" + + nm.getConfig().get(dirsProperty)); + dirsHandler = nm.getNodeHealthChecker().getDiskHandler(); + List<String> list = localORLogDirs ? dirsHandler.getLocalDirs() + : dirsHandler.getLogDirs(); + String[] dirs = list.toArray(new String[list.size()]); + Assert.assertEquals("Number of nm-" + dirType + "-dirs is wrong.", + numLocalDirs, dirs.length); + String expectedDirs = StringUtils.join(",", list); + // validate the health of disks initially + verifyDisksHealth(localORLogDirs, expectedDirs, true); + + // Make 1 nm-local-dir fail and verify if "the nodemanager can identify + // the disk failure(s) and can update the list of good nm-local-dirs. + prepareDirToFail(dirs[2]); + expectedDirs = dirs[0] + "," + dirs[1] + "," + + dirs[3]; + verifyDisksHealth(localORLogDirs, expectedDirs, true); + + // Now, make 1 more nm-local-dir/nm-log-dir fail and verify if "the + // nodemanager can identify the disk failures and can update the list of + // good nm-local-dirs/nm-log-dirs and can update the overall health status + // of the node to unhealthy". + prepareDirToFail(dirs[0]); + expectedDirs = dirs[1] + "," + dirs[3]; + verifyDisksHealth(localORLogDirs, expectedDirs, false); + + // Fail the remaining 2 local-dirs/log-dirs and verify if NM remains with + // empty list of local-dirs/log-dirs and the overall health status is + // unhealthy. + prepareDirToFail(dirs[1]); + prepareDirToFail(dirs[3]); + expectedDirs = ""; + verifyDisksHealth(localORLogDirs, expectedDirs, false); + } + + /** + * Wait for the NodeManger to go for the disk-health-check at least once. + */ + private void waitForDiskHealthCheck() { + long lastDisksCheckTime = dirsHandler.getLastDisksCheckTime(); + long time = lastDisksCheckTime; + for (int i = 0; i < 10 && (time <= lastDisksCheckTime); i++) { + try { + Thread.sleep(1000); + } catch(InterruptedException e) { + LOG.error( + "Interrupted while waiting for NodeManager's disk health check."); + } + time = dirsHandler.getLastDisksCheckTime(); + } + } + + /** + * Verify if the NodeManager could identify disk failures. + * @param localORLogDirs <em>true</em> represent nm-local-dirs and <em>false + * </em> means nm-log-dirs + * @param expectedDirs expected nm-local-dirs/nm-log-dirs as a string + * @param isHealthy <em>true</em> if the overall node should be healthy + */ + private void verifyDisksHealth(boolean localORLogDirs, String expectedDirs, + boolean isHealthy) { + // Wait for the NodeManager to identify disk failures. + waitForDiskHealthCheck(); + + List<String> list = localORLogDirs ? dirsHandler.getLocalDirs() + : dirsHandler.getLogDirs(); + String seenDirs = StringUtils.join(",", list); + LOG.info("ExpectedDirs=" + expectedDirs); + LOG.info("SeenDirs=" + seenDirs); + Assert.assertTrue("NodeManager could not identify disk failure.", + expectedDirs.equals(seenDirs)); + + Assert.assertEquals("Node's health in terms of disks is wrong", + isHealthy, dirsHandler.areDisksHealthy()); + for (int i = 0; i < 10; i++) { + Iterator<RMNode> iter = yarnCluster.getResourceManager().getRMContext() + .getRMNodes().values().iterator(); + if (iter.next().getNodeHealthStatus().getIsNodeHealthy() == isHealthy) { + break; + } + // wait for the node health info to go to RM + try { + Thread.sleep(1000); + } catch(InterruptedException e) { + LOG.error("Interrupted while waiting for NM->RM heartbeat."); + } + } + Iterator<RMNode> iter = yarnCluster.getResourceManager().getRMContext() + .getRMNodes().values().iterator(); + Assert.assertEquals("RM is not updated with the health status of a node", + isHealthy, iter.next().getNodeHealthStatus().getIsNodeHealthy()); + } + + /** + * Prepare directory for a failure: Replace the given directory on the + * local FileSystem with a regular file with the same name. + * This would cause failure of creation of directory in DiskChecker.checkDir() + * with the same name. + * @param dir the directory to be failed + * @throws IOException + */ + private void prepareDirToFail(String dir) throws IOException { + File file = new File(dir); + FileUtil.fullyDelete(file); + file.createNewFile(); + LOG.info("Prepared " + dir + " to fail."); + } +} diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-site/src/site/apt/ClusterSetup.apt.vm b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-site/src/site/apt/ClusterSetup.apt.vm index 4643faecbd98b..079c54b48b0e7 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-site/src/site/apt/ClusterSetup.apt.vm +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-site/src/site/apt/ClusterSetup.apt.vm @@ -398,6 +398,15 @@ Hadoop MapReduce Next Generation - Cluster Setup | | | Timeout for health script execution. | *-------------------------+-------------------------+------------------------+ + The health checker script is not supposed to give ERROR if only some of the + local disks become bad. NodeManager has the ability to periodically check + the health of the local disks (specifically checks nodemanager-local-dirs + and nodemanager-log-dirs) and after reaching the threshold of number of + bad directories based on the value set for the config property + yarn.nodemanager.disk-health-checker.min-healthy-disks. The boot disk is + either raided or a failure in the boot disk is identified by the health + checker script. + * {Slaves file} Typically you choose one machine in the cluster to act as the NameNode and @@ -874,13 +883,6 @@ KVNO Timestamp Principal *-------------------------+-------------------------+------------------------+ || Parameter || Value || Notes | *-------------------------+-------------------------+------------------------+ -| <<<yarn.nodemanager.local-dirs>>> | | -| | Comma-separated list of NodeManager local directories. | | -| | | Paths to NodeManager local directories. Should be same as the value | -| | | which was provided to key in <<<conf/yarn-site.xml>>>. This is | -| | | required to validate paths passed to the setuid executable in order | -| | to prevent arbitrary paths being passed to it. | -*-------------------------+-------------------------+------------------------+ | <<<yarn.nodemanager.linux-container-executor.group>>> | <hadoop> | | | | | Unix group of the NodeManager. The group owner of the | | | |<container-executor> binary should be this group. Should be same as the | @@ -888,14 +890,6 @@ KVNO Timestamp Principal | | | required for validating the secure access of the <container-executor> | | | | binary. | *-------------------------+-------------------------+------------------------+ -| <<<yarn.nodemanager.log-dirs>>> | | -| | Comma-separated list of NodeManager log directories. | | -| | | Paths to NodeManager log directories. Should be same as the value | -| | | which was provided to key in <<<conf/yarn-site.xml>>>. This is | -| | | required to set proper permissions on the log files so that they can | -| | | be written to by the user's containers and read by the NodeManager for | -| | | <log aggregation>. | -*-------------------------+-------------------------+------------------------+ | <<<banned.users>>> | hfds,yarn,mapred,bin | Banned users. | *-------------------------+-------------------------+------------------------+ | <<<min.user.id>>> | 1000 | Prevent other super-users. |
eb9976a662b9bec6fb38929e2b262e24b3d2fc73
tapiji
Renames `tapiji.tools.java` to `tapiji.tools.java.ui`
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.java/.classpath b/org.eclipse.babel.tapiji.tools.java.ui/.classpath similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/.classpath rename to org.eclipse.babel.tapiji.tools.java.ui/.classpath diff --git a/org.eclipse.babel.tapiji.tools.java/.project b/org.eclipse.babel.tapiji.tools.java.ui/.project similarity index 88% rename from org.eclipse.babel.tapiji.tools.java/.project rename to org.eclipse.babel.tapiji.tools.java.ui/.project index 23d6bce3..fc555eb9 100644 --- a/org.eclipse.babel.tapiji.tools.java/.project +++ b/org.eclipse.babel.tapiji.tools.java.ui/.project @@ -1,28 +1,28 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.java</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.jdt.core.javabuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.ManifestBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.SchemaBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.java.ui</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.java/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.tools.java.ui/.settings/org.eclipse.jdt.core.prefs similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/.settings/org.eclipse.jdt.core.prefs rename to org.eclipse.babel.tapiji.tools.java.ui/.settings/org.eclipse.jdt.core.prefs diff --git a/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF similarity index 89% rename from org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF rename to org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF index 214ab17f..86f633db 100644 --- a/org.eclipse.babel.tapiji.tools.java/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.tapiji.tools.java.ui/META-INF/MANIFEST.MF @@ -1,7 +1,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 -Bundle-Name: JavaBuilderExtension -Bundle-SymbolicName: org.eclipse.babel.tapiji.tools.java;singleton:=true +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", diff --git a/org.eclipse.babel.tapiji.tools.java/build.properties b/org.eclipse.babel.tapiji.tools.java.ui/build.properties similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/build.properties rename to org.eclipse.babel.tapiji.tools.java.ui/build.properties diff --git a/org.eclipse.babel.tapiji.tools.java/epl-v10.html b/org.eclipse.babel.tapiji.tools.java.ui/epl-v10.html similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/epl-v10.html rename to org.eclipse.babel.tapiji.tools.java.ui/epl-v10.html diff --git a/org.eclipse.babel.tapiji.tools.java/plugin.xml b/org.eclipse.babel.tapiji.tools.java.ui/plugin.xml similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/plugin.xml rename to org.eclipse.babel.tapiji.tools.java.ui/plugin.xml diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java diff --git a/org.eclipse.babel.tapiji.tools.java/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/auditor/model/SLLocation.java similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/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/auditor/model/SLLocation.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java 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.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java diff --git a/org.eclipse.babel.tapiji.tools.java/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 similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java 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.ui/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java similarity index 100% rename from org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java rename to org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
f7de5d7fc5ac956afa63b91a62173dddcea902ea
Mylyn Reviews
Removed CDO dependency
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.core/META-INF/CDO.MF b/org.eclipse.mylyn.reviews.core/META-INF/CDO.MF deleted file mode 100644 index bbfa1b05..00000000 --- a/org.eclipse.mylyn.reviews.core/META-INF/CDO.MF +++ /dev/null @@ -1 +0,0 @@ -This is a marker file for bundles with CDO native models. diff --git a/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF b/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF index 66bc7522..2782c9a4 100644 --- a/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF +++ b/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF @@ -6,7 +6,6 @@ Bundle-Version: 0.0.1 Bundle-Activator: org.eclipse.mylyn.reviews.core.Activator Require-Bundle: org.eclipse.core.runtime, org.eclipse.emf.edit;bundle-version="2.5.0", - org.eclipse.emf.cdo;bundle-version="2.0.0", org.eclipse.team.core;bundle-version="3.5.0", org.eclipse.core.resources;bundle-version="3.5.1", org.eclipse.mylyn.tasks.core;bundle-version="3.3.0", diff --git a/org.eclipse.mylyn.reviews.core/model/review.genmodel b/org.eclipse.mylyn.reviews.core/model/review.genmodel index 440f4c37..c3b7f79e 100644 --- a/org.eclipse.mylyn.reviews.core/model/review.genmodel +++ b/org.eclipse.mylyn.reviews.core/model/review.genmodel @@ -1,14 +1,10 @@ <?xml version="1.0" encoding="UTF-8"?> <genmodel:GenModel xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" - xmlns:genmodel="http://www.eclipse.org/emf/2002/GenModel" copyrightText="Copyright (c) 2010 Vienna University of Technology&#xA;All rights reserved. This program and the accompanying materials&#xA;are made available under the terms of the Eclipse Public License v1.0&#xA;which accompanies this distribution, and is available at&#xA;http://www.eclipse.org/legal/epl-v10.html&#xA;&#xA;Contributors:&#xA; Vienna University of Technology - initial API and implementation" - modelDirectory="/org.eclipse.mylyn.reviews.core/src" modelPluginID="org.eclipse.mylyn.reviews.core" - modelName="Review" rootExtendsInterface="org.eclipse.emf.cdo.CDOObject" rootExtendsClass="org.eclipse.emf.internal.cdo.CDOObjectImpl" - reflectiveDelegation="true" testsDirectory="/org.eclipse.mylyn.reviews.core.tests/src" - importerID="org.eclipse.emf.importer.cdo" featureDelegation="Reflective" complianceLevel="6.0" - copyrightFields="false"> + xmlns:genmodel="http://www.eclipse.org/emf/2002/GenModel" modelDirectory="/org.eclipse.mylyn.reviews.core/src" + modelPluginID="org.eclipse.mylyn.reviews.core" modelName="Review" importerID="org.eclipse.emf.importer.ecore" + complianceLevel="5.0" copyrightFields="false"> <foreignModel>review.ecore</foreignModel> - <modelPluginVariables>CDO=org.eclipse.emf.cdo</modelPluginVariables> <genPackages prefix="Review" basePackage="org.eclipse.mylyn.reviews.core.model" disposableProviderFactory="true" ecorePackage="review.ecore#/"> <genEnums typeSafeEnumCompatible="false" ecoreEnum="review.ecore#//Rating"> diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java index e6acd268..5d3bf277 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java @@ -10,9 +10,8 @@ */ package org.eclipse.mylyn.reviews.core.model.review; -import org.eclipse.emf.cdo.CDOObject; - import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> @@ -29,10 +28,9 @@ * * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview() * @model - * @extends CDOObject * @generated */ -public interface Review extends CDOObject { +public interface Review extends EObject { /** * Returns the value of the '<em><b>Result</b></em>' reference. * <!-- begin-user-doc --> diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java index ec9d9aa2..59c089de 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java @@ -10,7 +10,7 @@ */ package org.eclipse.mylyn.reviews.core.model.review; -import org.eclipse.emf.cdo.CDOObject; +import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> @@ -28,10 +28,9 @@ * * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult() * @model - * @extends CDOObject * @generated */ -public interface ReviewResult extends CDOObject { +public interface ReviewResult extends EObject { /** * Returns the value of the '<em><b>Text</b></em>' attribute. * <!-- begin-user-doc --> diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java index 56dfcd3d..252a01a1 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java @@ -10,7 +10,7 @@ */ package org.eclipse.mylyn.reviews.core.model.review; -import org.eclipse.emf.cdo.CDOObject; +import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> @@ -26,10 +26,9 @@ * * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getScopeItem() * @model - * @extends CDOObject * @generated */ -public interface ScopeItem extends CDOObject { +public interface ScopeItem extends EObject { /** * Returns the value of the '<em><b>Author</b></em>' attribute. * <!-- begin-user-doc --> diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java index 8d541789..15f58c54 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java @@ -16,12 +16,14 @@ import java.util.Date; import org.eclipse.compare.patch.IFilePatch2; +import org.eclipse.emf.common.notify.Notification; import org.eclipse.compare.patch.PatchParser; import org.eclipse.compare.patch.ReaderCreator; import org.eclipse.core.runtime.CoreException; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.mylyn.reviews.core.model.review.Patch; import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage; @@ -31,22 +33,70 @@ * <p> * The following features are implemented: * <ul> - * <li> - * {@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getContents - * <em>Contents</em>}</li> - * <li> - * {@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getCreationDate - * <em>Creation Date</em>}</li> - * <li> - * {@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getFileName - * <em>File Name</em>}</li> + * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getContents <em>Contents</em>}</li> + * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getCreationDate <em>Creation Date</em>}</li> + * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getFileName <em>File Name</em>}</li> * </ul> * </p> * - * @author Kilian Matt * @generated */ public class PatchImpl extends ScopeItemImpl implements Patch { + /** + * The default value of the '{@link #getContents() <em>Contents</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getContents() + * @generated + * @ordered + */ + protected static final String CONTENTS_EDEFAULT = null; + /** + * The cached value of the '{@link #getContents() <em>Contents</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getContents() + * @generated + * @ordered + */ + protected String contents = CONTENTS_EDEFAULT; + /** + * The default value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getCreationDate() + * @generated + * @ordered + */ + protected static final Date CREATION_DATE_EDEFAULT = null; + /** + * The cached value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getCreationDate() + * @generated + * @ordered + */ + protected Date creationDate = CREATION_DATE_EDEFAULT; + /** + * The default value of the '{@link #getFileName() <em>File Name</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getFileName() + * @generated + * @ordered + */ + protected static final String FILE_NAME_EDEFAULT = null; + /** + * The cached value of the '{@link #getFileName() <em>File Name</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getFileName() + * @generated + * @ordered + */ + protected String fileName = FILE_NAME_EDEFAULT; + /* * owner* <!-- begin-user-doc --> <!-- end-user-doc --> * @@ -58,7 +108,6 @@ protected PatchImpl() { /** * <!-- begin-user-doc --> <!-- end-user-doc --> - * * @generated */ @Override @@ -68,56 +117,59 @@ protected EClass eStaticClass() { /** * <!-- begin-user-doc --> <!-- end-user-doc --> - * * @generated */ public String getContents() { - return (String) eGet(ReviewPackage.Literals.PATCH__CONTENTS, true); + return contents; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> - * * @generated */ public void setContents(String newContents) { - eSet(ReviewPackage.Literals.PATCH__CONTENTS, newContents); + String oldContents = contents; + contents = newContents; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CONTENTS, oldContents, contents)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> - * * @generated */ public Date getCreationDate() { - return (Date) eGet(ReviewPackage.Literals.PATCH__CREATION_DATE, true); + return creationDate; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> - * * @generated */ public void setCreationDate(Date newCreationDate) { - eSet(ReviewPackage.Literals.PATCH__CREATION_DATE, newCreationDate); + Date oldCreationDate = creationDate; + creationDate = newCreationDate; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CREATION_DATE, oldCreationDate, creationDate)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> - * * @generated */ public String getFileName() { - return (String) eGet(ReviewPackage.Literals.PATCH__FILE_NAME, true); + return fileName; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> - * * @generated */ public void setFileName(String newFileName) { - eSet(ReviewPackage.Literals.PATCH__FILE_NAME, newFileName); + String oldFileName = fileName; + fileName = newFileName; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__FILE_NAME, oldFileName, fileName)); } /** @@ -146,4 +198,102 @@ public Reader createReader() throws CoreException { } } + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public Object eGet(int featureID, boolean resolve, boolean coreType) { + switch (featureID) { + case ReviewPackage.PATCH__CONTENTS: + return getContents(); + case ReviewPackage.PATCH__CREATION_DATE: + return getCreationDate(); + case ReviewPackage.PATCH__FILE_NAME: + return getFileName(); + } + return super.eGet(featureID, resolve, coreType); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public void eSet(int featureID, Object newValue) { + switch (featureID) { + case ReviewPackage.PATCH__CONTENTS: + setContents((String)newValue); + return; + case ReviewPackage.PATCH__CREATION_DATE: + setCreationDate((Date)newValue); + return; + case ReviewPackage.PATCH__FILE_NAME: + setFileName((String)newValue); + return; + } + super.eSet(featureID, newValue); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public void eUnset(int featureID) { + switch (featureID) { + case ReviewPackage.PATCH__CONTENTS: + setContents(CONTENTS_EDEFAULT); + return; + case ReviewPackage.PATCH__CREATION_DATE: + setCreationDate(CREATION_DATE_EDEFAULT); + return; + case ReviewPackage.PATCH__FILE_NAME: + setFileName(FILE_NAME_EDEFAULT); + return; + } + super.eUnset(featureID); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public boolean eIsSet(int featureID) { + switch (featureID) { + case ReviewPackage.PATCH__CONTENTS: + return CONTENTS_EDEFAULT == null ? contents != null : !CONTENTS_EDEFAULT.equals(contents); + case ReviewPackage.PATCH__CREATION_DATE: + return CREATION_DATE_EDEFAULT == null ? creationDate != null : !CREATION_DATE_EDEFAULT.equals(creationDate); + case ReviewPackage.PATCH__FILE_NAME: + return FILE_NAME_EDEFAULT == null ? fileName != null : !FILE_NAME_EDEFAULT.equals(fileName); + } + return super.eIsSet(featureID); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public String toString() { + if (eIsProxy()) return super.toString(); + + StringBuffer result = new StringBuffer(super.toString()); + result.append(" (contents: "); + result.append(contents); + result.append(", creationDate: "); + result.append(creationDate); + result.append(", fileName: "); + result.append(fileName); + result.append(')'); + return result.toString(); + } + } // PatchImpl diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java index 1167ec76..0ef56ca2 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java @@ -69,10 +69,10 @@ public ReviewFactoryImpl() { @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { - case ReviewPackage.REVIEW: return (EObject)createReview(); - case ReviewPackage.REVIEW_RESULT: return (EObject)createReviewResult(); - case ReviewPackage.PATCH: return (EObject)createPatch(); - case ReviewPackage.SCOPE_ITEM: return (EObject)createScopeItem(); + case ReviewPackage.REVIEW: return createReview(); + case ReviewPackage.REVIEW_RESULT: return createReviewResult(); + case ReviewPackage.PATCH: return createPatch(); + case ReviewPackage.SCOPE_ITEM: return createScopeItem(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java index d634e095..4cebc515 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java @@ -10,11 +10,16 @@ */ package org.eclipse.mylyn.reviews.core.model.review.impl; +import java.util.Collection; +import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; -import org.eclipse.emf.internal.cdo.CDOObjectImpl; +import org.eclipse.emf.ecore.InternalEObject; +import org.eclipse.emf.ecore.impl.ENotificationImpl; +import org.eclipse.emf.ecore.impl.EObjectImpl; +import org.eclipse.emf.ecore.util.EObjectResolvingEList; import org.eclipse.mylyn.reviews.core.model.review.Review; import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage; @@ -35,7 +40,26 @@ * * @generated */ -public class ReviewImpl extends CDOObjectImpl implements Review { +public class ReviewImpl extends EObjectImpl implements Review { + /** + * The cached value of the '{@link #getResult() <em>Result</em>}' reference. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getResult() + * @generated + * @ordered + */ + protected ReviewResult result; + /** + * The cached value of the '{@link #getScope() <em>Scope</em>}' reference list. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getScope() + * @generated + * @ordered + */ + protected EList<ScopeItem> scope; + /** * <!-- begin-user-doc --> * <!-- end-user-doc --> @@ -60,9 +84,16 @@ protected EClass eStaticClass() { * <!-- end-user-doc --> * @generated */ - @Override - protected int eStaticFeatureCount() { - return 0; + public ReviewResult getResult() { + if (result != null && result.eIsProxy()) { + InternalEObject oldResult = (InternalEObject)result; + result = (ReviewResult)eResolveProxy(oldResult); + if (result != oldResult) { + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReviewPackage.REVIEW__RESULT, oldResult, result)); + } + } + return result; } /** @@ -70,8 +101,8 @@ protected int eStaticFeatureCount() { * <!-- end-user-doc --> * @generated */ - public ReviewResult getResult() { - return (ReviewResult)eGet(ReviewPackage.Literals.REVIEW__RESULT, true); + public ReviewResult basicGetResult() { + return result; } /** @@ -80,7 +111,10 @@ public ReviewResult getResult() { * @generated */ public void setResult(ReviewResult newResult) { - eSet(ReviewPackage.Literals.REVIEW__RESULT, newResult); + ReviewResult oldResult = result; + result = newResult; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW__RESULT, oldResult, result)); } /** @@ -90,7 +124,81 @@ public void setResult(ReviewResult newResult) { */ @SuppressWarnings("unchecked") public EList<ScopeItem> getScope() { - return (EList<ScopeItem>)eGet(ReviewPackage.Literals.REVIEW__SCOPE, true); + if (scope == null) { + scope = new EObjectResolvingEList<ScopeItem>(ScopeItem.class, this, ReviewPackage.REVIEW__SCOPE); + } + return scope; + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public Object eGet(int featureID, boolean resolve, boolean coreType) { + switch (featureID) { + case ReviewPackage.REVIEW__RESULT: + if (resolve) return getResult(); + return basicGetResult(); + case ReviewPackage.REVIEW__SCOPE: + return getScope(); + } + return super.eGet(featureID, resolve, coreType); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @SuppressWarnings("unchecked") + @Override + public void eSet(int featureID, Object newValue) { + switch (featureID) { + case ReviewPackage.REVIEW__RESULT: + setResult((ReviewResult)newValue); + return; + case ReviewPackage.REVIEW__SCOPE: + getScope().clear(); + getScope().addAll((Collection<? extends ScopeItem>)newValue); + return; + } + super.eSet(featureID, newValue); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public void eUnset(int featureID) { + switch (featureID) { + case ReviewPackage.REVIEW__RESULT: + setResult((ReviewResult)null); + return; + case ReviewPackage.REVIEW__SCOPE: + getScope().clear(); + return; + } + super.eUnset(featureID); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public boolean eIsSet(int featureID) { + switch (featureID) { + case ReviewPackage.REVIEW__RESULT: + return result != null; + case ReviewPackage.REVIEW__SCOPE: + return scope != null && !scope.isEmpty(); + } + return super.eIsSet(featureID); } } //ReviewImpl diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java index b15c49a5..1619866d 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java @@ -10,10 +10,10 @@ */ package org.eclipse.mylyn.reviews.core.model.review.impl; +import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; - -import org.eclipse.emf.internal.cdo.CDOObjectImpl; - +import org.eclipse.emf.ecore.impl.ENotificationImpl; +import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.mylyn.reviews.core.model.review.Rating; import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage; import org.eclipse.mylyn.reviews.core.model.review.ReviewResult; @@ -33,24 +33,69 @@ * * @generated */ -public class ReviewResultImpl extends CDOObjectImpl implements ReviewResult { +public class ReviewResultImpl extends EObjectImpl implements ReviewResult { /** + * The default value of the '{@link #getText() <em>Text</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> + * @see #getText() * @generated + * @ordered */ - protected ReviewResultImpl() { - super(); - } + protected static final String TEXT_EDEFAULT = null; + /** + * The cached value of the '{@link #getText() <em>Text</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getText() + * @generated + * @ordered + */ + protected String text = TEXT_EDEFAULT; + /** + * The default value of the '{@link #getRating() <em>Rating</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getRating() + * @generated + * @ordered + */ + protected static final Rating RATING_EDEFAULT = Rating.NONE; + /** + * The cached value of the '{@link #getRating() <em>Rating</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getRating() + * @generated + * @ordered + */ + protected Rating rating = RATING_EDEFAULT; + /** + * The default value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getReviewer() + * @generated + * @ordered + */ + protected static final String REVIEWER_EDEFAULT = null; + /** + * The cached value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getReviewer() + * @generated + * @ordered + */ + protected String reviewer = REVIEWER_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ - @Override - protected EClass eStaticClass() { - return ReviewPackage.Literals.REVIEW_RESULT; + protected ReviewResultImpl() { + super(); } /** @@ -59,8 +104,8 @@ protected EClass eStaticClass() { * @generated */ @Override - protected int eStaticFeatureCount() { - return 0; + protected EClass eStaticClass() { + return ReviewPackage.Literals.REVIEW_RESULT; } /** @@ -69,7 +114,7 @@ protected int eStaticFeatureCount() { * @generated */ public String getText() { - return (String)eGet(ReviewPackage.Literals.REVIEW_RESULT__TEXT, true); + return text; } /** @@ -78,7 +123,10 @@ public String getText() { * @generated */ public void setText(String newText) { - eSet(ReviewPackage.Literals.REVIEW_RESULT__TEXT, newText); + String oldText = text; + text = newText; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__TEXT, oldText, text)); } /** @@ -87,7 +135,7 @@ public void setText(String newText) { * @generated */ public Rating getRating() { - return (Rating)eGet(ReviewPackage.Literals.REVIEW_RESULT__RATING, true); + return rating; } /** @@ -96,7 +144,10 @@ public Rating getRating() { * @generated */ public void setRating(Rating newRating) { - eSet(ReviewPackage.Literals.REVIEW_RESULT__RATING, newRating); + Rating oldRating = rating; + rating = newRating == null ? RATING_EDEFAULT : newRating; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__RATING, oldRating, rating)); } /** @@ -105,7 +156,7 @@ public void setRating(Rating newRating) { * @generated */ public String getReviewer() { - return (String)eGet(ReviewPackage.Literals.REVIEW_RESULT__REVIEWER, true); + return reviewer; } /** @@ -114,7 +165,108 @@ public String getReviewer() { * @generated */ public void setReviewer(String newReviewer) { - eSet(ReviewPackage.Literals.REVIEW_RESULT__REVIEWER, newReviewer); + String oldReviewer = reviewer; + reviewer = newReviewer; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__REVIEWER, oldReviewer, reviewer)); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public Object eGet(int featureID, boolean resolve, boolean coreType) { + switch (featureID) { + case ReviewPackage.REVIEW_RESULT__TEXT: + return getText(); + case ReviewPackage.REVIEW_RESULT__RATING: + return getRating(); + case ReviewPackage.REVIEW_RESULT__REVIEWER: + return getReviewer(); + } + return super.eGet(featureID, resolve, coreType); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public void eSet(int featureID, Object newValue) { + switch (featureID) { + case ReviewPackage.REVIEW_RESULT__TEXT: + setText((String)newValue); + return; + case ReviewPackage.REVIEW_RESULT__RATING: + setRating((Rating)newValue); + return; + case ReviewPackage.REVIEW_RESULT__REVIEWER: + setReviewer((String)newValue); + return; + } + super.eSet(featureID, newValue); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public void eUnset(int featureID) { + switch (featureID) { + case ReviewPackage.REVIEW_RESULT__TEXT: + setText(TEXT_EDEFAULT); + return; + case ReviewPackage.REVIEW_RESULT__RATING: + setRating(RATING_EDEFAULT); + return; + case ReviewPackage.REVIEW_RESULT__REVIEWER: + setReviewer(REVIEWER_EDEFAULT); + return; + } + super.eUnset(featureID); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public boolean eIsSet(int featureID) { + switch (featureID) { + case ReviewPackage.REVIEW_RESULT__TEXT: + return TEXT_EDEFAULT == null ? text != null : !TEXT_EDEFAULT.equals(text); + case ReviewPackage.REVIEW_RESULT__RATING: + return rating != RATING_EDEFAULT; + case ReviewPackage.REVIEW_RESULT__REVIEWER: + return REVIEWER_EDEFAULT == null ? reviewer != null : !REVIEWER_EDEFAULT.equals(reviewer); + } + return super.eIsSet(featureID); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public String toString() { + if (eIsProxy()) return super.toString(); + + StringBuffer result = new StringBuffer(super.toString()); + result.append(" (text: "); + result.append(text); + result.append(", rating: "); + result.append(rating); + result.append(", reviewer: "); + result.append(reviewer); + result.append(')'); + return result.toString(); } } //ReviewResultImpl diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java index 806b27cf..cad5f6f7 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java @@ -10,10 +10,10 @@ */ package org.eclipse.mylyn.reviews.core.model.review.impl; +import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; - -import org.eclipse.emf.internal.cdo.CDOObjectImpl; - +import org.eclipse.emf.ecore.impl.ENotificationImpl; +import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage; import org.eclipse.mylyn.reviews.core.model.review.ScopeItem; @@ -30,7 +30,26 @@ * * @generated */ -public class ScopeItemImpl extends CDOObjectImpl implements ScopeItem { +public class ScopeItemImpl extends EObjectImpl implements ScopeItem { + /** + * The default value of the '{@link #getAuthor() <em>Author</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getAuthor() + * @generated + * @ordered + */ + protected static final String AUTHOR_EDEFAULT = null; + /** + * The cached value of the '{@link #getAuthor() <em>Author</em>}' attribute. + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @see #getAuthor() + * @generated + * @ordered + */ + protected String author = AUTHOR_EDEFAULT; + /** * <!-- begin-user-doc --> * <!-- end-user-doc --> @@ -50,14 +69,39 @@ protected EClass eStaticClass() { return ReviewPackage.Literals.SCOPE_ITEM; } + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + public String getAuthor() { + return author; + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + public void setAuthor(String newAuthor) { + String oldAuthor = author; + author = newAuthor; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.SCOPE_ITEM__AUTHOR, oldAuthor, author)); + } + /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override - protected int eStaticFeatureCount() { - return 0; + public Object eGet(int featureID, boolean resolve, boolean coreType) { + switch (featureID) { + case ReviewPackage.SCOPE_ITEM__AUTHOR: + return getAuthor(); + } + return super.eGet(featureID, resolve, coreType); } /** @@ -65,8 +109,14 @@ protected int eStaticFeatureCount() { * <!-- end-user-doc --> * @generated */ - public String getAuthor() { - return (String)eGet(ReviewPackage.Literals.SCOPE_ITEM__AUTHOR, true); + @Override + public void eSet(int featureID, Object newValue) { + switch (featureID) { + case ReviewPackage.SCOPE_ITEM__AUTHOR: + setAuthor((String)newValue); + return; + } + super.eSet(featureID, newValue); } /** @@ -74,8 +124,44 @@ public String getAuthor() { * <!-- end-user-doc --> * @generated */ - public void setAuthor(String newAuthor) { - eSet(ReviewPackage.Literals.SCOPE_ITEM__AUTHOR, newAuthor); + @Override + public void eUnset(int featureID) { + switch (featureID) { + case ReviewPackage.SCOPE_ITEM__AUTHOR: + setAuthor(AUTHOR_EDEFAULT); + return; + } + super.eUnset(featureID); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public boolean eIsSet(int featureID) { + switch (featureID) { + case ReviewPackage.SCOPE_ITEM__AUTHOR: + return AUTHOR_EDEFAULT == null ? author != null : !AUTHOR_EDEFAULT.equals(author); + } + return super.eIsSet(featureID); + } + + /** + * <!-- begin-user-doc --> + * <!-- end-user-doc --> + * @generated + */ + @Override + public String toString() { + if (eIsProxy()) return super.toString(); + + StringBuffer result = new StringBuffer(super.toString()); + result.append(" (author: "); + result.append(author); + result.append(')'); + return result.toString(); } } //ScopeItemImpl diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java index 2374149a..73e096eb 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java @@ -14,6 +14,7 @@ import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; +import org.eclipse.mylyn.reviews.core.model.review.*; import org.eclipse.mylyn.reviews.core.model.review.Patch; import org.eclipse.mylyn.reviews.core.model.review.Review; import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage; @@ -24,22 +25,21 @@ * <!-- begin-user-doc --> The <b>Adapter Factory</b> for the model. It provides * an adapter <code>createXXX</code> method for each class of the model. <!-- * end-user-doc --> - * * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage * @generated */ public class ReviewAdapterFactory extends AdapterFactoryImpl { /** - * The cached model package. <!-- begin-user-doc --> <!-- end-user-doc --> - * + * The cached model package. + * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected static ReviewPackage modelPackage; /** - * Creates an instance of the adapter factory. <!-- begin-user-doc --> <!-- + * Creates an instance of the adapter factory. + * <!-- begin-user-doc --> <!-- * end-user-doc --> - * * @generated */ public ReviewAdapterFactory() { @@ -53,7 +53,6 @@ public ReviewAdapterFactory() { * <!-- begin-user-doc --> This implementation returns <code>true</code> if * the object is either the model's package or is an instance object of the * model. <!-- end-user-doc --> - * * @return whether this factory is applicable for the type of the object. * @generated */ @@ -63,7 +62,7 @@ public boolean isFactoryForType(Object object) { return true; } if (object instanceof EObject) { - return ((EObject) object).eClass().getEPackage() == modelPackage; + return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } @@ -75,44 +74,39 @@ public boolean isFactoryForType(Object object) { * @generated */ protected ReviewSwitch<Adapter> modelSwitch = new ReviewSwitch<Adapter>() { - @Override - public Adapter caseReview(Review object) { - return createReviewAdapter(); - } - - @Override - public Adapter caseReviewResult(ReviewResult object) { - return createReviewResultAdapter(); - } - - @Override - public Adapter casePatch(Patch object) { - return createPatchAdapter(); - } - - @Override - public Adapter caseScopeItem(ScopeItem object) { - return createScopeItemAdapter(); - } - - @Override - public Adapter defaultCase(EObject object) { - return createEObjectAdapter(); - } - }; + @Override + public Adapter caseReview(Review object) { + return createReviewAdapter(); + } + @Override + public Adapter caseReviewResult(ReviewResult object) { + return createReviewResultAdapter(); + } + @Override + public Adapter casePatch(Patch object) { + return createPatchAdapter(); + } + @Override + public Adapter caseScopeItem(ScopeItem object) { + return createScopeItemAdapter(); + } + @Override + public Adapter defaultCase(EObject object) { + return createEObjectAdapter(); + } + }; /** - * Creates an adapter for the <code>target</code>. <!-- begin-user-doc --> + * Creates an adapter for the <code>target</code>. + * <!-- begin-user-doc --> * <!-- end-user-doc --> - * - * @param target - * the object to adapt. + * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { - return modelSwitch.doSwitch((EObject) target); + return modelSwitch.doSwitch((EObject)target); } /** @@ -148,12 +142,10 @@ public Adapter createReviewResultAdapter() { } /** - * Creates a new adapter for an object of class ' - * {@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>} - * '. <!-- begin-user-doc --> This default implementation returns null so + * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>}'. + * <!-- begin-user-doc --> This default implementation returns null so * that we can easily ignore cases; it's useful to ignore a case when * inheritance will catch all the cases anyway. <!-- end-user-doc --> - * * @return the new adapter. * @see org.eclipse.mylyn.reviews.core.model.review.Patch * @generated @@ -163,13 +155,11 @@ public Adapter createPatchAdapter() { } /** - * Creates a new adapter for an object of class ' - * {@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem - * <em>Scope Item</em>}'. <!-- begin-user-doc --> This default + * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem <em>Scope Item</em>}'. + * <!-- begin-user-doc --> This default * implementation returns null so that we can easily ignore cases; it's * useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> - * * @return the new adapter. * @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem * @generated @@ -179,9 +169,9 @@ public Adapter createScopeItemAdapter() { } /** - * Creates a new adapter for the default case. <!-- begin-user-doc --> This + * Creates a new adapter for the default case. + * <!-- begin-user-doc --> This * default implementation returns null. <!-- end-user-doc --> - * * @return the new adapter. * @generated */ diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java index d676e9e8..3ab3388d 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java @@ -14,6 +14,7 @@ import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; +import org.eclipse.mylyn.reviews.core.model.review.*; import org.eclipse.mylyn.reviews.core.model.review.Patch; import org.eclipse.mylyn.reviews.core.model.review.Review; import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage; @@ -27,22 +28,21 @@ * starting with the actual class of the object and proceeding up the * inheritance hierarchy until a non-null result is returned, which is the * result of the switch. <!-- end-user-doc --> - * * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage * @generated */ public class ReviewSwitch<T> { /** - * The cached model package <!-- begin-user-doc --> <!-- end-user-doc --> - * + * The cached model package + * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected static ReviewPackage modelPackage; /** - * Creates an instance of the switch. <!-- begin-user-doc --> <!-- + * Creates an instance of the switch. + * <!-- begin-user-doc --> <!-- * end-user-doc --> - * * @generated */ public ReviewSwitch() { @@ -52,12 +52,10 @@ public ReviewSwitch() { } /** - * Calls <code>caseXXX</code> for each class of the model until one returns - * a non null result; it yields that result. <!-- begin-user-doc --> <!-- + * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. + * <!-- begin-user-doc --> <!-- * end-user-doc --> - * - * @return the first non-null result returned by a <code>caseXXX</code> - * call. + * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ public T doSwitch(EObject theEObject) { @@ -65,80 +63,70 @@ public T doSwitch(EObject theEObject) { } /** - * Calls <code>caseXXX</code> for each class of the model until one returns - * a non null result; it yields that result. <!-- begin-user-doc --> <!-- + * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. + * <!-- begin-user-doc --> <!-- * end-user-doc --> - * - * @return the first non-null result returned by a <code>caseXXX</code> - * call. + * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected T doSwitch(EClass theEClass, EObject theEObject) { if (theEClass.eContainer() == modelPackage) { return doSwitch(theEClass.getClassifierID(), theEObject); - } else { + } + else { List<EClass> eSuperTypes = theEClass.getESuperTypes(); - return eSuperTypes.isEmpty() ? defaultCase(theEObject) : doSwitch( - eSuperTypes.get(0), theEObject); + return + eSuperTypes.isEmpty() ? + defaultCase(theEObject) : + doSwitch(eSuperTypes.get(0), theEObject); } } /** - * Calls <code>caseXXX</code> for each class of the model until one returns - * a non null result; it yields that result. <!-- begin-user-doc --> <!-- + * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. + * <!-- begin-user-doc --> <!-- * end-user-doc --> - * - * @return the first non-null result returned by a <code>caseXXX</code> - * call. + * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { - case ReviewPackage.REVIEW: { - Review review = (Review) theEObject; - T result = caseReview(review); - if (result == null) - result = defaultCase(theEObject); - return result; - } - case ReviewPackage.REVIEW_RESULT: { - ReviewResult reviewResult = (ReviewResult) theEObject; - T result = caseReviewResult(reviewResult); - if (result == null) - result = defaultCase(theEObject); - return result; - } - case ReviewPackage.PATCH: { - Patch patch = (Patch) theEObject; - T result = casePatch(patch); - if (result == null) - result = caseScopeItem(patch); - if (result == null) - result = defaultCase(theEObject); - return result; - } - case ReviewPackage.SCOPE_ITEM: { - ScopeItem scopeItem = (ScopeItem) theEObject; - T result = caseScopeItem(scopeItem); - if (result == null) - result = defaultCase(theEObject); - return result; - } - default: - return defaultCase(theEObject); + case ReviewPackage.REVIEW: { + Review review = (Review)theEObject; + T result = caseReview(review); + if (result == null) result = defaultCase(theEObject); + return result; + } + case ReviewPackage.REVIEW_RESULT: { + ReviewResult reviewResult = (ReviewResult)theEObject; + T result = caseReviewResult(reviewResult); + if (result == null) result = defaultCase(theEObject); + return result; + } + case ReviewPackage.PATCH: { + Patch patch = (Patch)theEObject; + T result = casePatch(patch); + if (result == null) result = caseScopeItem(patch); + if (result == null) result = defaultCase(theEObject); + return result; + } + case ReviewPackage.SCOPE_ITEM: { + ScopeItem scopeItem = (ScopeItem)theEObject; + T result = caseScopeItem(scopeItem); + if (result == null) result = defaultCase(theEObject); + return result; + } + default: return defaultCase(theEObject); } } /** - * Returns the result of interpreting the object as an instance of ' - * <em>Review</em>'. <!-- begin-user-doc --> This implementation returns + * Returns the result of interpreting the object as an instance of '<em>Review</em>'. + * <!-- begin-user-doc --> This implementation returns * null; returning a non-null result will terminate the switch. <!-- * end-user-doc --> - * - * @param object - * the target of the switch. - * @return the result of interpreting the object as an instance of ' - * <em>Review</em>'. + * @param object the target of the switch. + * @return the result of interpreting the object as an instance of '<em>Review</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ @@ -147,15 +135,12 @@ public T caseReview(Review object) { } /** - * Returns the result of interpreting the object as an instance of ' - * <em>Result</em>'. <!-- begin-user-doc --> This implementation returns + * Returns the result of interpreting the object as an instance of '<em>Result</em>'. + * <!-- begin-user-doc --> This implementation returns * null; returning a non-null result will terminate the switch. <!-- * end-user-doc --> - * - * @param object - * the target of the switch. - * @return the result of interpreting the object as an instance of ' - * <em>Result</em>'. + * @param object the target of the switch. + * @return the result of interpreting the object as an instance of '<em>Result</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ @@ -164,15 +149,12 @@ public T caseReviewResult(ReviewResult object) { } /** - * Returns the result of interpreting the object as an instance of ' - * <em>Patch</em>'. <!-- begin-user-doc --> This implementation returns + * Returns the result of interpreting the object as an instance of '<em>Patch</em>'. + * <!-- begin-user-doc --> This implementation returns * null; returning a non-null result will terminate the switch. <!-- * end-user-doc --> - * - * @param object - * the target of the switch. - * @return the result of interpreting the object as an instance of ' - * <em>Patch</em>'. + * @param object the target of the switch. + * @return the result of interpreting the object as an instance of '<em>Patch</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ @@ -181,15 +163,12 @@ public T casePatch(Patch object) { } /** - * Returns the result of interpreting the object as an instance of ' - * <em>Scope Item</em>'. <!-- begin-user-doc --> This implementation returns + * Returns the result of interpreting the object as an instance of '<em>Scope Item</em>'. + * <!-- begin-user-doc --> This implementation returns * null; returning a non-null result will terminate the switch. <!-- * end-user-doc --> - * - * @param object - * the target of the switch. - * @return the result of interpreting the object as an instance of ' - * <em>Scope Item</em>'. + * @param object the target of the switch. + * @return the result of interpreting the object as an instance of '<em>Scope Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ @@ -198,15 +177,12 @@ public T caseScopeItem(ScopeItem object) { } /** - * Returns the result of interpreting the object as an instance of ' - * <em>EObject</em>'. <!-- begin-user-doc --> This implementation returns + * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. + * <!-- begin-user-doc --> This implementation returns * null; returning a non-null result will terminate the switch, but this is * the last case anyway. <!-- end-user-doc --> - * - * @param object - * the target of the switch. - * @return the result of interpreting the object as an instance of ' - * <em>EObject</em>'. + * @param object the target of the switch. + * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */
ed8ba5dff378f6ebd3edca10994ca63976af541b
hbase
HBASE-1773 Fix broken tests (setWriteBuffer now- throws IOE)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@805236 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java b/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java index 724201f3cdcb..48277a361159 100644 --- a/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java +++ b/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java @@ -104,7 +104,7 @@ public void testRowsBatchUpdateBufferedOneFlush() { } } - public void testRowsBatchUpdateBufferedManyManyFlushes() { + public void testRowsBatchUpdateBufferedManyManyFlushes() throws IOException { table.setAutoFlush(false); table.setWriteBufferSize(10); ArrayList<BatchUpdate> rowsUpdate = new ArrayList<BatchUpdate>(); diff --git a/src/test/org/apache/hadoop/hbase/client/TestPut.java b/src/test/org/apache/hadoop/hbase/client/TestPut.java index 972c72e1abfb..3fb6ba5a6bbd 100644 --- a/src/test/org/apache/hadoop/hbase/client/TestPut.java +++ b/src/test/org/apache/hadoop/hbase/client/TestPut.java @@ -42,7 +42,6 @@ public class TestPut extends HBaseClusterTestCase { private static final int SMALL_LENGTH = 1; private static final int NB_BATCH_ROWS = 10; private byte [] value; - private byte [] smallValue; private HTableDescriptor desc = null; private HTable table = null; @@ -53,7 +52,6 @@ public class TestPut extends HBaseClusterTestCase { public TestPut() throws UnsupportedEncodingException { super(); value = Bytes.toBytes("abcd"); - smallValue = Bytes.toBytes("a"); } @Override @@ -164,7 +162,7 @@ public void testRowsPutBufferedOneFlush() { } } - public void testRowsPutBufferedManyManyFlushes() { + public void testRowsPutBufferedManyManyFlushes() throws IOException { table.setAutoFlush(false); table.setWriteBufferSize(10); ArrayList<Put> rowsUpdate = new ArrayList<Put>();
71ab4ddb1907323ff661d6f1c0a87678f95a7571
hbase
HBASE-12731 Heap occupancy based client pushback--
a
https://github.com/apache/hbase
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ExponentialClientBackoffPolicy.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ExponentialClientBackoffPolicy.java index 6e75670227eb..5b1d3d273d52 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ExponentialClientBackoffPolicy.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ExponentialClientBackoffPolicy.java @@ -20,10 +20,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.classification.InterfaceStability; +import com.google.common.base.Preconditions; + /** * Simple exponential backoff policy on for the client that uses a percent^4 times the * max backoff to generate the backoff time. @@ -38,9 +41,15 @@ public class ExponentialClientBackoffPolicy implements ClientBackoffPolicy { public static final long DEFAULT_MAX_BACKOFF = 5 * ONE_MINUTE; public static final String MAX_BACKOFF_KEY = "hbase.client.exponential-backoff.max"; private long maxBackoff; + private float heapOccupancyLowWatermark; + private float heapOccupancyHighWatermark; public ExponentialClientBackoffPolicy(Configuration conf) { this.maxBackoff = conf.getLong(MAX_BACKOFF_KEY, DEFAULT_MAX_BACKOFF); + this.heapOccupancyLowWatermark = conf.getFloat(HConstants.HEAP_OCCUPANCY_LOW_WATERMARK_KEY, + HConstants.DEFAULT_HEAP_OCCUPANCY_LOW_WATERMARK); + this.heapOccupancyHighWatermark = conf.getFloat(HConstants.HEAP_OCCUPANCY_HIGH_WATERMARK_KEY, + HConstants.DEFAULT_HEAP_OCCUPANCY_HIGH_WATERMARK); } @Override @@ -56,16 +65,40 @@ public long getBackoffTime(ServerName serverName, byte[] region, ServerStatistic return 0; } + // Factor in memstore load + double percent = regionStats.getMemstoreLoadPercent() / 100.0; + + // Factor in heap occupancy + float heapOccupancy = regionStats.getHeapOccupancyPercent() / 100.0f; + if (heapOccupancy >= heapOccupancyLowWatermark) { + // If we are higher than the high watermark, we are already applying max + // backoff and cannot scale more (see scale() below) + if (heapOccupancy > heapOccupancyHighWatermark) { + heapOccupancy = heapOccupancyHighWatermark; + } + percent = Math.max(percent, + scale(heapOccupancy, heapOccupancyLowWatermark, heapOccupancyHighWatermark, + 0.1, 1.0)); + } + // square the percent as a value less than 1. Closer we move to 100 percent, // the percent moves to 1, but squaring causes the exponential curve - double percent = regionStats.getMemstoreLoadPercent() / 100.0; double multiplier = Math.pow(percent, 4.0); - // shouldn't ever happen, but just incase something changes in the statistic data if (multiplier > 1) { - LOG.warn("Somehow got a backoff multiplier greater than the allowed backoff. Forcing back " + - "down to the max backoff"); multiplier = 1; } return (long) (multiplier * maxBackoff); } + + /** Scale valueIn in the range [baseMin,baseMax] to the range [limitMin,limitMax] */ + private static double scale(double valueIn, double baseMin, double baseMax, double limitMin, + double limitMax) { + Preconditions.checkArgument(baseMin <= baseMax, "Illegal source range [%s,%s]", + baseMin, baseMax); + Preconditions.checkArgument(limitMin <= limitMax, "Illegal target range [%s,%s]", + limitMin, limitMax); + Preconditions.checkArgument(valueIn >= baseMin && valueIn <= baseMax, + "Value %s must be within the range [%s,%s]", valueIn, baseMin, baseMax); + return ((limitMax - limitMin) * (valueIn - baseMin) / (baseMax - baseMin)) + limitMin; + } } \ No newline at end of file diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ServerStatistics.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ServerStatistics.java index a3b8e11a6328..c7519be09198 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ServerStatistics.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/backoff/ServerStatistics.java @@ -54,15 +54,21 @@ public RegionStatistics getStatsForRegion(byte[] regionName){ return stats.get(regionName); } - public static class RegionStatistics{ + public static class RegionStatistics { private int memstoreLoad = 0; + private int heapOccupancy = 0; public void update(ClientProtos.RegionLoadStats currentStats) { this.memstoreLoad = currentStats.getMemstoreLoad(); + this.heapOccupancy = currentStats.getHeapOccupancy(); } public int getMemstoreLoadPercent(){ return this.memstoreLoad; } + + public int getHeapOccupancyPercent(){ + return this.heapOccupancy; + } } } diff --git a/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestClientExponentialBackoff.java b/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestClientExponentialBackoff.java index 88e409d5bafb..3a902d01d3ea 100644 --- a/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestClientExponentialBackoff.java +++ b/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestClientExponentialBackoff.java @@ -18,6 +18,7 @@ package org.apache.hadoop.hbase.client; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.backoff.ExponentialClientBackoffPolicy; import org.apache.hadoop.hbase.client.backoff.ServerStatistics; @@ -101,10 +102,42 @@ public void testResultOrdering() { } } + @Test + public void testHeapOccupancyPolicy() { + Configuration conf = new Configuration(false); + ExponentialClientBackoffPolicy backoff = new ExponentialClientBackoffPolicy(conf); + + ServerStatistics stats = new ServerStatistics(); + long backoffTime; + + update(stats, 0, 95); + backoffTime = backoff.getBackoffTime(server, regionname, stats); + assertTrue("Heap occupancy at low watermark had no effect", backoffTime > 0); + + long previous = backoffTime; + update(stats, 0, 96); + backoffTime = backoff.getBackoffTime(server, regionname, stats); + assertTrue("Increase above low watermark should have increased backoff", + backoffTime > previous); + + update(stats, 0, 98); + backoffTime = backoff.getBackoffTime(server, regionname, stats); + assertEquals("We should be using max backoff when at high watermark", backoffTime, + ExponentialClientBackoffPolicy.DEFAULT_MAX_BACKOFF); + } + private void update(ServerStatistics stats, int load) { ClientProtos.RegionLoadStats stat = ClientProtos.RegionLoadStats.newBuilder() .setMemstoreLoad (load).build(); stats.update(regionname, stat); } + + private void update(ServerStatistics stats, int memstoreLoad, int heapOccupancy) { + ClientProtos.RegionLoadStats stat = ClientProtos.RegionLoadStats.newBuilder() + .setMemstoreLoad(memstoreLoad) + .setHeapOccupancy(heapOccupancy) + .build(); + stats.update(regionname, stat); + } } \ No newline at end of file diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java index 8585299d6a8d..e84f78aa0007 100644 --- a/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java @@ -1128,6 +1128,12 @@ public static enum Modify { public static final String ENABLE_CLIENT_BACKPRESSURE = "hbase.client.backpressure.enabled"; public static final boolean DEFAULT_ENABLE_CLIENT_BACKPRESSURE = false; + public static final String HEAP_OCCUPANCY_LOW_WATERMARK_KEY = + "hbase.heap.occupancy.low_water_mark"; + public static final float DEFAULT_HEAP_OCCUPANCY_LOW_WATERMARK = 0.95f; + public static final String HEAP_OCCUPANCY_HIGH_WATERMARK_KEY = + "hbase.heap.occupancy.high_water_mark"; + public static final float DEFAULT_HEAP_OCCUPANCY_HIGH_WATERMARK = 0.98f; private HConstants() { // Can't be instantiated with this ctor. diff --git a/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java b/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java index ab86e1e269c7..afd67a1cc530 100644 --- a/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java +++ b/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java @@ -26218,7 +26218,7 @@ public interface RegionLoadStatsOrBuilder * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ boolean hasMemstoreLoad(); @@ -26226,10 +26226,30 @@ public interface RegionLoadStatsOrBuilder * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ int getMemstoreLoad(); + + // optional int32 heapOccupancy = 2 [default = 0]; + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + boolean hasHeapOccupancy(); + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + int getHeapOccupancy(); } /** * Protobuf type {@code RegionLoadStats} @@ -26292,6 +26312,11 @@ private RegionLoadStats( memstoreLoad_ = input.readInt32(); break; } + case 16: { + bitField0_ |= 0x00000002; + heapOccupancy_ = input.readInt32(); + break; + } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { @@ -26339,7 +26364,7 @@ public com.google.protobuf.Parser<RegionLoadStats> getParserForType() { * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ public boolean hasMemstoreLoad() { @@ -26349,15 +26374,42 @@ public boolean hasMemstoreLoad() { * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ public int getMemstoreLoad() { return memstoreLoad_; } + // optional int32 heapOccupancy = 2 [default = 0]; + public static final int HEAPOCCUPANCY_FIELD_NUMBER = 2; + private int heapOccupancy_; + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + public boolean hasHeapOccupancy() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + public int getHeapOccupancy() { + return heapOccupancy_; + } + private void initFields() { memstoreLoad_ = 0; + heapOccupancy_ = 0; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { @@ -26374,6 +26426,9 @@ public void writeTo(com.google.protobuf.CodedOutputStream output) if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt32(1, memstoreLoad_); } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeInt32(2, heapOccupancy_); + } getUnknownFields().writeTo(output); } @@ -26387,6 +26442,10 @@ public int getSerializedSize() { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, memstoreLoad_); } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, heapOccupancy_); + } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; @@ -26415,6 +26474,11 @@ public boolean equals(final java.lang.Object obj) { result = result && (getMemstoreLoad() == other.getMemstoreLoad()); } + result = result && (hasHeapOccupancy() == other.hasHeapOccupancy()); + if (hasHeapOccupancy()) { + result = result && (getHeapOccupancy() + == other.getHeapOccupancy()); + } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; @@ -26432,6 +26496,10 @@ public int hashCode() { hash = (37 * hash) + MEMSTORELOAD_FIELD_NUMBER; hash = (53 * hash) + getMemstoreLoad(); } + if (hasHeapOccupancy()) { + hash = (37 * hash) + HEAPOCCUPANCY_FIELD_NUMBER; + hash = (53 * hash) + getHeapOccupancy(); + } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; @@ -26548,6 +26616,8 @@ public Builder clear() { super.clear(); memstoreLoad_ = 0; bitField0_ = (bitField0_ & ~0x00000001); + heapOccupancy_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); return this; } @@ -26580,6 +26650,10 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.RegionLoadStats b to_bitField0_ |= 0x00000001; } result.memstoreLoad_ = memstoreLoad_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.heapOccupancy_ = heapOccupancy_; result.bitField0_ = to_bitField0_; onBuilt(); return result; @@ -26599,6 +26673,9 @@ public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.ClientProtos if (other.hasMemstoreLoad()) { setMemstoreLoad(other.getMemstoreLoad()); } + if (other.hasHeapOccupancy()) { + setHeapOccupancy(other.getHeapOccupancy()); + } this.mergeUnknownFields(other.getUnknownFields()); return this; } @@ -26632,7 +26709,7 @@ public Builder mergeFrom( * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ public boolean hasMemstoreLoad() { @@ -26642,7 +26719,7 @@ public boolean hasMemstoreLoad() { * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ public int getMemstoreLoad() { @@ -26652,7 +26729,7 @@ public int getMemstoreLoad() { * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ public Builder setMemstoreLoad(int value) { @@ -26665,7 +26742,7 @@ public Builder setMemstoreLoad(int value) { * <code>optional int32 memstoreLoad = 1 [default = 0];</code> * * <pre> - * percent load on the memstore. Guaranteed to be positive, between 0 and 100 + * Percent load on the memstore. Guaranteed to be positive, between 0 and 100. * </pre> */ public Builder clearMemstoreLoad() { @@ -26675,6 +26752,59 @@ public Builder clearMemstoreLoad() { return this; } + // optional int32 heapOccupancy = 2 [default = 0]; + private int heapOccupancy_ ; + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + public boolean hasHeapOccupancy() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + public int getHeapOccupancy() { + return heapOccupancy_; + } + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + public Builder setHeapOccupancy(int value) { + bitField0_ |= 0x00000002; + heapOccupancy_ = value; + onChanged(); + return this; + } + /** + * <code>optional int32 heapOccupancy = 2 [default = 0];</code> + * + * <pre> + * Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + * We can move this to "ServerLoadStats" should we develop them. + * </pre> + */ + public Builder clearHeapOccupancy() { + bitField0_ = (bitField0_ & ~0x00000002); + heapOccupancy_ = 0; + onChanged(); + return this; + } + // @@protoc_insertion_point(builder_scope:RegionLoadStats) } @@ -31922,33 +32052,33 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiResponse mul "\030\003 \001(\0132\004.Get\022-\n\014service_call\030\004 \001(\0132\027.Cop" + "rocessorServiceCall\"Y\n\014RegionAction\022 \n\006r" + "egion\030\001 \002(\0132\020.RegionSpecifier\022\016\n\006atomic\030" + - "\002 \001(\010\022\027\n\006action\030\003 \003(\0132\007.Action\"*\n\017Region" + - "LoadStats\022\027\n\014memstoreLoad\030\001 \001(\005:\0010\"\266\001\n\021R" + - "esultOrException\022\r\n\005index\030\001 \001(\r\022\027\n\006resul" + - "t\030\002 \001(\0132\007.Result\022!\n\texception\030\003 \001(\0132\016.Na" + - "meBytesPair\0221\n\016service_result\030\004 \001(\0132\031.Co", - "processorServiceResult\022#\n\tloadStats\030\005 \001(" + - "\0132\020.RegionLoadStats\"f\n\022RegionActionResul" + - "t\022-\n\021resultOrException\030\001 \003(\0132\022.ResultOrE" + - "xception\022!\n\texception\030\002 \001(\0132\016.NameBytesP" + - "air\"f\n\014MultiRequest\022#\n\014regionAction\030\001 \003(" + - "\0132\r.RegionAction\022\022\n\nnonceGroup\030\002 \001(\004\022\035\n\t" + - "condition\030\003 \001(\0132\n.Condition\"S\n\rMultiResp" + - "onse\022/\n\022regionActionResult\030\001 \003(\0132\023.Regio" + - "nActionResult\022\021\n\tprocessed\030\002 \001(\010*\'\n\013Cons" + - "istency\022\n\n\006STRONG\020\000\022\014\n\010TIMELINE\020\0012\205\003\n\rCl", - "ientService\022 \n\003Get\022\013.GetRequest\032\014.GetRes" + - "ponse\022)\n\006Mutate\022\016.MutateRequest\032\017.Mutate" + - "Response\022#\n\004Scan\022\014.ScanRequest\032\r.ScanRes" + - "ponse\022>\n\rBulkLoadHFile\022\025.BulkLoadHFileRe" + - "quest\032\026.BulkLoadHFileResponse\022F\n\013ExecSer" + - "vice\022\032.CoprocessorServiceRequest\032\033.Copro" + - "cessorServiceResponse\022R\n\027ExecRegionServe" + - "rService\022\032.CoprocessorServiceRequest\032\033.C" + - "oprocessorServiceResponse\022&\n\005Multi\022\r.Mul" + - "tiRequest\032\016.MultiResponseBB\n*org.apache.", - "hadoop.hbase.protobuf.generatedB\014ClientP" + - "rotosH\001\210\001\001\240\001\001" + "\002 \001(\010\022\027\n\006action\030\003 \003(\0132\007.Action\"D\n\017Region" + + "LoadStats\022\027\n\014memstoreLoad\030\001 \001(\005:\0010\022\030\n\rhe" + + "apOccupancy\030\002 \001(\005:\0010\"\266\001\n\021ResultOrExcepti" + + "on\022\r\n\005index\030\001 \001(\r\022\027\n\006result\030\002 \001(\0132\007.Resu" + + "lt\022!\n\texception\030\003 \001(\0132\016.NameBytesPair\0221\n", + "\016service_result\030\004 \001(\0132\031.CoprocessorServi" + + "ceResult\022#\n\tloadStats\030\005 \001(\0132\020.RegionLoad" + + "Stats\"f\n\022RegionActionResult\022-\n\021resultOrE" + + "xception\030\001 \003(\0132\022.ResultOrException\022!\n\tex" + + "ception\030\002 \001(\0132\016.NameBytesPair\"f\n\014MultiRe" + + "quest\022#\n\014regionAction\030\001 \003(\0132\r.RegionActi" + + "on\022\022\n\nnonceGroup\030\002 \001(\004\022\035\n\tcondition\030\003 \001(" + + "\0132\n.Condition\"S\n\rMultiResponse\022/\n\022region" + + "ActionResult\030\001 \003(\0132\023.RegionActionResult\022" + + "\021\n\tprocessed\030\002 \001(\010*\'\n\013Consistency\022\n\n\006STR", + "ONG\020\000\022\014\n\010TIMELINE\020\0012\205\003\n\rClientService\022 \n" + + "\003Get\022\013.GetRequest\032\014.GetResponse\022)\n\006Mutat" + + "e\022\016.MutateRequest\032\017.MutateResponse\022#\n\004Sc" + + "an\022\014.ScanRequest\032\r.ScanResponse\022>\n\rBulkL" + + "oadHFile\022\025.BulkLoadHFileRequest\032\026.BulkLo" + + "adHFileResponse\022F\n\013ExecService\022\032.Coproce" + + "ssorServiceRequest\032\033.CoprocessorServiceR" + + "esponse\022R\n\027ExecRegionServerService\022\032.Cop" + + "rocessorServiceRequest\032\033.CoprocessorServ" + + "iceResponse\022&\n\005Multi\022\r.MultiRequest\032\016.Mu", + "ltiResponseBB\n*org.apache.hadoop.hbase.p" + + "rotobuf.generatedB\014ClientProtosH\001\210\001\001\240\001\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { @@ -32110,7 +32240,7 @@ public com.google.protobuf.ExtensionRegistry assignDescriptors( internal_static_RegionLoadStats_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_RegionLoadStats_descriptor, - new java.lang.String[] { "MemstoreLoad", }); + new java.lang.String[] { "MemstoreLoad", "HeapOccupancy", }); internal_static_ResultOrException_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_ResultOrException_fieldAccessorTable = new diff --git a/hbase-protocol/src/main/protobuf/Client.proto b/hbase-protocol/src/main/protobuf/Client.proto index 1a3c43e4a0fb..606ca8df1310 100644 --- a/hbase-protocol/src/main/protobuf/Client.proto +++ b/hbase-protocol/src/main/protobuf/Client.proto @@ -356,9 +356,12 @@ message RegionAction { /* * Statistics about the current load on the region */ -message RegionLoadStats{ - // percent load on the memstore. Guaranteed to be positive, between 0 and 100 +message RegionLoadStats { + // Percent load on the memstore. Guaranteed to be positive, between 0 and 100. optional int32 memstoreLoad = 1 [default = 0]; + // Percent JVM heap occupancy. Guaranteed to be positive, between 0 and 100. + // We can move this to "ServerLoadStats" should we develop them. + optional int32 heapOccupancy = 2 [default = 0]; } /** diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java index dd1cf8d78987..2b6f9743c0fb 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java @@ -5244,6 +5244,7 @@ public ClientProtos.RegionLoadStats getRegionStats() { ClientProtos.RegionLoadStats.Builder stats = ClientProtos.RegionLoadStats.newBuilder(); stats.setMemstoreLoad((int) (Math.min(100, (this.memstoreSize.get() * 100) / this .memstoreFlushSize))); + stats.setHeapOccupancy((int)rsServices.getHeapMemoryManager().getHeapOccupancyPercent()*100); return stats.build(); } diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java index 4669f8f59534..5263a99f4fe2 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java @@ -3140,4 +3140,9 @@ public void updateConfiguration() { conf.reloadConfiguration(); configurationManager.notifyAllObservers(conf); } + + @Override + public HeapMemoryManager getHeapMemoryManager() { + return hMemManager; + } } diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HeapMemoryManager.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HeapMemoryManager.java index ddd3e95b0267..112634e9f28b 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HeapMemoryManager.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HeapMemoryManager.java @@ -21,6 +21,7 @@ import static org.apache.hadoop.hbase.HConstants.HFILE_BLOCK_CACHE_SIZE_KEY; import java.lang.management.ManagementFactory; +import java.lang.management.MemoryUsage; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; @@ -57,7 +58,7 @@ public class HeapMemoryManager { "hbase.regionserver.global.memstore.size.min.range"; public static final String HBASE_RS_HEAP_MEMORY_TUNER_PERIOD = "hbase.regionserver.heapmemory.tuner.period"; - public static final int HBASE_RS_HEAP_MEMORY_TUNER_DEFAULT_PERIOD = 5 * 60 * 1000; + public static final int HBASE_RS_HEAP_MEMORY_TUNER_DEFAULT_PERIOD = 60 * 1000; public static final String HBASE_RS_HEAP_MEMORY_TUNER_CLASS = "hbase.regionserver.heapmemory.tuner.class"; @@ -70,12 +71,16 @@ public class HeapMemoryManager { private float blockCachePercentMaxRange; private float l2BlockCachePercent; + private float heapOccupancyPercent; + private final ResizableBlockCache blockCache; private final FlushRequester memStoreFlusher; private final Server server; private HeapMemoryTunerChore heapMemTunerChore = null; private final boolean tunerOn; + private final int defaultChorePeriod; + private final float heapOccupancyLowWatermark; private long maxHeapSize = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax(); @@ -91,10 +96,15 @@ public static HeapMemoryManager create(Configuration conf, FlushRequester memSto @VisibleForTesting HeapMemoryManager(ResizableBlockCache blockCache, FlushRequester memStoreFlusher, Server server) { + Configuration conf = server.getConfiguration(); this.blockCache = blockCache; this.memStoreFlusher = memStoreFlusher; this.server = server; - this.tunerOn = doInit(server.getConfiguration()); + this.tunerOn = doInit(conf); + this.defaultChorePeriod = conf.getInt(HBASE_RS_HEAP_MEMORY_TUNER_PERIOD, + HBASE_RS_HEAP_MEMORY_TUNER_DEFAULT_PERIOD); + this.heapOccupancyLowWatermark = conf.getFloat(HConstants.HEAP_OCCUPANCY_LOW_WATERMARK_KEY, + HConstants.DEFAULT_HEAP_OCCUPANCY_LOW_WATERMARK); } private boolean doInit(Configuration conf) { @@ -174,10 +184,10 @@ private boolean doInit(Configuration conf) { } public void start() { + LOG.info("Starting HeapMemoryTuner chore."); + this.heapMemTunerChore = new HeapMemoryTunerChore(); + Threads.setDaemonThreadRunning(heapMemTunerChore.getThread()); if (tunerOn) { - LOG.info("Starting HeapMemoryTuner chore."); - this.heapMemTunerChore = new HeapMemoryTunerChore(); - Threads.setDaemonThreadRunning(heapMemTunerChore.getThread()); // Register HeapMemoryTuner as a memstore flush listener memStoreFlusher.registerFlushRequestListener(heapMemTunerChore); } @@ -185,10 +195,8 @@ public void start() { public void stop() { // The thread is Daemon. Just interrupting the ongoing process. - if (tunerOn) { - LOG.info("Stoping HeapMemoryTuner chore."); - this.heapMemTunerChore.interrupt(); - } + LOG.info("Stoping HeapMemoryTuner chore."); + this.heapMemTunerChore.interrupt(); } // Used by the test cases. @@ -196,16 +204,23 @@ boolean isTunerOn() { return this.tunerOn; } + /** + * @return heap occupancy percentage, 0 <= n <= 1 + */ + public float getHeapOccupancyPercent() { + return this.heapOccupancyPercent; + } + private class HeapMemoryTunerChore extends Chore implements FlushRequestListener { private HeapMemoryTuner heapMemTuner; private AtomicLong blockedFlushCount = new AtomicLong(); private AtomicLong unblockedFlushCount = new AtomicLong(); private long evictCount = 0L; private TunerContext tunerContext = new TunerContext(); + private boolean alarming = false; public HeapMemoryTunerChore() { - super(server.getServerName() + "-HeapMemoryTunerChore", server.getConfiguration().getInt( - HBASE_RS_HEAP_MEMORY_TUNER_PERIOD, HBASE_RS_HEAP_MEMORY_TUNER_DEFAULT_PERIOD), server); + super(server.getServerName() + "-HeapMemoryTunerChore", defaultChorePeriod, server); Class<? extends HeapMemoryTuner> tunerKlass = server.getConfiguration().getClass( HBASE_RS_HEAP_MEMORY_TUNER_CLASS, DefaultHeapMemoryTuner.class, HeapMemoryTuner.class); heapMemTuner = ReflectionUtils.newInstance(tunerKlass, server.getConfiguration()); @@ -213,6 +228,41 @@ public HeapMemoryTunerChore() { @Override protected void chore() { + // Sample heap occupancy + MemoryUsage memUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); + heapOccupancyPercent = (float)memUsage.getUsed() / (float)memUsage.getCommitted(); + // If we are above the heap occupancy alarm low watermark, switch to short + // sleeps for close monitoring. Stop autotuning, we are in a danger zone. + if (heapOccupancyPercent >= heapOccupancyLowWatermark) { + if (!alarming) { + LOG.warn("heapOccupancyPercent " + heapOccupancyPercent + + " is above heap occupancy alarm watermark (" + heapOccupancyLowWatermark + ")"); + alarming = true; + } + getSleeper().skipSleepCycle(); + try { + // Need to sleep ourselves since we've told the chore's sleeper + // to skip the next sleep cycle. + Thread.sleep(1000); + } catch (InterruptedException e) { + // Interrupted, propagate + Thread.currentThread().interrupt(); + } + } else { + if (alarming) { + LOG.info("heapOccupancyPercent " + heapOccupancyPercent + + " is now below the heap occupancy alarm watermark (" + + heapOccupancyLowWatermark + ")"); + alarming = false; + } + } + // Autotune if tuning is enabled and allowed + if (tunerOn && !alarming) { + tune(); + } + } + + private void tune() { evictCount = blockCache.getStats().getEvictedCount() - evictCount; tunerContext.setBlockedFlushCount(blockedFlushCount.getAndSet(0)); tunerContext.setUnblockedFlushCount(unblockedFlushCount.getAndSet(0)); diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionServerServices.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionServerServices.java index 08d038c8669e..3565195f8267 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionServerServices.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionServerServices.java @@ -149,4 +149,8 @@ void postOpenDeployTasks(final HRegion r) */ boolean registerService(Service service); + /** + * @return heap memory manager instance + */ + HeapMemoryManager getHeapMemoryManager(); } diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/MockRegionServerServices.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/MockRegionServerServices.java index e7111e2495b2..e6e98f28c4ac 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/MockRegionServerServices.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/MockRegionServerServices.java @@ -41,6 +41,7 @@ import org.apache.hadoop.hbase.regionserver.CompactionRequestor; import org.apache.hadoop.hbase.regionserver.FlushRequester; import org.apache.hadoop.hbase.regionserver.HRegion; +import org.apache.hadoop.hbase.regionserver.HeapMemoryManager; import org.apache.hadoop.hbase.regionserver.Leases; import org.apache.hadoop.hbase.regionserver.RegionServerAccounting; import org.apache.hadoop.hbase.regionserver.RegionServerServices; @@ -280,4 +281,9 @@ public boolean registerService(Service service) { // TODO Auto-generated method stub return false; } + + @Override + public HeapMemoryManager getHeapMemoryManager() { + return null; + } } diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/MockRegionServer.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/MockRegionServer.java index 82d224b022b9..0fc33db2467f 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/MockRegionServer.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/MockRegionServer.java @@ -94,6 +94,7 @@ import org.apache.hadoop.hbase.regionserver.CompactionRequestor; import org.apache.hadoop.hbase.regionserver.FlushRequester; import org.apache.hadoop.hbase.regionserver.HRegion; +import org.apache.hadoop.hbase.regionserver.HeapMemoryManager; import org.apache.hadoop.hbase.regionserver.Leases; import org.apache.hadoop.hbase.regionserver.RegionServerAccounting; import org.apache.hadoop.hbase.regionserver.RegionServerServices; @@ -614,4 +615,9 @@ public UpdateConfigurationResponse updateConfiguration( throws ServiceException { return null; } + + @Override + public HeapMemoryManager getHeapMemoryManager() { + return null; + } } \ No newline at end of file
ac2f8f35e385c6962c99b5ea2ab57eab73694753
Delta Spike
DELTASPIKE-289 add WindowContext API draft
a
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/AttributeAware.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/AttributeAware.java new file mode 100644 index 000000000..0638c6969 --- /dev/null +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/AttributeAware.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.core.spi; + + +import java.io.Serializable; + +/** + * This interface is just for internal use. + * It should ensure that refactorings don't lead to different method-names for the same purpose. + * Furthermore, it allows to easily find all artifacts which allow generic attributes. + */ +public interface AttributeAware extends Serializable +{ + /** + * Sets an attribute + * @param name name of the attribute + * @param value value of the attribute (null values aren't allowed) + * @return true if it was possible to set the value + */ + boolean setAttribute(String name, Object value); + + /** + * Returns true if there is a value for the given name + * @param name name of the argument in question + * @return true if there is a value for the given name, false otherwise + */ + boolean containsAttribute(String name); + + /** + * Exposes the value for the given name + * @param name name of the attribute + * @param targetType type of the attribute + * @param <T> current type + * @return value of the attribute, or null if there is no attribute with the given name + */ + <T> T getAttribute(String name, Class<T> targetType); +} diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java new file mode 100644 index 000000000..890cb40ab --- /dev/null +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.core.spi.scope.window; + +import org.apache.deltaspike.core.spi.AttributeAware; + +/** + * <p>We support the general notion of multiple 'windows'. + * That might be different parallel edit pages in a + * desktop application (think about different open documents + * in an editor) or multiple browser tabs in a + * web application.</p> + * <p>For web applications each browser tab or window will be + * represented by an own {@link WindowContext}. All those + * {@link WindowContext}s will be held in the users servlet + * session as &#064;SessionScoped bean. + * </p> + */ +public interface WindowContext extends AttributeAware +{ + /** + * @return the unique identifier for this window context + */ + String getWindowId(); + +} diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContextManager.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContextManager.java new file mode 100644 index 000000000..c131c5c2f --- /dev/null +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContextManager.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.core.spi.scope.window; + +/** + * <p>We support the general notion of multiple 'windows' + * That might be different parallel edit pages in a + * desktop application (think about different open documents + * in an editor) or multiple browser tabs in a + * web application.</p> + * <p>For web applications each browser tab or window will be + * represented by an own {@link WindowContext}. All those + * {@link WindowContext}s will be held in the users servlet + * session as &#064;SessionScoped bean. + * </p> + * <p>Every WindowContext is uniquely identified via a + * 'windowId'. Each Thread is associated with at most + * one single windowId at a time. The {@link WindowContextManager} + * is the interface which allows resolving the current <i>windowId</i> + * associated with this very Thread.</p> + */ +public interface WindowContextManager +{ + /** + * @return the <i>windowId</i> associated with the very Thread or <code>null</code>. + */ + String getCurrentWindowId(); + + /** + * Set the current windowId as the currently active for the very Thread. + * If no WindowContext exists with the very windowId we will create a new one. + * @param windowId + */ + void activateWindowContext(String windowId); + + /** + * @return the {@link WindowContext} associated with the very Thread or <code>null</code>. + */ + WindowContext getCurrentWindowContext(); + + /** + * close the WindowContext with the currently activated windowId for the very Thread. + * @return <code>true</code> if any did exist, <code>false</code> otherwise + */ + boolean closeCurrentWindowContext(); + + + /** + * Close all WindowContexts which are managed by the WindowContextManager. + * This is necessary when the session gets closed down. + * @return + */ + void closeAllWindowContexts(); + + +}
f4b4b023a3983531baf68542f35a318248dee6fa
kotlin
Introduce Variable: Support extraction of string- template fragments -KT-2089 Fixed--
a
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt index 50d6a8e82cb86..5df97b4d69fd5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt @@ -55,15 +55,25 @@ public class KtPsiFactory(private val project: Project) { return (createExpression("a?.b") as KtSafeQualifiedExpression).getOperationTokenNode() } - public fun createExpression(text: String): KtExpression { + private fun doCreateExpression(text: String): KtExpression { //TODO: '\n' below if important - some strange code indenting problems appear without it val expression = createProperty("val x =\n$text").getInitializer() ?: error("Failed to create expression from text: '$text'") + return expression + } + + public fun createExpression(text: String): KtExpression { + val expression = doCreateExpression(text) assert(expression.getText() == text) { "Failed to create expression from text: '$text', resulting expression's text was: '${expression.getText()}'" } return expression } + public fun createExpressionIfPossible(text: String): KtExpression? { + val expression = doCreateExpression(text) + return if (expression.getText() == text) expression else null + } + public fun createClassLiteral(className: String): KtClassLiteralExpression = createExpression("$className::class") as KtClassLiteralExpression @@ -291,6 +301,8 @@ public class KtPsiFactory(private val project: Project) { return stringTemplateExpression.getEntries()[0] as KtStringTemplateEntryWithExpression } + public fun createStringTemplate(content: String) = createExpression("\"$content\"") as KtStringTemplateExpression + public fun createPackageDirective(fqName: FqName): KtPackageDirective { return createFile("package ${fqName.asString()}").getPackageDirective()!! } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt index ddf33fe7354dc..e0b5338003d8e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt @@ -138,6 +138,8 @@ public fun PsiElement.getNextSiblingIgnoringWhitespaceAndComments(): PsiElement? return siblings(withItself = false).filter { it !is PsiWhiteSpace && it !is PsiComment }.firstOrNull() } +inline public fun <reified T : PsiElement> T.nextSiblingOfSameType() = PsiTreeUtil.getNextSiblingOfType(this, T::class.java) + public fun PsiElement?.isAncestor(element: PsiElement, strict: Boolean = false): Boolean { return PsiTreeUtil.isAncestor(this, element, strict) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java index e5aded5d0bfd1..342ad7b094fc9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java @@ -45,8 +45,8 @@ import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor; import org.jetbrains.kotlin.idea.KotlinBundle; import org.jetbrains.kotlin.idea.caches.resolve.ResolutionUtils; -import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils; import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde; +import org.jetbrains.kotlin.idea.refactoring.introduce.IntroduceUtilKt; import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers; import org.jetbrains.kotlin.idea.util.string.StringUtilKt; import org.jetbrains.kotlin.psi.*; @@ -489,7 +489,7 @@ public static String getExpressionShortText(@NotNull KtElement element) { //todo private static KtExpression findExpression( @NotNull KtFile file, int startOffset, int endOffset, boolean failOnNoExpression ) throws IntroduceRefactoringException { - KtExpression element = CodeInsightUtils.findExpression(file, startOffset, endOffset); + KtExpression element = IntroduceUtilKt.findExpressionOrStringFragment(file, startOffset, endOffset); if (element == null) { //todo: if it's infix expression => add (), then commit document then return new created expression diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt new file mode 100644 index 0000000000000..199d1db889d58 --- /dev/null +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt @@ -0,0 +1,99 @@ +/* + * Copyright 2010-2015 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.kotlin.idea.refactoring.introduce + +import com.intellij.openapi.util.Key +import com.intellij.openapi.util.TextRange +import com.intellij.psi.PsiElement +import org.jetbrains.kotlin.builtins.KotlinBuiltIns +import org.jetbrains.kotlin.idea.analysis.analyzeInContext +import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade +import org.jetbrains.kotlin.idea.util.getResolutionScope +import org.jetbrains.kotlin.psi.* +import org.jetbrains.kotlin.psi.psiUtil.endOffset +import org.jetbrains.kotlin.psi.psiUtil.nextSiblingOfSameType +import org.jetbrains.kotlin.psi.psiUtil.startOffset +import org.jetbrains.kotlin.resolve.DelegatingBindingTrace +import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator +import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.TypeUtils + +class ExtractableSubstringInfo( + val startEntry: KtStringTemplateEntry, + val endEntry: KtStringTemplateEntry, + val prefix: String, + val suffix: String, + type: KotlinType? = null +) { + private fun guessLiteralType(literal: String): KotlinType { + val facade = template.getResolutionFacade() + val builtIns = facade.moduleDescriptor.builtIns + val stringType = builtIns.stringType + + if (startEntry != endEntry || startEntry !is KtLiteralStringTemplateEntry) return stringType + + val expr = KtPsiFactory(startEntry).createExpressionIfPossible(literal) ?: return stringType + + val context = facade.analyze(template, BodyResolveMode.PARTIAL) + val scope = template.getResolutionScope(context, facade) + + val tempContext = expr.analyzeInContext(scope, template) + val trace = DelegatingBindingTrace(tempContext, "Evaluate '$literal'") + val value = ConstantExpressionEvaluator(builtIns).evaluateExpression(expr, trace) + if (value == null || value.isError) return stringType + + return value.toConstantValue(TypeUtils.NO_EXPECTED_TYPE).type + } + + val template: KtStringTemplateExpression = startEntry.parent as KtStringTemplateExpression + + val content = with(entries.map { it.text }.joinToString(separator = "")) { substring(prefix.length, length - suffix.length) } + + val type = type ?: guessLiteralType(content) + + val contentRange: TextRange + get() = TextRange(startEntry.startOffset + prefix.length, endEntry.endOffset - suffix.length) + + val entries: Sequence<KtStringTemplateEntry> + get() = sequence(startEntry) { if (it != endEntry) it.nextSiblingOfSameType() else null } + + fun createExpression(): KtExpression { + val quote = template.firstChild.text + val literalValue = if (KotlinBuiltIns.isString(type)) "$quote$content$quote" else content + return KtPsiFactory(startEntry).createExpression(literalValue).apply { extractableSubstringInfo = this@ExtractableSubstringInfo } + } + + fun copy(newTemplate: KtStringTemplateExpression): ExtractableSubstringInfo { + val oldEntries = template.entries + val newEntries = newTemplate.entries + val startIndex = oldEntries.indexOf(startEntry) + val endIndex = oldEntries.indexOf(endEntry) + if (startIndex < 0 || startIndex >= newEntries.size || endIndex < 0 || endIndex >= newEntries.size) { + throw AssertionError("Old template($startIndex..$endIndex): ${template.text}, new template: ${newTemplate.text}") + } + return ExtractableSubstringInfo(newEntries[startIndex], newEntries[endIndex], prefix, suffix, type) + } +} + +var KtExpression.extractableSubstringInfo: ExtractableSubstringInfo? by UserDataProperty(Key.create("EXTRACTED_SUBSTRING_INFO")) + +val KtExpression.substringContextOrThis: KtExpression + get() = extractableSubstringInfo?.template ?: this + +val PsiElement.substringContextOrThis: PsiElement + get() = (this as? KtExpression)?.extractableSubstringInfo?.template ?: this \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt index b8f2307c7f409..a40368b276ef3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt @@ -20,17 +20,16 @@ import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key +import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils import org.jetbrains.kotlin.idea.core.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringBundle import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringUtil -import org.jetbrains.kotlin.psi.KtExpression -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType -import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType -import org.jetbrains.kotlin.psi.psiUtil.getOutermostParentContainedIn +import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiRange +import org.jetbrains.kotlin.psi.* +import org.jetbrains.kotlin.psi.psiUtil.* fun showErrorHint(project: Project, editor: Editor, message: String, title: String) { CodeInsightUtils.showErrorHint(project, editor, message, title, null) @@ -48,8 +47,9 @@ fun selectElementsWithTargetSibling( continuation: (elements: List<PsiElement>, targetSibling: PsiElement) -> Unit ) { fun onSelectionComplete(elements: List<PsiElement>, targetContainer: PsiElement) { - val parent = PsiTreeUtil.findCommonParent(elements) - ?: throw AssertionError("Should have at least one parent: ${elements.joinToString("\n")}") + val physicalElements = elements.map { it.substringContextOrThis } + val parent = PsiTreeUtil.findCommonParent(physicalElements) + ?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}") if (parent == targetContainer) { continuation(elements, elements.first()) @@ -80,8 +80,9 @@ fun selectElementsWithTargetParent( } fun selectTargetContainer(elements: List<PsiElement>) { - val parent = PsiTreeUtil.findCommonParent(elements) - ?: throw AssertionError("Should have at least one parent: ${elements.joinToString("\n")}") + val physicalElements = elements.map { it.substringContextOrThis } + val parent = PsiTreeUtil.findCommonParent(physicalElements) + ?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}") val containers = getContainers(elements, parent) if (containers.isEmpty()) { @@ -147,3 +148,29 @@ fun PsiElement.findExpressionsByCopyableDataAndClearIt(key: Key<Boolean>): List< results.forEach { it.putCopyableUserData(key, null) } return results } + +fun findExpressionOrStringFragment(file: KtFile, startOffset: Int, endOffset: Int): KtExpression? { + CodeInsightUtils.findExpression(file, startOffset, endOffset)?.let { return it } + + val entry1 = file.findElementAt(startOffset)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null + val entry2 = file.findElementAt(endOffset - 1)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null + + if (entry1 == entry2 && entry1 is KtStringTemplateEntryWithExpression) return entry1.expression + + val stringTemplate = entry1.parent as? KtStringTemplateExpression ?: return null + if (entry2.parent != stringTemplate) return null + + val templateOffset = stringTemplate.startOffset + if (stringTemplate.getContentRange().equalsToRange(startOffset - templateOffset, endOffset - templateOffset)) return stringTemplate + + val prefixOffset = startOffset - entry1.startOffset + if (entry1 !is KtLiteralStringTemplateEntry && prefixOffset > 0) return null + + val suffixOffset = endOffset - entry2.startOffset + if (entry2 !is KtLiteralStringTemplateEntry && suffixOffset < entry2.textLength) return null + + val prefix = entry1.text.substring(0, prefixOffset) + val suffix = entry2.text.substring(suffixOffset) + + return ExtractableSubstringInfo(entry1, entry2, prefix, suffix).createExpression() +} \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt index 148341563a763..e4cfdf65b19a9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt @@ -21,6 +21,7 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key +import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile @@ -45,10 +46,7 @@ import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention import org.jetbrains.kotlin.idea.intentions.RemoveCurlyBracesFromTemplateIntention import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringBundle import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringUtil -import org.jetbrains.kotlin.idea.refactoring.introduce.KotlinIntroduceHandlerBase -import org.jetbrains.kotlin.idea.refactoring.introduce.findElementByCopyableDataAndClearIt -import org.jetbrains.kotlin.idea.refactoring.introduce.findExpressionByCopyableDataAndClearIt -import org.jetbrains.kotlin.idea.refactoring.introduce.findExpressionsByCopyableDataAndClearIt +import org.jetbrains.kotlin.idea.refactoring.introduce.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.ShortenReferences @@ -105,17 +103,34 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { return newContainer.findElementAt(offset)?.parentsWithSelf?.firstOrNull { (it as? KtExpression)?.text == text } } - private fun replaceExpression(replace: KtExpression, addToReferences: Boolean): KtExpression { - val isActualExpression = expression == replace + private fun replaceExpression(expressionToReplace: KtExpression, addToReferences: Boolean): KtExpression { + val isActualExpression = expression == expressionToReplace val replacement = psiFactory.createExpression(nameSuggestion) - var result = if (replace.isFunctionLiteralOutsideParentheses()) { - val functionLiteralArgument = replace.getStrictParentOfType<KtFunctionLiteralArgument>()!! + val substringInfo = expressionToReplace.extractableSubstringInfo + var result = if (expressionToReplace.isFunctionLiteralOutsideParentheses()) { + val functionLiteralArgument = expressionToReplace.getStrictParentOfType<KtFunctionLiteralArgument>()!! val newCallExpression = functionLiteralArgument.moveInsideParenthesesAndReplaceWith(replacement, bindingContext) newCallExpression.valueArguments.last().getArgumentExpression()!! } + else if (substringInfo != null) { + with(substringInfo) { + val parent = startEntry.parent + + psiFactory.createStringTemplate(prefix).entries.singleOrNull()?.let { parent.addBefore(it, startEntry) } + + val refEntry = psiFactory.createBlockStringTemplateEntry(replacement) + val addedRefEntry = parent.addBefore(refEntry, startEntry) as KtStringTemplateEntryWithExpression + + psiFactory.createStringTemplate(suffix).entries.singleOrNull()?.let { parent.addAfter(it, endEntry) } + + parent.deleteChildRange(startEntry, endEntry) + + addedRefEntry.expression!! + } + } else { - replace.replace(replacement) as KtExpression + expressionToReplace.replace(replacement) as KtExpression } val parent = result.parent @@ -279,7 +294,7 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { expression.putCopyableUserData(EXPRESSION_KEY, true) for (replace in allReplaces) { - replace.putCopyableUserData(REPLACE_KEY, true) + replace.substringContextOrThis.putCopyableUserData(REPLACE_KEY, true) } commonParent.putCopyableUserData(COMMON_PARENT_KEY, true) @@ -290,7 +305,12 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { val newExpression = newCommonContainer.findExpressionByCopyableDataAndClearIt(EXPRESSION_KEY) val newCommonParent = newCommonContainer.findElementByCopyableDataAndClearIt(COMMON_PARENT_KEY) - val newAllReplaces = newCommonContainer.findExpressionsByCopyableDataAndClearIt(REPLACE_KEY) + val newAllReplaces = (allReplaces zip newCommonContainer.findExpressionsByCopyableDataAndClearIt(REPLACE_KEY)).map { + val (originalReplace, newReplace) = it + originalReplace.extractableSubstringInfo?.let { + originalReplace.apply { extractableSubstringInfo = it.copy(newReplace as KtStringTemplateExpression) } + } ?: newReplace + } runRefactoring(newExpression, newCommonContainer, newCommonParent, newAllReplaces) } @@ -299,7 +319,7 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { private fun calculateAnchor(commonParent: PsiElement, commonContainer: PsiElement, allReplaces: List<KtExpression>): PsiElement? { if (commonParent != commonContainer) return commonParent.parentsWithSelf.firstOrNull { it.parent == commonContainer } - val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> Math.min(offset, expr.startOffset) } + val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> Math.min(offset, expr.substringContextOrThis.startOffset) } return commonContainer.allChildren.lastOrNull { it.textRange.contains(startOffset) } ?: return null } @@ -376,38 +396,42 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { occurrencesToReplace: List<KtExpression>?, onNonInteractiveFinish: ((KtProperty) -> Unit)? ) { - val parent = expression.parent + val substringInfo = expression.extractableSubstringInfo + val physicalExpression = expression.substringContextOrThis + + val parent = physicalExpression.parent when { parent is KtQualifiedExpression -> { - if (parent.receiverExpression != expression) { + if (parent.receiverExpression != physicalExpression) { return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) } } - expression is KtStatementExpression -> + physicalExpression is KtStatementExpression -> return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) - parent is KtOperationExpression && parent.operationReference == expression -> + parent is KtOperationExpression && parent.operationReference == physicalExpression -> return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) } - PsiTreeUtil.getNonStrictParentOfType(expression, + PsiTreeUtil.getNonStrictParentOfType(physicalExpression, KtTypeReference::class.java, KtConstructorCalleeExpression::class.java, KtSuperExpression::class.java)?.let { return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.container")) } - val expressionType = bindingContext.getType(expression) //can be null or error type - val scope = expression.getResolutionScope(bindingContext, resolutionFacade) - val dataFlowInfo = bindingContext.getDataFlowInfo(expression) + val expressionType = substringInfo?.type ?: bindingContext.getType(physicalExpression) //can be null or error type + val scope = physicalExpression.getResolutionScope(bindingContext, resolutionFacade) + val dataFlowInfo = bindingContext.getDataFlowInfo(physicalExpression) val bindingTrace = ObservableBindingTrace(BindingTraceContext()) - val typeNoExpectedType = expression.computeTypeInfoInContext(scope, expression, bindingTrace, dataFlowInfo).type + val typeNoExpectedType = substringInfo?.type + ?: physicalExpression.computeTypeInfoInContext(scope, physicalExpression, bindingTrace, dataFlowInfo).type val noTypeInference = expressionType != null && typeNoExpectedType != null && !KotlinTypeChecker.DEFAULT.equalTypes(expressionType, typeNoExpectedType) - if (expressionType == null && bindingContext.get(BindingContext.QUALIFIER, expression) != null) { + if (expressionType == null && bindingContext.get(BindingContext.QUALIFIER, physicalExpression) != null) { return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.package.expression")) } @@ -426,9 +450,11 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { OccurrencesChooser.ReplaceChoice.ALL -> allOccurrences else -> listOf(expression) } - val replaceOccurrence = expression.shouldReplaceOccurrence(bindingContext, container) || allReplaces.size > 1 + val replaceOccurrence = substringInfo != null + || expression.shouldReplaceOccurrence(bindingContext, container) + || allReplaces.size > 1 - val commonParent = PsiTreeUtil.findCommonParent(allReplaces) as KtElement + val commonParent = PsiTreeUtil.findCommonParent(allReplaces.map { it.substringContextOrThis }) as KtElement var commonContainer = commonParent.getContainer()!! if (commonContainer != container && container.isAncestor(commonContainer, true)) { commonContainer = container @@ -439,7 +465,11 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { calculateAnchor(commonParent, commonContainer, allReplaces), NewDeclarationNameValidator.Target.VARIABLES ) - val suggestedNames = KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, "value") + val suggestedNames = KotlinNameSuggester.suggestNamesByExpressionAndType(expression, + substringInfo?.type, + bindingContext, + validator, + "value") val introduceVariableContext = IntroduceVariableContext( expression, suggestedNames.iterator().next(), allReplaces, commonContainer, commonParent, replaceOccurrence, noTypeInference, expressionType, bindingContext, resolutionFacade @@ -477,7 +507,12 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { } if (isInplaceAvailable && occurrencesToReplace == null) { - OccurrencesChooser.simpleChooser<KtExpression>(editor).showChooser(expression, allOccurrences, callback) + val chooser = object: OccurrencesChooser<KtExpression>(editor) { + override fun getOccurrenceRange(occurrence: KtExpression): TextRange? { + return occurrence.extractableSubstringInfo?.contentRange ?: occurrence.textRange + } + } + chooser.showChooser(expression, allOccurrences, callback) } else { callback.pass(OccurrencesChooser.ReplaceChoice.ALL) @@ -494,13 +529,17 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { resolutionFacade: ResolutionFacade, originalContext: BindingContext ): List<Pair<KtElement, KtElement>> { - val file = getContainingKtFile() + val physicalExpression = substringContextOrThis + val contentRange = extractableSubstringInfo?.contentRange - val references = collectDescendantsOfType<KtReferenceExpression>() + val file = physicalExpression.getContainingKtFile() + + val references = physicalExpression + .collectDescendantsOfType<KtReferenceExpression> { contentRange == null || contentRange.contains(it.textRange) } fun isResolvableNextTo(neighbour: KtExpression): Boolean { val scope = neighbour.getResolutionScope(originalContext, resolutionFacade) - val newContext = analyzeInContext(scope, neighbour) + val newContext = physicalExpression.analyzeInContext(scope, neighbour) val project = file.project return references.all { val originalDescriptor = originalContext[BindingContext.REFERENCE_TARGET, it] @@ -515,8 +554,8 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { } } - val firstContainer = getContainer() ?: return emptyList() - val firstOccurrenceContainer = getOccurrenceContainer() ?: return emptyList() + val firstContainer = physicalExpression.getContainer() ?: return emptyList() + val firstOccurrenceContainer = physicalExpression.getOccurrenceContainer() ?: return emptyList() val containers = SmartList(firstContainer) val occurrenceContainers = SmartList(firstOccurrenceContainer) @@ -554,8 +593,10 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { val expression = expressionToExtract?.let { KtPsiUtil.safeDeparenthesize(it) } ?: return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) - val resolutionFacade = expression.getResolutionFacade() - val bindingContext = resolutionFacade.analyze(expression, BodyResolveMode.FULL) + val physicalExpression = expression.substringContextOrThis + + val resolutionFacade = physicalExpression.getResolutionFacade() + val bindingContext = resolutionFacade.analyze(physicalExpression, BodyResolveMode.FULL) fun runWithChosenContainers(container: KtElement, occurrenceContainer: KtElement) { doRefactoring(project, editor, expression, container, occurrenceContainer, resolutionFacade, bindingContext, occurrencesToReplace, onNonInteractiveFinish) @@ -580,6 +621,7 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) { if (file !is KtFile) return + try { KotlinRefactoringUtil.selectExpression(editor, file) { doRefactoring(project, editor, it, null, null) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt b/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt index 8a2eea70be839..0539b523418dd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt +++ b/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt @@ -23,6 +23,8 @@ import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.core.refactoring.getContextForContainingDeclarationBody +import org.jetbrains.kotlin.idea.refactoring.introduce.ExtractableSubstringInfo +import org.jetbrains.kotlin.idea.refactoring.introduce.extractableSubstringInfo import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiRange.Empty import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnificationResult.* @@ -60,7 +62,7 @@ public interface UnificationResult { override fun and(other: Status): Status = this }; - public abstract fun and(other: Status): Status + public abstract infix fun and(other: Status): Status } object Unmatched : UnificationResult { @@ -111,6 +113,7 @@ public class KotlinPsiUnifier( val declarationPatternsToTargets = MultiMap<DeclarationDescriptor, DeclarationDescriptor>() val weakMatches = HashMap<KtElement, KtElement>() var checkEquivalence: Boolean = false + var targetSubstringInfo: ExtractableSubstringInfo? = null private fun KotlinPsiRange.getBindingContext(): BindingContext { val element = (this as? KotlinPsiRange.ListRange)?.startElement as? KtElement @@ -702,7 +705,73 @@ public class KotlinPsiUnifier( return targetElementType != null && KotlinTypeChecker.DEFAULT.isSubtypeOf(targetElementType, parameter.expectedType) } + private fun doUnifyStringTemplateFragments(target: KtStringTemplateExpression, pattern: ExtractableSubstringInfo): Status { + val prefixLength = pattern.prefix.length + val suffixLength = pattern.suffix.length + val targetEntries = target.entries + val patternEntries = pattern.entries.toList() + for ((index, targetEntry) in targetEntries.withIndex()) { + if (index + patternEntries.size > targetEntries.size) return UNMATCHED + + val targetEntryText = targetEntry.text + + if (pattern.startEntry == pattern.endEntry && (prefixLength > 0 || suffixLength > 0)) { + if (targetEntry !is KtLiteralStringTemplateEntry) continue + + val patternText = with(pattern.startEntry.text) { substring(prefixLength, length - suffixLength) } + val i = targetEntryText.indexOf(patternText) + if (i < 0) continue + val targetPrefix = targetEntryText.substring(0, i) + val targetSuffix = targetEntryText.substring(i + patternText.length) + targetSubstringInfo = ExtractableSubstringInfo(targetEntry, targetEntry, targetPrefix, targetSuffix, pattern.type) + return MATCHED + } + + val matchStartByText = pattern.startEntry is KtLiteralStringTemplateEntry + val matchEndByText = pattern.endEntry is KtLiteralStringTemplateEntry + + val targetPrefix = if (matchStartByText) { + if (targetEntry !is KtLiteralStringTemplateEntry) continue + + val patternText = pattern.startEntry.text.substring(prefixLength) + if (!targetEntryText.endsWith(patternText)) continue + targetEntryText.substring(0, targetEntryText.length - patternText.length) + } + else "" + + val lastTargetEntry = targetEntries[index + patternEntries.lastIndex] + + val targetSuffix = if (matchEndByText) { + if (lastTargetEntry !is KtLiteralStringTemplateEntry) continue + + val patternText = with(pattern.endEntry.text) { substring(0, length - suffixLength) } + val lastTargetEntryText = lastTargetEntry.text + if (!lastTargetEntryText.startsWith(patternText)) continue + lastTargetEntryText.substring(patternText.length) + } + else "" + + val fromIndex = if (matchStartByText) 1 else 0 + val toIndex = if (matchEndByText) patternEntries.lastIndex - 1 else patternEntries.lastIndex + val status = (fromIndex..toIndex).fold(MATCHED) { s, patternEntryIndex -> + val targetEntryToUnify = targetEntries[index + patternEntryIndex] + val patternEntryToUnify = patternEntries[patternEntryIndex] + if (s != UNMATCHED) s and doUnify(targetEntryToUnify, patternEntryToUnify) else s + } + if (status == UNMATCHED) continue + targetSubstringInfo = ExtractableSubstringInfo(targetEntry, lastTargetEntry, targetPrefix, targetSuffix, pattern.type) + return status + } + + return UNMATCHED + } + fun doUnify(target: KotlinPsiRange, pattern: KotlinPsiRange): Status { + (pattern.elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.let { + val targetTemplate = target.elements.singleOrNull() as? KtStringTemplateExpression ?: return UNMATCHED + return doUnifyStringTemplateFragments(targetTemplate, it) + } + val targetElements = target.elements val patternElements = pattern.elements if (targetElements.size() != patternElements.size()) return UNMATCHED @@ -828,8 +897,14 @@ public class KotlinPsiUnifier( when { substitution.size() != descriptorToParameter.size() -> Unmatched - status == MATCHED -> - if (weakMatches.isEmpty()) StronglyMatched(target, substitution) else WeaklyMatched(target, substitution, weakMatches) + status == MATCHED -> { + val targetRange = targetSubstringInfo?.createExpression()?.toRange() ?: target + if (weakMatches.isEmpty()) { + StronglyMatched(targetRange, substitution) + } else { + WeaklyMatched(targetRange, substitution, weakMatches) + } + } else -> Unmatched } diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt new file mode 100644 index 0000000000000..8d3f78f7b2c84 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt @@ -0,0 +1,3 @@ +fun foo(param: Int): String { + return "<selection>abc${pa</selection>ram}def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt.conflicts b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt.conflicts new file mode 100644 index 0000000000000..0c9a536b18e6d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt.conflicts @@ -0,0 +1 @@ +Cannot find an expression to introduce \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt new file mode 100644 index 0000000000000..a7ef59f2d4287 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt @@ -0,0 +1,3 @@ +fun foo(param: Int): String { + return "<selection>abc$pa</selection>ram" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt.conflicts b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt.conflicts new file mode 100644 index 0000000000000..0c9a536b18e6d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt.conflicts @@ -0,0 +1 @@ +Cannot find an expression to introduce \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt new file mode 100644 index 0000000000000..3cc3e6f347136 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt @@ -0,0 +1,3 @@ +fun foo(a: Int): String { + return "<selection>abc$a\</selection>ndef" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt.conflicts b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt.conflicts new file mode 100644 index 0000000000000..0c9a536b18e6d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt.conflicts @@ -0,0 +1 @@ +Cannot find an expression to introduce \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt new file mode 100644 index 0000000000000..1ec4ee42caffa --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt @@ -0,0 +1,6 @@ +fun foo(param: Int): String { + val x = "xyfalsez" + val y = "xyFalsez" + val z = false + return "ab<selection>false</selection>def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt.after new file mode 100644 index 0000000000000..39c2dc543c645 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt.after @@ -0,0 +1,7 @@ +fun foo(param: Int): String { + val b = false + val x = "xy${b}z" + val y = "xyFalsez" + val z = false + return "ab${b}def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt new file mode 100644 index 0000000000000..826c73d618f23 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt @@ -0,0 +1,7 @@ +fun foo(param: Int): String { + val x = "a1234_" + val y = "-4123a" + val z = "+1243a" + val u = 123 + return "ab<selection>123</selection>def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt.after new file mode 100644 index 0000000000000..7be885da6e484 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt.after @@ -0,0 +1,8 @@ +fun foo(param: Int): String { + val i = 123 + val x = "a${i}4_" + val y = "-4${i}a" + val z = "+1243a" + val u = 123 + return "ab${i}def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt new file mode 100644 index 0000000000000..7d6dde9721900 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt @@ -0,0 +1,6 @@ +fun foo(param: Int): String { + val x = "atrue123" + val x = "aTRUE123" + val z = true + return "ab<selection>true</selection>def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt.after new file mode 100644 index 0000000000000..ba078c9b293ee --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt.after @@ -0,0 +1,7 @@ +fun foo(param: Int): String { + val b = true + val x = "a${b}123" + val x = "aTRUE123" + val z = true + return "ab${b}def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt new file mode 100644 index 0000000000000..8b10cb97d4cbb --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = "abc$a" + val y = "abc${a}" + val z = "abc{$a}def" + return "<selection>abc$a</selection>" + "def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt.after new file mode 100644 index 0000000000000..2e2d3540f7ce0 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = "abc$a" + val x = s + val y = s + val z = "abc{$a}def" + return s + "def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt new file mode 100644 index 0000000000000..2a19834a5bc67 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = "-${a + 1}" + val y = "x${a + 1}y" + val z = "x${a - 1}y" + return "abc<selection>${a + 1}</selection>def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt.after new file mode 100644 index 0000000000000..920ba830a2157 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val i = a + 1 + val x = "-$i" + val y = "x${i}y" + val z = "x${a - 1}y" + return "abc${i}def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt new file mode 100644 index 0000000000000..b3e5ea58080b3 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = "-$a" + val y = "x${a}y" + val z = "x$ay" + return "abc<selection>${a}</selection>def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt.after new file mode 100644 index 0000000000000..60d242b3bb83d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val a1 = a + val x = "-$a1" + val y = "x${a1}y" + val z = "x$ay" + return "abc${a1}def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt new file mode 100644 index 0000000000000..e059fcf97328b --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt @@ -0,0 +1,5 @@ +fun foo(a: Int): String { + val x = "+cd$a:${a + 1}efg" + val y = "+cd$a${a + 1}efg" + return "ab<selection>cd$a:${a + 1}ef</selection>" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt.after new file mode 100644 index 0000000000000..3bc1c2c2842a1 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt.after @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val s = "cd$a:${a + 1}ef" + val x = "+${s}g" + val y = "+cd$a${a + 1}efg" + return "ab$s" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt new file mode 100644 index 0000000000000..e81ce108d0de8 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt @@ -0,0 +1,5 @@ +fun foo(a: Int): String { + val x = "_c$a:${a + 1}d_" + val y = "_$a:${a + 1}d_" + return "ab<selection>c$a:${a + 1}d</selection>ef" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt.after new file mode 100644 index 0000000000000..fc66f321bf26e --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt.after @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val s = "c$a:${a + 1}d" + val x = "_${s}_" + val y = "_$a:${a + 1}d_" + return "ab${s}ef" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt new file mode 100644 index 0000000000000..f77d65ff3a28c --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt @@ -0,0 +1,5 @@ +fun foo(a: Int): String { + val x = "_ab$a:${a + 1}cd__" + val y = "_a$a:${a + 1}cd__" + return "<selection>ab$a:${a + 1}cd</selection>ef" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt.after new file mode 100644 index 0000000000000..58ec28df9cd03 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt.after @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val s = "ab$a:${a + 1}cd" + val x = "_${s}__" + val y = "_a$a:${a + 1}cd__" + return "${s}ef" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt new file mode 100644 index 0000000000000..d4f1d34ed57dc --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt @@ -0,0 +1,9 @@ +fun foo(a: Int): String { + val x = """_c$a + :${a + 1}d_""" + val y = "_$a:${a + 1}d_" + val z = """_c$a:${a + 1}d_""" + val u = "_c$a\n:${a + 1}d_" + return """ab<selection>c$a + :${a + 1}d</selection>ef""" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt.after new file mode 100644 index 0000000000000..31a44acbe3f34 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt.after @@ -0,0 +1,9 @@ +fun foo(a: Int): String { + val s = """c$a + :${a + 1}d""" + val x = """_${s}_""" + val y = "_$a:${a + 1}d_" + val z = """_c$a:${a + 1}d_""" + val u = "_c$a\n:${a + 1}d_" + return """ab${s}ef""" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt new file mode 100644 index 0000000000000..9dc8211a168fb --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = "xabc$a" + val y = "${a}abcx" + val z = "xacb$a" + return "<selection>abc</selection>def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt.after new file mode 100644 index 0000000000000..fb4778f7e0761 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = "abc" + val x = "x$s$a" + val y = "${a}${s}x" + val z = "xacb$a" + return "${s}def" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt new file mode 100644 index 0000000000000..091f98c39f182 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = "xcd$a" + val y = "${a}cdx" + val z = "xcf$a" + return "ab<selection>cd</selection>ef" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt.after new file mode 100644 index 0000000000000..f83413680bb83 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = "cd" + val x = "x$s$a" + val y = "${a}${s}x" + val z = "xcf$a" + return "ab${s}ef" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt new file mode 100644 index 0000000000000..53d3c4eff519e --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = "xdef$a" + val y = "${a}defx" + val z = "xddf$a" + return "abc<selection>def</selection>" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt.after new file mode 100644 index 0000000000000..ca6300ff3806c --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = "def" + val x = "x$s$a" + val y = "${a}${s}x" + val z = "xddf$a" + return "abc$s" +} \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java index 1f1abfd5543ab..2f0a0c80f16ee 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java @@ -507,6 +507,111 @@ public void testOuterItInsideNestedLamba() throws Exception { doIntroduceVariableTest(fileName); } } + + @TestMetadata("idea/testData/refactoring/introduceVariable/stringTemplates") + @TestDataPath("$PROJECT_ROOT") + @RunWith(JUnit3RunnerWithInners.class) + public static class StringTemplates extends AbstractExtractionTest { + public void testAllFilesPresentInStringTemplates() throws Exception { + KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/refactoring/introduceVariable/stringTemplates"), Pattern.compile("^(.+)\\.kt$"), true); + } + + @TestMetadata("brokenEntryWithBlockExpr.kt") + public void testBrokenEntryWithBlockExpr() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("brokenEntryWithExpr.kt") + public void testBrokenEntryWithExpr() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("brokenEscapeEntry.kt") + public void testBrokenEscapeEntry() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("extractFalse.kt") + public void testExtractFalse() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("extractIntegerLiteral.kt") + public void testExtractIntegerLiteral() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("extractTrue.kt") + public void testExtractTrue() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("fullContent.kt") + public void testFullContent() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("fullEntryWithBlockExpr.kt") + public void testFullEntryWithBlockExpr() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("fullEntryWithSimpleName.kt") + public void testFullEntryWithSimpleName() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("multipleEntriesWithPrefix.kt") + public void testMultipleEntriesWithPrefix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("multipleEntriesWithSubstring.kt") + public void testMultipleEntriesWithSubstring() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("multipleEntriesWithSuffix.kt") + public void testMultipleEntriesWithSuffix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("rawTemplateWithSubstring.kt") + public void testRawTemplateWithSubstring() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("singleEntryPrefix.kt") + public void testSingleEntryPrefix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("singleEntrySubstring.kt") + public void testSingleEntrySubstring() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt"); + doIntroduceVariableTest(fileName); + } + + @TestMetadata("singleEntrySuffix.kt") + public void testSingleEntrySuffix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt"); + doIntroduceVariableTest(fileName); + } + } } @TestMetadata("idea/testData/refactoring/extractFunction")
a376c8da9d3fa0e8b600b69cdc30c9fb0d303709
hbase
HBASE-12366 Add login code to HBase Canary tool- (Srikanth Srungarapu)--
a
https://github.com/apache/hbase
diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/AuthUtil.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/AuthUtil.java new file mode 100644 index 000000000000..bdc68377659b --- /dev/null +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/AuthUtil.java @@ -0,0 +1,98 @@ +/* + * 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.hbase; + +import java.io.IOException; +import java.net.UnknownHostException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.classification.InterfaceAudience; +import org.apache.hadoop.hbase.classification.InterfaceStability; +import org.apache.hadoop.hbase.security.UserProvider; +import org.apache.hadoop.hbase.util.Strings; +import org.apache.hadoop.hbase.util.Threads; +import org.apache.hadoop.net.DNS; +import org.apache.hadoop.security.UserGroupInformation; + +/** + * Utility methods for helping with security tasks. + */ [email protected] [email protected] +public class AuthUtil { + private static final Log LOG = LogFactory.getLog(AuthUtil.class); + /** + * Checks if security is enabled and if so, launches chore for refreshing kerberos ticket. + */ + public static void launchAuthChore(Configuration conf) throws IOException { + UserProvider userProvider = UserProvider.instantiate(conf); + // login the principal (if using secure Hadoop) + boolean securityEnabled = + userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled(); + if (!securityEnabled) return; + String host = null; + try { + host = Strings.domainNamePointerToHostName(DNS.getDefaultHost( + conf.get("hbase.client.dns.interface", "default"), + conf.get("hbase.client.dns.nameserver", "default"))); + userProvider.login("hbase.client.keytab.file", "hbase.client.kerberos.principal", host); + } catch (UnknownHostException e) { + LOG.error("Error resolving host name"); + throw e; + } catch (IOException e) { + LOG.error("Error while trying to perform the initial login"); + throw e; + } + + final UserGroupInformation ugi = userProvider.getCurrent().getUGI(); + Stoppable stoppable = new Stoppable() { + private volatile boolean isStopped = false; + + @Override + public void stop(String why) { + isStopped = true; + } + + @Override + public boolean isStopped() { + return isStopped; + } + }; + + // if you're in debug mode this is useful to avoid getting spammed by the getTGT() + // you can increase this, keeping in mind that the default refresh window is 0.8 + // e.g. 5min tgt * 0.8 = 4min refresh so interval is better be way less than 1min + final int CHECK_TGT_INTERVAL = 30 * 1000; // 30sec + + Chore refreshCredentials = new Chore("RefreshCredentials", CHECK_TGT_INTERVAL, stoppable) { + @Override + protected void chore() { + try { + ugi.checkTGTAndReloginFromKeytab(); + } catch (IOException e) { + LOG.info("Got exception while trying to refresh credentials "); + } + } + }; + // Start the chore for refreshing credentials + Threads.setDaemonThreadRunning(refreshCredentials.getThread()); + } +} diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java index e6e975f165bc..539ba70be2ea 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java @@ -34,6 +34,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.AuthUtil; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; @@ -755,7 +756,9 @@ private Map<String, List<HRegionInfo>> doFilterRegionServerByName( } public static void main(String[] args) throws Exception { - int exitCode = ToolRunner.run(HBaseConfiguration.create(), new Canary(), args); + final Configuration conf = HBaseConfiguration.create(); + AuthUtil.launchAuthChore(conf); + int exitCode = ToolRunner.run(conf, new Canary(), args); System.exit(exitCode); } }
5824fa23d60acca2edd40f1eec0c4687199f0124
camel
CAMEL-1933: Overhaul of JMX. Routes can now be- started/stopped.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@808328 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/CamelContext.java b/camel-core/src/main/java/org/apache/camel/CamelContext.java index bbf01de86716e..a3d862ec94b5f 100644 --- a/camel-core/src/main/java/org/apache/camel/CamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/CamelContext.java @@ -258,18 +258,53 @@ public interface CamelContext extends Service, RuntimeConfiguration { * * @param route the route to start * @throws Exception is thrown if the route could not be started for whatever reason + * @deprecated will be removed in Camel 2.2 */ void startRoute(RouteDefinition route) throws Exception; + /** + * Starts the given route if it has been previously stopped + * + * @param routeId the route id + * @throws Exception is thrown if the route could not be started for whatever reason + */ + void startRoute(String routeId) throws Exception; + /** * Stops the given route. It will remain in the list of route definitions return by {@link #getRouteDefinitions()} * unless you use the {@link #removeRouteDefinitions(java.util.Collection)} * * @param route the route to stop * @throws Exception is thrown if the route could not be stopped for whatever reason + * @deprecated will be removed in Camel 2.2 */ void stopRoute(RouteDefinition route) throws Exception; + /** + * Stops the given route. It will remain in the list of route definitions return by {@link #getRouteDefinitions()} + * unless you use the {@link #removeRouteDefinitions(java.util.Collection)} + * + * @param routeId the route id + * @throws Exception is thrown if the route could not be stopped for whatever reason + */ + void stopRoute(String routeId) throws Exception; + + /** + * Returns the current status of the given route + * + * @param routeId the route id + * @return the status for the route + */ + ServiceStatus getRouteStatus(String routeId); + + /** + * Returns the current status of the given route + * + * @param route the route + * @return the status for the route + * @deprecated will be removed in Camel 2.2 + */ + ServiceStatus getRouteStatus(RouteDefinition route); // Properties //----------------------------------------------------------------------- @@ -430,23 +465,6 @@ public interface CamelContext extends Service, RuntimeConfiguration { */ FactoryFinder getFactoryFinder(String path) throws NoFactoryAvailableException; - /** - * Returns the current status of the given route - * - * @param routeId the route id - * @return the status for the route - */ - ServiceStatus getRouteStatus(String routeId); - - /** - * Returns the current status of the given route - * - * @param route the route - * @return the status for the route - * @deprecated will be removed in Camel 2.2 - */ - ServiceStatus getRouteStatus(RouteDefinition route); - /** * Returns the class resolver to be used for loading/lookup of classes. * 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 5dbaca11ccc21..8cd91a52646b1 100644 --- a/camel-core/src/main/java/org/apache/camel/Route.java +++ b/camel-core/src/main/java/org/apache/camel/Route.java @@ -53,15 +53,26 @@ public interface Route { /** * This property map is used to associate information about - * the route. Gets all tbe services for this routes + * the route. Gets all the services for this routes + * </p> + * This implementation is used for initiali * * @return the services * @throws Exception is thrown in case of error + * @deprecated will be removed in Camel 2.2 */ List<Service> getServicesForRoute() throws Exception; /** - * Returns the additional services required for this particular route + * A strategy callback allowing special initialization when services is starting. + * + * @param services the service + * @throws Exception is thrown in case of error + */ + void onStartingServices(List<Service> services) throws Exception; + + /** + * Returns the services for this particular route */ List<Service> getServices(); 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 2acaac3bf695d..ee9478ee012bd 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 @@ -597,6 +597,13 @@ public void startRoute(RouteDefinition route) throws Exception { startRouteService(routeService); } + public synchronized void startRoute(String routeId) throws Exception { + RouteService routeService = routeServices.get(routeId); + if (routeService != null) { + routeService.start(); + } + } + public void stopRoute(RouteDefinition route) throws Exception { stopRoute(route.idOrCreate(nodeIdFactory)); } @@ -605,7 +612,7 @@ public void stopRoute(RouteDefinition route) throws Exception { * Stops the route denoted by the given RouteType id */ public synchronized void stopRoute(String key) throws Exception { - RouteService routeService = routeServices.remove(key); + RouteService routeService = routeServices.get(key); if (routeService != null) { routeService.stop(); } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java index 5294feec7aa6c..4e8ae80151316 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java @@ -86,6 +86,10 @@ public List<Service> getServicesForRoute() throws Exception { return servicesForRoute; } + public void onStartingServices(List<Service> services) throws Exception { + addServices(services); + } + public List<Service> getServices() { return services; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/RouteService.java b/camel-core/src/main/java/org/apache/camel/impl/RouteService.java index 30890b41f5300..ca6434dadc665 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/RouteService.java +++ b/camel-core/src/main/java/org/apache/camel/impl/RouteService.java @@ -29,6 +29,8 @@ import org.apache.camel.spi.RouteContext; import org.apache.camel.util.EventHelper; import org.apache.camel.util.ServiceHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; /** * Represents the runtime objects for a given {@link RouteDefinition} so that it can be stopped independently @@ -38,6 +40,8 @@ */ public class RouteService extends ServiceSupport { + private static final Log LOG = LogFactory.getLog(RouteService.class); + private final DefaultCamelContext camelContext; private final RouteDefinition routeDefinition; private final List<RouteContext> routeContexts; @@ -80,12 +84,19 @@ protected void doStart() throws Exception { } for (Route route : routes) { - List<Service> services = route.getServicesForRoute(); + if (LOG.isTraceEnabled()) { + LOG.trace("Starting route: " + route); + } + + List<Service> services = route.getServices(); + + // callback that we are staring these services + route.onStartingServices(services); // gather list of services to start as we need to start child services as well List<Service> list = new ArrayList<Service>(); for (Service service : services) { - doGetServiesToStart(list, service); + doGetChildServies(list, service); } startChildService(list); @@ -94,37 +105,26 @@ protected void doStart() throws Exception { } } - /** - * Need to recursive start child services for routes - */ - private void doGetServiesToStart(List<Service> services, Service service) throws Exception { - services.add(service); - - if (service instanceof Navigate) { - Navigate<?> nav = (Navigate<?>) service; - if (nav.hasNext()) { - List<?> children = nav.next(); - for (Object child : children) { - if (child instanceof Service) { - doGetServiesToStart(services, (Service) child); - } - } - } - } - } - protected void doStop() throws Exception { for (LifecycleStrategy strategy : camelContext.getLifecycleStrategies()) { strategy.onRoutesRemove(routes); } - // do not stop child services as in doStart - // as route.getServicesForRoute() will restart - // already stopped services, so we end up starting - // stuff when we stop. - - // fire events for (Route route : routes) { + if (LOG.isTraceEnabled()) { + LOG.trace("Stopping route: " + route); + } + // getServices will not add services again + List<Service> services = route.getServices(); + + // gather list of services to stop as we need to start child services as well + List<Service> list = new ArrayList<Service>(); + for (Service service : services) { + doGetChildServies(list, service); + } + stopChildService(list); + + // fire event EventHelper.notifyRouteStopped(camelContext, route); } @@ -141,4 +141,33 @@ protected void startChildService(List<Service> services) throws Exception { } } + protected void stopChildService(List<Service> services) throws Exception { + for (Service service : services) { + for (LifecycleStrategy strategy : camelContext.getLifecycleStrategies()) { + strategy.onServiceRemove(camelContext, service); + } + ServiceHelper.stopService(service); + removeChildService(service); + } + } + + /** + * Need to recursive start child services for routes + */ + private static void doGetChildServies(List<Service> services, Service service) throws Exception { + services.add(service); + + if (service instanceof Navigate) { + Navigate<?> nav = (Navigate<?>) service; + if (nav.hasNext()) { + List<?> children = nav.next(); + for (Object child : children) { + if (child instanceof Service) { + doGetChildServies(services, (Service) child); + } + } + } + } + } + } diff --git a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java index 03f139d27efd7..bd76e8eb1f8b1 100644 --- a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java @@ -94,28 +94,28 @@ public boolean manageProcessor(ProcessorDefinition definition) { return false; } - public void manageObject(Object o) throws Exception { + public void manageObject(Object managedObject) throws Exception { // noop } - public void manageNamedObject(Object o, Object o1) throws Exception { + public void manageNamedObject(Object managedObject, Object preferedName) throws Exception { // noop } - public <T> T getManagedObjectName(Object o, String s, Class<T> tClass) throws Exception { + public <T> T getManagedObjectName(Object managedObject, String customName, Class<T> nameType) throws Exception { // noop return null; } - public void unmanageObject(Object o) throws Exception { + public void unmanageObject(Object managedObject) throws Exception { // noop } - public void unmanageNamedObject(Object o) throws Exception { + public void unmanageNamedObject(Object name) throws Exception { // noop } - public boolean isManaged(Object o, Object o1) { + public boolean isManaged(Object managedObject, Object name) { // noop return false; } diff --git a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java index e6cd8c0b5ac12..e41f2af93a858 100644 --- a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java +++ b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java @@ -68,7 +68,7 @@ public String getEndpointUri() { return ep != null ? ep.getEndpointUri() : VALUE_UNKNOWN; } - @ManagedAttribute(description = "Route state") + @ManagedAttribute(description = "Route State") public String getState() { // must use String type to be sure remote JMX can read the attribute without requiring Camel classes. ServiceStatus status = context.getRouteStatus(route.getId()); @@ -86,11 +86,11 @@ public String getCamelId() { @ManagedOperation(description = "Start Route") public void start() throws Exception { - throw new IllegalArgumentException("Start not supported"); + context.startRoute(getRouteId()); } @ManagedOperation(description = "Stop Route") public void stop() throws Exception { - throw new IllegalArgumentException("Stop not supported"); + context.stopRoute(getRouteId()); } } diff --git a/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopAndStartTest.java b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopAndStartTest.java new file mode 100644 index 0000000000000..0cf87bf36871e --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopAndStartTest.java @@ -0,0 +1,102 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.management; + +import java.util.Set; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.ServiceStatus; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; + +/** + * @version $Revision$ + */ +public class ManagedRouteStopAndStartTest extends ContextTestSupport { + + @Override + protected void setUp() throws Exception { + deleteDirectory("target/managed"); + super.setUp(); + } + + public void testStopAndStartRoute() throws Exception { + MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer(); + ObjectName on = getRouteObjectName(mbeanServer); + + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("Hello World"); + + template.sendBodyAndHeader("file://target/managed", "Hello World", Exchange.FILE_NAME, "hello.txt"); + + assertMockEndpointsSatisfied(); + + // should be started + String state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be started", ServiceStatus.Started.name(), state); + + // stop + mbeanServer.invoke(on, "stop", null, null); + + state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be stopped", ServiceStatus.Stopped.name(), state); + + mock.reset(); + mock.expectedBodiesReceived("Bye World"); + // wait 3 seconds while route is stopped to verify that file was not consumed + mock.setResultWaitTime(3000); + + template.sendBodyAndHeader("file://target/managed", "Bye World", Exchange.FILE_NAME, "bye.txt"); + + // route is stopped so we do not get the file + mock.assertIsNotSatisfied(); + + // prepare mock for starting route + mock.reset(); + mock.expectedBodiesReceived("Bye World"); + + // start + mbeanServer.invoke(on, "start", null, null); + + state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be started", ServiceStatus.Started.name(), state); + + // this time the file is consumed + mock.assertIsSatisfied(); + } + + private static ObjectName getRouteObjectName(MBeanServer mbeanServer) throws Exception { + Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null); + assertEquals(1, set.size()); + + return set.iterator().next(); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("file://target/managed").to("mock:result"); + } + }; + } + +} diff --git a/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopTest.java b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopTest.java new file mode 100644 index 0000000000000..d8c91b57c4d20 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopTest.java @@ -0,0 +1,76 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.management; + +import java.util.Set; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.ServiceStatus; +import org.apache.camel.builder.RouteBuilder; + +/** + * @version $Revision$ + */ +public class ManagedRouteStopTest extends ContextTestSupport { + + public void testStopRoute() throws Exception { + // fire a message to get it running + getMockEndpoint("mock:result").expectedMessageCount(1); + template.sendBody("direct:start", "Hello World"); + assertMockEndpointsSatisfied(); + + MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer(); + + Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null); + assertEquals(1, set.size()); + + ObjectName on = set.iterator().next(); + + boolean registered = mbeanServer.isRegistered(on); + assertEquals("Should be registered", true, registered); + + String uri = (String) mbeanServer.getAttribute(on, "EndpointUri"); + // the route has this starting endpoint uri + assertEquals("direct://start", uri); + + // should be started + String state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be started", ServiceStatus.Started.name(), state); + + mbeanServer.invoke(on, "stop", null, null); + + registered = mbeanServer.isRegistered(on); + assertEquals("Should be registered", true, registered); + + // should be stopped, eg its removed + state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be stopped", ServiceStatus.Stopped.name(), state); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("direct:start").to("log:foo").to("mock:result"); + } + }; + } + +} \ No newline at end of file diff --git a/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java b/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java index 3a37ac30820cb..764eb3a92ce2e 100644 --- a/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java +++ b/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java @@ -20,8 +20,8 @@ import javax.management.ObjectName; import org.apache.camel.CamelContext; -import org.apache.camel.TestSupport; import org.apache.camel.ServiceStatus; +import org.apache.camel.TestSupport; import org.apache.camel.impl.DefaultCamelContext; /**
2b0b6845d3c96a4c784d5c0b1b211860909d2f23
ReactiveX-RxJava
Add CompositeSubscription--- also a utility method for creating a Subscription around a Future-
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java b/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java index 0ad92e1d06..05f804000d 100644 --- a/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java +++ b/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java @@ -1,3 +1,18 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package rx.subscriptions; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/rxjava-core/src/main/java/rx/subscriptions/CompositeSubscription.java b/rxjava-core/src/main/java/rx/subscriptions/CompositeSubscription.java new file mode 100644 index 0000000000..096500217c --- /dev/null +++ b/rxjava-core/src/main/java/rx/subscriptions/CompositeSubscription.java @@ -0,0 +1,80 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package rx.subscriptions; + +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import rx.Subscription; +import rx.util.functions.Functions; + +/** + * Subscription that represents a group of Subscriptions that are unsubscribed together. + * + * @see Rx.Net equivalent CompositeDisposable at http://msdn.microsoft.com/en-us/library/system.reactive.disposables.compositedisposable(v=vs.103).aspx + */ +public class CompositeSubscription implements Subscription { + + private static final Logger logger = LoggerFactory.getLogger(Functions.class); + + /* + * The reason 'synchronized' is used on 'add' and 'unsubscribe' is because AtomicBoolean/ConcurrentLinkedQueue are both being modified so it needs to be done atomically. + * + * TODO evaluate whether use of synchronized is a performance issue here and if it's worth using an atomic state machine or other non-locking approach + */ + private AtomicBoolean unsubscribed = new AtomicBoolean(false); + private final ConcurrentLinkedQueue<Subscription> subscriptions = new ConcurrentLinkedQueue<Subscription>(); + + public CompositeSubscription(List<Subscription> subscriptions) { + this.subscriptions.addAll(subscriptions); + } + + public CompositeSubscription(Subscription... subscriptions) { + for (Subscription s : subscriptions) { + this.subscriptions.add(s); + } + } + + public boolean isUnsubscribed() { + return unsubscribed.get(); + } + + public synchronized void add(Subscription s) { + if (unsubscribed.get()) { + s.unsubscribe(); + } else { + subscriptions.add(s); + } + } + + @Override + public synchronized void unsubscribe() { + if (unsubscribed.compareAndSet(false, true)) { + for (Subscription s : subscriptions) { + try { + s.unsubscribe(); + } catch (Exception e) { + logger.error("Failed to unsubscribe.", e); + } + } + } + } + +} diff --git a/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java b/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java index 4c79ce7bfa..1db0b7a660 100644 --- a/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java +++ b/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java @@ -1,5 +1,22 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package rx.subscriptions; +import java.util.concurrent.Future; + import rx.Subscription; import rx.util.functions.Action0; import rx.util.functions.FuncN; @@ -31,6 +48,37 @@ public void unsubscribe() { }; } + /** + * A {@link Subscription} that wraps a {@link Future} and cancels it when unsubscribed. + * + * + * @param f + * {@link Future} + * @return {@link Subscription} + */ + public static Subscription create(final Future<?> f) { + return new Subscription() { + + @Override + public void unsubscribe() { + f.cancel(true); + } + + }; + } + + /** + * A {@link Subscription} that groups multiple Subscriptions together and unsubscribes from all of them together. + * + * @param subscriptions + * Subscriptions to group together + * @return {@link Subscription} + */ + + public static CompositeSubscription create(Subscription... subscriptions) { + return new CompositeSubscription(subscriptions); + } + /** * A {@link Subscription} implemented via an anonymous function (such as closures from other languages). *
395b43d62ec11bacbf636bdd3a55151e936a569c
Mylyn Reviews
Added update site
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews-site/.project b/org.eclipse.mylyn.reviews-site/.project new file mode 100644 index 00000000..e7305348 --- /dev/null +++ b/org.eclipse.mylyn.reviews-site/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.mylyn.reviews-site</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.pde.UpdateSiteBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.UpdateSiteNature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.mylyn.reviews-site/site.xml b/org.eclipse.mylyn.reviews-site/site.xml new file mode 100644 index 00000000..5ca060f2 --- /dev/null +++ b/org.eclipse.mylyn.reviews-site/site.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<site> + <feature url="features/org.eclipse.mylyn.reviews_0.0.1.jar" id="org.eclipse.mylyn.reviews" version="0.0.1"> + <category name="mylyn.reviews"/> + </feature> + <category-def name="mylyn.reviews" label="Mylyn Reviews (Incubation)"/> +</site>
77f49b96f4e89e5bee34e7c53eeb8a06ba82aeb1
dozermapper$dozer
Banishing the singletons (#403) * introducing DozerBeanMapperBuilder and hiding DozerBeanMapper constructor related to #375 * removing singleton capability from GlobalSettings related to #375 * removing singleton capability from MappingsParser related to #375 * adjusting new project code to DozerBeanMapper * removing singleton capability from XMLParserFactory related to #375 * removing GlobalStatistics as this singleton has no functionality but provided global reference to StatisticManager; now other classes have StatisticManager injected for them related to #375 * removing singleton capability from DozerInitializer related to #375 * removing singleton capability from BeanContainer related to #375 * adjusting new project code to DozerBeanMapperBuilder * removing global state from DestBeanBuilderCreator related to #375 * removing global state from BeanMappingGenerator related to #375 * removing global state from PropertyDescriptorFactory; applying work-around to resolve ProtobufSupportModule dependency to Dozer internals related to #375 * deprecating DozerBeanMapperSingletonWrapper related to #375 * restoring public constructors of DozerBeanMapper and deprecating them to give users possibility to gradually migrate their code * updating documentation and migration notes according to the changes in pr * recovering backwards-compatibility for BeanFactory interface
p
https://github.com/dozermapper/dozer
diff --git a/README.md b/README.md index 5c12ef692..f4bd062bc 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ If you are using Maven, simply copy-paste this dependency to your project. ```Java SourceClassName sourceObject = ... -Mapper mapper = new DozerBeanMapper(); +Mapper mapper = DozerBeanMapperBuilder.createDefault(); DestinationObject destObject = mapper.map(sourceObject, DestinationClassName.class); assertTrue(destObject.getYourDestinationFieldName().equals(sourceObject.getYourSourceFieldName)); diff --git a/core/src/main/java/org/dozer/BeanFactory.java b/core/src/main/java/org/dozer/BeanFactory.java index 4d7d5400f..325730908 100644 --- a/core/src/main/java/org/dozer/BeanFactory.java +++ b/core/src/main/java/org/dozer/BeanFactory.java @@ -15,6 +15,8 @@ */ package org.dozer; +import org.dozer.config.BeanContainer; + /** * Public custom bean factory interface. * @@ -40,5 +42,15 @@ public interface BeanFactory { // Need sourceObjClass in case sourceObj is null - Object createBean(Object source, Class<?> sourceClass, String targetBeanId); + default Object createBean(Object source, Class<?> sourceClass, String targetBeanId, BeanContainer beanContainer) { + return createBean(source, sourceClass, targetBeanId); + } + + /** + * Will be removed in 6.2. Please use {@link BeanFactory#createBean(Object, Class, String, BeanContainer)}. + */ + @Deprecated + default Object createBean(Object source, Class<?> sourceClass, String targetBeanId) { + return null; + } } diff --git a/core/src/main/java/org/dozer/DozerBeanMapper.java b/core/src/main/java/org/dozer/DozerBeanMapper.java index 4e8962984..b18b3efef 100644 --- a/core/src/main/java/org/dozer/DozerBeanMapper.java +++ b/core/src/main/java/org/dozer/DozerBeanMapper.java @@ -26,28 +26,41 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; +import org.dozer.builder.DestBeanBuilderCreator; import org.dozer.cache.CacheManager; import org.dozer.cache.DozerCacheManager; import org.dozer.cache.DozerCacheType; +import org.dozer.classmap.ClassMapBuilder; import org.dozer.classmap.ClassMappings; import org.dozer.classmap.Configuration; import org.dozer.classmap.MappingFileData; +import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.config.BeanContainer; import org.dozer.config.GlobalSettings; import org.dozer.event.DozerEventManager; import org.dozer.factory.DestBeanCreator; import org.dozer.loader.CustomMappingsLoader; import org.dozer.loader.LoadMappingsResult; +import org.dozer.loader.MappingsParser; import org.dozer.loader.api.BeanMappingBuilder; import org.dozer.loader.xml.MappingFileReader; import org.dozer.loader.xml.MappingStreamReader; +import org.dozer.loader.xml.XMLParser; import org.dozer.loader.xml.XMLParserFactory; import org.dozer.metadata.DozerMappingMetadata; import org.dozer.metadata.MappingMetadata; -import org.dozer.stats.GlobalStatistics; +import org.dozer.osgi.Activator; +import org.dozer.osgi.OSGiClassLoader; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.stats.StatisticType; import org.dozer.stats.StatisticsInterceptor; import org.dozer.stats.StatisticsManager; +import org.dozer.stats.StatisticsManagerImpl; +import org.dozer.util.DefaultClassLoader; +import org.dozer.util.DozerClassLoader; import org.dozer.util.MappingValidator; +import org.dozer.util.RuntimeUtils; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,9 +83,19 @@ public class DozerBeanMapper implements Mapper { private final Logger log = LoggerFactory.getLogger(DozerBeanMapper.class); - private final StatisticsManager statsMgr = GlobalStatistics.getInstance().getStatsMgr(); private final AtomicBoolean initializing = new AtomicBoolean(false); private final CountDownLatch ready = new CountDownLatch(1); + private final StatisticsManager statsMgr; + private final GlobalSettings globalSettings; + private final CustomMappingsLoader customMappingsLoader; + private final XMLParserFactory xmlParserFactory; + private final DozerInitializer dozerInitializer; + private final BeanContainer beanContainer; + private final XMLParser xmlParser; + private final DestBeanCreator destBeanCreator; + private final DestBeanBuilderCreator destBeanBuilderCreator; + private final BeanMappingGenerator beanMappingGenerator; + private final PropertyDescriptorFactory propertyDescriptorFactory; /* * Accessible for custom injection @@ -91,14 +114,68 @@ public class DozerBeanMapper implements Mapper { private ClassMappings customMappings; private Configuration globalConfiguration; // There are no global caches. Caches are per bean mapper instance - private final CacheManager cacheManager = new DozerCacheManager(); + private final CacheManager cacheManager; private DozerEventManager eventManager; + /** + * @deprecated will be removed in 6.2. Please use {@code DozerBeanMapperBuilder.create().build()}. + */ + @Deprecated public DozerBeanMapper() { - this(Collections.<String>emptyList()); + this(Collections.emptyList()); } + /** + * @deprecated will be removed in 6.2. Please use {@code DozerBeanMapperBuilder.create().withMappingFiles(..).build()}. + */ + @Deprecated public DozerBeanMapper(List<String> mappingFiles) { + DozerClassLoader classLoader = RuntimeUtils.isOSGi() + ? new OSGiClassLoader(Activator.getBundle().getBundleContext()) + : new DefaultClassLoader(DozerBeanMapperBuilder.class.getClassLoader()); + this.globalSettings = new GlobalSettings(classLoader); + this.beanContainer = new BeanContainer(); + this.destBeanCreator = new DestBeanCreator(beanContainer); + this.propertyDescriptorFactory = new PropertyDescriptorFactory(); + this.beanMappingGenerator = new BeanMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory); + ClassMapBuilder classMapBuilder = new ClassMapBuilder( + beanContainer, destBeanCreator, beanMappingGenerator, propertyDescriptorFactory); + this.customMappingsLoader = new CustomMappingsLoader( + new MappingsParser(beanContainer, destBeanCreator, propertyDescriptorFactory), classMapBuilder, beanContainer); + this.xmlParserFactory = new XMLParserFactory(beanContainer); + this.statsMgr = new StatisticsManagerImpl(globalSettings); + this.dozerInitializer = new DozerInitializer(); + this.xmlParser = new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory); + this.destBeanBuilderCreator = new DestBeanBuilderCreator(); + this.cacheManager = new DozerCacheManager(statsMgr); + this.mappingFiles.addAll(mappingFiles); + init(); + } + + DozerBeanMapper(List<String> mappingFiles, + GlobalSettings globalSettings, + CustomMappingsLoader customMappingsLoader, + XMLParserFactory xmlParserFactory, + StatisticsManager statsMgr, + DozerInitializer dozerInitializer, + BeanContainer beanContainer, + XMLParser xmlParser, + DestBeanCreator destBeanCreator, + DestBeanBuilderCreator destBeanBuilderCreator, + BeanMappingGenerator beanMappingGenerator, + PropertyDescriptorFactory propertyDescriptorFactory) { + this.globalSettings = globalSettings; + this.customMappingsLoader = customMappingsLoader; + this.xmlParserFactory = xmlParserFactory; + this.statsMgr = statsMgr; + this.cacheManager = new DozerCacheManager(statsMgr); + this.dozerInitializer = dozerInitializer; + this.beanContainer = beanContainer; + this.xmlParser = xmlParser; + this.destBeanCreator = destBeanCreator; + this.destBeanBuilderCreator = destBeanBuilderCreator; + this.beanMappingGenerator = beanMappingGenerator; + this.propertyDescriptorFactory = propertyDescriptorFactory; this.mappingFiles.addAll(mappingFiles); init(); } @@ -156,7 +233,7 @@ public void setMappingFiles(List<String> mappingFileUrls) { public void setFactories(Map<String, BeanFactory> factories) { checkIfInitialized(); - DestBeanCreator.setStoredFactories(factories); + destBeanCreator.setStoredFactories(factories); } public void setCustomConverters(List<CustomConverter> customConverters) { @@ -174,13 +251,12 @@ public Map<String, CustomConverter> getCustomConvertersWithId() { } private void init() { - DozerInitializer.getInstance().init(); + dozerInitializer.init(globalSettings, statsMgr, beanContainer, destBeanBuilderCreator, beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); log.info("Initializing a new instance of dozer bean mapper."); // initialize any bean mapper caches. These caches are only visible to the bean mapper instance and // are not shared across the VM. - GlobalSettings globalSettings = GlobalSettings.getInstance(); cacheManager.addCache(DozerCacheType.CONVERTER_BY_DEST_TYPE.name(), globalSettings.getConverterByDestTypeCacheMaxSize()); cacheManager.addCache(DozerCacheType.SUPER_TYPE_CHECK.name(), globalSettings.getSuperTypesCacheMaxSize()); @@ -189,14 +265,15 @@ private void init() { } public void destroy() { - DozerInitializer.getInstance().destroy(); + dozerInitializer.destroy(globalSettings); } protected Mapper getMappingProcessor() { initMappings(); Mapper processor = new MappingProcessor(customMappings, globalConfiguration, cacheManager, statsMgr, customConverters, - eventManager, getCustomFieldMapper(), customConvertersWithId); + eventManager, getCustomFieldMapper(), customConvertersWithId, beanContainer, destBeanCreator, destBeanBuilderCreator, + beanMappingGenerator, propertyDescriptorFactory); // If statistics are enabled, then Proxy the processor with a statistics interceptor if (statsMgr.isStatisticsEnabled()) { @@ -209,7 +286,6 @@ protected Mapper getMappingProcessor() { } void loadCustomMappings() { - CustomMappingsLoader customMappingsLoader = new CustomMappingsLoader(); List<MappingFileData> xmlMappings = loadFromFiles(mappingFiles); ArrayList<MappingFileData> allMappings = new ArrayList<MappingFileData>(); allMappings.addAll(xmlMappings); @@ -220,13 +296,13 @@ void loadCustomMappings() { } private List<MappingFileData> loadFromFiles(List<String> mappingFiles) { - MappingFileReader mappingFileReader = new MappingFileReader(XMLParserFactory.getInstance()); + MappingFileReader mappingFileReader = new MappingFileReader(xmlParserFactory, xmlParser, beanContainer); List<MappingFileData> mappingFileDataList = new ArrayList<MappingFileData>(); if (mappingFiles != null && mappingFiles.size() > 0) { log.info("Using the following xml files to load custom mappings for the bean mapper instance: {}", mappingFiles); for (String mappingFileName : mappingFiles) { log.info("Trying to find xml mapping file: {}", mappingFileName); - URL url = MappingValidator.validateURL(mappingFileName); + URL url = MappingValidator.validateURL(mappingFileName, beanContainer); log.info("Using URL [" + url + "] to load custom xml mappings"); MappingFileData mappingFileData = mappingFileReader.read(url); log.info("Successfully loaded custom xml mappings from URL: [{}]", url); @@ -247,7 +323,7 @@ private List<MappingFileData> loadFromFiles(List<String> mappingFiles) { */ public void addMapping(InputStream xmlStream) { checkIfInitialized(); - MappingStreamReader fileReader = new MappingStreamReader(XMLParserFactory.getInstance()); + MappingStreamReader fileReader = new MappingStreamReader(xmlParserFactory, xmlParser); MappingFileData mappingFileData = fileReader.read(xmlStream); builderMappings.add(mappingFileData); } @@ -259,7 +335,7 @@ public void addMapping(InputStream xmlStream) { */ public void addMapping(BeanMappingBuilder mappingBuilder) { checkIfInitialized(); - MappingFileData mappingFileData = mappingBuilder.build(); + MappingFileData mappingFileData = mappingBuilder.build(beanContainer, destBeanCreator, propertyDescriptorFactory); builderMappings.add(mappingFileData); } diff --git a/core/src/main/java/org/dozer/DozerBeanMapperBuilder.java b/core/src/main/java/org/dozer/DozerBeanMapperBuilder.java new file mode 100644 index 000000000..0c30a5e38 --- /dev/null +++ b/core/src/main/java/org/dozer/DozerBeanMapperBuilder.java @@ -0,0 +1,177 @@ +/* + * Copyright 2005-2017 Dozer Project + * + * 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.dozer; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.dozer.builder.DestBeanBuilderCreator; +import org.dozer.classmap.ClassMapBuilder; +import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.config.BeanContainer; +import org.dozer.config.GlobalSettings; +import org.dozer.factory.DestBeanCreator; +import org.dozer.loader.CustomMappingsLoader; +import org.dozer.loader.MappingsParser; +import org.dozer.loader.xml.XMLParser; +import org.dozer.loader.xml.XMLParserFactory; +import org.dozer.osgi.Activator; +import org.dozer.osgi.OSGiClassLoader; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; +import org.dozer.stats.StatisticsManager; +import org.dozer.stats.StatisticsManagerImpl; +import org.dozer.util.DefaultClassLoader; +import org.dozer.util.DozerClassLoader; +import org.dozer.util.DozerConstants; +import org.dozer.util.RuntimeUtils; + +/** + * Builds an instance of {@link DozerBeanMapper}. + * Provides fluent interface to configure every aspect of the mapper. Everything which is not explicitly specified + * will receive its default value. Please refer to class methods for possible configuration options. + */ +public final class DozerBeanMapperBuilder { + + private List<String> mappingFiles = new ArrayList<>(1); + private DozerClassLoader classLoader; + + private DozerBeanMapperBuilder() { + } + + /** + * Creates new builder. All the configuration has its default values. + * + * @return new instance of the builder. + */ + public static DozerBeanMapperBuilder create() { + return new DozerBeanMapperBuilder(); + } + + /** + * Creates an instance of {@link DozerBeanMapper}, with all the configuration set to its default values. + * <p> + * The only special handling is for mapping file. If there is a file with name {@code dozerBeanMapping.xml} + * available on classpath, this file will be used by created mapper. Otherwise the mapper is implicit. + * + * @return new instance of {@link DozerBeanMapper} with default configuration and optionally initiated mapping file. + */ + public static DozerBeanMapper buildDefault() { + DozerBeanMapperBuilder builder = create(); + DozerClassLoader classLoader = builder.getClassLoader(); + URL defaultMappingFile = classLoader.loadResource(DozerConstants.DEFAULT_MAPPING_FILE); + if (defaultMappingFile != null) { + builder.withMappingFiles(DozerConstants.DEFAULT_MAPPING_FILE); + } + return builder.withClassLoader(classLoader).build(); + } + + /** + * Adds {@code mappingFiles} to the list of files to be used as mapping configuration. + * Multiple calls of this method will result in all the files being added to the list + * of mappings in the order methods were called. + * <p> + * If not called, no files will be added to the mapping configuration, and mapper will use implicit mode. + * + * @param mappingFiles mapping files to be added. + * @return modified builder to be further configured. + */ + public DozerBeanMapperBuilder withMappingFiles(String... mappingFiles) { + this.mappingFiles.addAll(Arrays.asList(mappingFiles)); + return this; + } + + /** + * Sets {@link DozerClassLoader} to be used whenever Dozer needs to load a class or resource. + * <p> + * By default, if Dozer is executed in OSGi environment, {@link org.dozer.osgi.OSGiClassLoader} will be + * used (i.e. delegate loading to Dozer bundle classloader). If Dozer is executed in non-OSGi environment, + * classloader of {@link DozerBeanMapperBuilder} will be used (wrapped into {@link DefaultClassLoader}). + * + * @param classLoader custom classloader to be used by Dozer. + * @return modified builder to be further configured. + */ + public DozerBeanMapperBuilder withClassLoader(DozerClassLoader classLoader) { + this.classLoader = classLoader; + return this; + } + + /** + * Sets classloader to be used whenever Dozer needs to load a class or resource. + * <p> + * By default, if Dozer is executed in OSGi environment, {@link org.dozer.osgi.OSGiClassLoader} will be + * used (i.e. delegate loading to Dozer bundle classloader). If Dozer is executed in non-OSGi environment, + * classloader of {@link DozerBeanMapperBuilder} will be used (wrapped into {@link DefaultClassLoader}). + * + * @param classLoader custom classloader to be used by Dozer. Will be wrapped into {@link DefaultClassLoader}. + * @return modified builder to be further configured. + */ + public DozerBeanMapperBuilder withClassLoader(ClassLoader classLoader) { + this.classLoader = new DefaultClassLoader(classLoader); + return this; + } + + /** + * Creates an instance of {@link DozerBeanMapper}. Mapper is configured according to the current builder state. + * <p> + * Subsequent calls of this method will return new instances. + * + * @return new instance of {@link DozerBeanMapper}. + */ + public DozerBeanMapper build() { + DozerClassLoader classLoader = getClassLoader(); + GlobalSettings globalSettings = new GlobalSettings(classLoader); + BeanContainer beanContainer = new BeanContainer(); + DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + PropertyDescriptorFactory propertyDescriptorFactory = new PropertyDescriptorFactory(); + BeanMappingGenerator beanMappingGenerator = new BeanMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory); + ClassMapBuilder classMapBuilder = new ClassMapBuilder(beanContainer, destBeanCreator, beanMappingGenerator, propertyDescriptorFactory); + CustomMappingsLoader customMappingsLoader = new CustomMappingsLoader( + new MappingsParser(beanContainer, destBeanCreator, propertyDescriptorFactory), classMapBuilder, beanContainer); + XMLParserFactory xmlParserFactory = new XMLParserFactory(beanContainer); + StatisticsManager statisticsManager = new StatisticsManagerImpl(globalSettings); + DozerInitializer dozerInitializer = new DozerInitializer(); + XMLParser xmlParser = new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory); + DestBeanBuilderCreator destBeanBuilderCreator = new DestBeanBuilderCreator(); + + return new DozerBeanMapper(mappingFiles, + globalSettings, + customMappingsLoader, + xmlParserFactory, + statisticsManager, + dozerInitializer, + beanContainer, + xmlParser, + destBeanCreator, + destBeanBuilderCreator, + beanMappingGenerator, propertyDescriptorFactory); + } + + private DozerClassLoader getClassLoader() { + if (classLoader == null) { + if (RuntimeUtils.isOSGi()) { + return new OSGiClassLoader(Activator.getBundle().getBundleContext()); + + } else { + return new DefaultClassLoader(DozerBeanMapperBuilder.class.getClassLoader()); + } + + } else { + return classLoader; + } + } + +} diff --git a/core/src/main/java/org/dozer/DozerBeanMapperSingletonWrapper.java b/core/src/main/java/org/dozer/DozerBeanMapperSingletonWrapper.java index a5ee135d2..37beb5f1d 100644 --- a/core/src/main/java/org/dozer/DozerBeanMapperSingletonWrapper.java +++ b/core/src/main/java/org/dozer/DozerBeanMapperSingletonWrapper.java @@ -15,9 +15,6 @@ */ package org.dozer; -import java.util.ArrayList; -import java.util.List; - import org.dozer.util.DozerConstants; /** @@ -26,8 +23,11 @@ * DozerBeanMapper(MapperIF) instance is configured via an IOC framework, such as Spring, with singleton property set to * "true" * + * @deprecated Will be removed in version 6.2. Please use {@link DozerBeanMapperBuilder#buildDefault()}. + * * @author garsombke.franz */ +@Deprecated public final class DozerBeanMapperSingletonWrapper { private static Mapper instance; @@ -36,12 +36,13 @@ private DozerBeanMapperSingletonWrapper() { } + /** + * @deprecated Will be removed in version 6.2. Please use {@link DozerBeanMapperBuilder#buildDefault()}. + */ + @Deprecated public static synchronized Mapper getInstance() { if (instance == null) { - List<String> mappingFiles = new ArrayList<String>(); - mappingFiles.add(DozerConstants.DEFAULT_MAPPING_FILE); - - instance = new DozerBeanMapper(mappingFiles); + instance = DozerBeanMapperBuilder.buildDefault(); } return instance; diff --git a/core/src/main/java/org/dozer/DozerInitializer.java b/core/src/main/java/org/dozer/DozerInitializer.java index 601fbb4be..d68cbd976 100644 --- a/core/src/main/java/org/dozer/DozerInitializer.java +++ b/core/src/main/java/org/dozer/DozerInitializer.java @@ -23,14 +23,19 @@ import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; +import org.dozer.builder.DestBeanBuilderCreator; +import org.dozer.classmap.generator.BeanMappingGenerator; import org.dozer.config.BeanContainer; import org.dozer.config.GlobalSettings; +import org.dozer.factory.DestBeanCreator; import org.dozer.jmx.DozerAdminController; import org.dozer.jmx.DozerStatisticsController; import org.dozer.jmx.JMXPlatform; import org.dozer.jmx.JMXPlatformImpl; import org.dozer.loader.xml.ELEngine; import org.dozer.loader.xml.ExpressionElementReader; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; +import org.dozer.stats.StatisticsManager; import org.dozer.util.DefaultClassLoader; import org.dozer.util.DozerClassLoader; import org.dozer.util.DozerConstants; @@ -54,18 +59,20 @@ public final class DozerInitializer { private static final String DOZER_STATISTICS_CONTROLLER = "org.dozer.jmx:type=DozerStatisticsController"; private static final String DOZER_ADMIN_CONTROLLER = "org.dozer.jmx:type=DozerAdminController"; - private static final DozerInitializer instance = new DozerInitializer(); - private volatile boolean isInitialized; - private DozerInitializer() { + public DozerInitializer() { } - public void init() { - init(getClass().getClassLoader()); + public void init(GlobalSettings globalSettings, StatisticsManager statsMgr, BeanContainer beanContainer, + DestBeanBuilderCreator destBeanBuilderCreator, BeanMappingGenerator beanMappingGenerator, PropertyDescriptorFactory propertyDescriptorFactory, + DestBeanCreator destBeanCreator) { + init(globalSettings, getClass().getClassLoader().getParent(), statsMgr, beanContainer, destBeanBuilderCreator, beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); } - public void init(ClassLoader classLoader) { + public void init(GlobalSettings globalSettings, ClassLoader classLoader, StatisticsManager statsMgr, BeanContainer beanContainer, + DestBeanBuilderCreator destBeanBuilderCreator, BeanMappingGenerator beanMappingGenerator, PropertyDescriptorFactory propertyDescriptorFactory, + DestBeanCreator destBeanCreator) { // Multiple threads may try to initialize simultaneously synchronized (this) { if (isInitialized) { @@ -76,26 +83,25 @@ public void init(ClassLoader classLoader) { log.info("Initializing Dozer. Version: {}, Thread Name: {}", DozerConstants.CURRENT_VERSION, Thread.currentThread().getName()); - GlobalSettings globalSettings = GlobalSettings.getInstance(); - initialize(globalSettings, classLoader); + initialize(globalSettings, classLoader, statsMgr, beanContainer, destBeanBuilderCreator, beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); isInitialized = true; } } - void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { + void initialize(GlobalSettings globalSettings, ClassLoader classLoader, StatisticsManager statsMgr, BeanContainer beanContainer, + DestBeanBuilderCreator destBeanBuilderCreator, BeanMappingGenerator beanMappingGenerator, PropertyDescriptorFactory propertyDescriptorFactory, + DestBeanCreator destBeanCreator) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { - registerJMXBeans(new JMXPlatformImpl()); + registerJMXBeans(globalSettings, new JMXPlatformImpl(), statsMgr); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } - BeanContainer beanContainer = BeanContainer.getInstance(); - registerClassLoader(globalSettings, classLoader, beanContainer); registerProxyResolver(globalSettings, beanContainer); @@ -108,6 +114,11 @@ void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); + module.init(beanContainer, destBeanCreator, propertyDescriptorFactory); + + destBeanBuilderCreator.addPluggedStrategies(module.getBeanBuilderCreationStrategies()); + beanMappingGenerator.addPluggedFieldDetectors(module.getBeanFieldsDetectors()); + propertyDescriptorFactory.addPluggedPropertyDescriptorCreationStrategies(module.getPropertyDescriptorCreationStrategies()); } } @@ -142,14 +153,13 @@ private <T> Class<? extends T> loadBeanType(String classLoaderName, DozerClassLo /** * Performs framework shutdown sequence. Includes de-registering existing Dozer JMX MBeans. */ - public void destroy() { + public void destroy(GlobalSettings globalSettings) { synchronized (this) { if (!isInitialized) { log.debug("Tried to destroy when no Dozer instance started."); return; } - GlobalSettings globalSettings = GlobalSettings.getInstance(); if (globalSettings.isAutoregisterJMXBeans()) { try { unregisterJMXBeans(new JMXPlatformImpl()); @@ -165,11 +175,13 @@ public boolean isInitialized() { return isInitialized; } - private void registerJMXBeans(JMXPlatform platform) throws MalformedObjectNameException, InstanceNotFoundException, - MBeanRegistrationException, InstanceAlreadyExistsException, NotCompliantMBeanException { + private void registerJMXBeans(GlobalSettings globalSettings, JMXPlatform platform, StatisticsManager statsMgr) + throws MalformedObjectNameException, InstanceNotFoundException, + MBeanRegistrationException, InstanceAlreadyExistsException, NotCompliantMBeanException { + if (platform.isAvailable()) { - platform.registerMBean(DOZER_STATISTICS_CONTROLLER, new DozerStatisticsController()); - platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController()); + platform.registerMBean(DOZER_STATISTICS_CONTROLLER, new DozerStatisticsController(statsMgr, globalSettings)); + platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController(globalSettings)); } else { log.warn("jdk1.5 jmx management classes unavailable. Dozer JMX MBeans will not be auto registered."); } @@ -184,8 +196,4 @@ private void unregisterJMXBeans(JMXPlatform platform) throws MBeanRegistrationEx } } - public static DozerInitializer getInstance() { - return instance; - } - } diff --git a/core/src/main/java/org/dozer/DozerModule.java b/core/src/main/java/org/dozer/DozerModule.java index f1ee49445..0a12f6290 100644 --- a/core/src/main/java/org/dozer/DozerModule.java +++ b/core/src/main/java/org/dozer/DozerModule.java @@ -15,9 +15,50 @@ */ package org.dozer; +import java.util.Collection; +import java.util.Collections; +import org.dozer.builder.BeanBuilderCreationStrategy; +import org.dozer.classmap.generator.BeanFieldsDetector; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorCreationStrategy; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + /** * @author Dmitry Spikhalskiy */ public interface DozerModule { + + /** + * This is a temporal solution to resolve dependencies to Dozer internals. + * @deprecated requires completere design of Dozer Modules + */ + @Deprecated + void init(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory); + void init(); + + /** + * To be implemented by module if it provides any additional strategies for beans creation. + * @return collection of bean creation strategies; or empty collection if module does not provide this. + */ + default Collection<BeanBuilderCreationStrategy> getBeanBuilderCreationStrategies() { + return Collections.emptyList(); + } + + /** + * To be implemented by module if it provides any additional detectors of bean fields. + * @return collection of bean field detectors; or empty collection if module does not provide this. + */ + default Collection<BeanFieldsDetector> getBeanFieldsDetectors() { + return Collections.emptyList(); + } + + /** + * To be implemented by module if it provides any additional strategies to create property description. + * @return collection of property creation strategies; or empty collection if module does not provide this. + */ + default Collection<PropertyDescriptorCreationStrategy> getPropertyDescriptorCreationStrategies() { + return Collections.emptyList(); + } } diff --git a/core/src/main/java/org/dozer/MappingProcessor.java b/core/src/main/java/org/dozer/MappingProcessor.java index 513967f3d..520d62192 100644 --- a/core/src/main/java/org/dozer/MappingProcessor.java +++ b/core/src/main/java/org/dozer/MappingProcessor.java @@ -43,6 +43,8 @@ import org.dozer.classmap.Configuration; import org.dozer.classmap.CopyByReferenceContainer; import org.dozer.classmap.RelationshipType; +import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.config.BeanContainer; import org.dozer.converters.DateFormatContainer; import org.dozer.converters.PrimitiveOrWrapperConverter; import org.dozer.event.DozerEvent; @@ -56,6 +58,7 @@ import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.HintContainer; import org.dozer.fieldmap.MapFieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.stats.StatisticType; import org.dozer.stats.StatisticsManager; import org.dozer.util.CollectionUtils; @@ -100,13 +103,19 @@ public class MappingProcessor implements Mapper { private final Cache converterByDestTypeCache; private final Cache superTypeCache; - private final PrimitiveOrWrapperConverter primitiveConverter = new PrimitiveOrWrapperConverter(); + private final PrimitiveOrWrapperConverter primitiveConverter; private final LogMsgFactory logMsgFactory = new LogMsgFactory(); + private final BeanContainer beanContainer; + private final ClassMapBuilder classMapBuilder; + private final DestBeanCreator destBeanCreator; + private final DestBeanBuilderCreator destBeanBuilderCreator; protected MappingProcessor(ClassMappings classMappings, Configuration globalConfiguration, CacheManager cacheMgr, StatisticsManager statsMgr, List<CustomConverter> customConverterObjects, DozerEventManager eventManager, CustomFieldMapper customFieldMapper, - Map<String, CustomConverter> customConverterObjectsWithId) { + Map<String, CustomConverter> customConverterObjectsWithId, BeanContainer beanContainer, + DestBeanCreator destBeanCreator, DestBeanBuilderCreator destBeanBuilderCreator, + BeanMappingGenerator beanMappingGenerator, PropertyDescriptorFactory propertyDescriptorFactory) { this.classMappings = classMappings; this.globalConfiguration = globalConfiguration; this.statsMgr = statsMgr; @@ -116,6 +125,11 @@ protected MappingProcessor(ClassMappings classMappings, Configuration globalConf this.converterByDestTypeCache = cacheMgr.getCache(DozerCacheType.CONVERTER_BY_DEST_TYPE.name()); this.superTypeCache = cacheMgr.getCache(DozerCacheType.SUPER_TYPE_CHECK.name()); this.customConverterObjectsWithId = customConverterObjectsWithId; + this.beanContainer = beanContainer; + this.destBeanBuilderCreator = destBeanBuilderCreator; + this.classMapBuilder = new ClassMapBuilder(beanContainer, destBeanCreator, beanMappingGenerator, propertyDescriptorFactory); + this.primitiveConverter = new PrimitiveOrWrapperConverter(beanContainer); + this.destBeanCreator = destBeanCreator; } /* Mapper Interface Implementation */ @@ -150,7 +164,7 @@ public void map(final Object srcObj, final Object destObj, final String mapId) { * @return new or updated destination object */ private <T> T mapGeneral(Object srcObj, final Class<T> destClass, final T destObj, final String mapId) { - srcObj = MappingUtils.deProxy(srcObj); + srcObj = MappingUtils.deProxy(srcObj, beanContainer); Class<T> destType; T result; @@ -215,9 +229,9 @@ private <T> T mapGeneral(Object srcObj, final Class<T> destClass, final T destOb */ private <T> T createByCreationDirectiveAndMap(BeanCreationDirective creationDirective, ClassMap classMap, Object srcObj, T result, boolean bypassSuperMappings, String mapId) { if (result == null) { - BeanBuilder beanBuilder = DestBeanBuilderCreator.create(creationDirective); + BeanBuilder beanBuilder = destBeanBuilderCreator.create(creationDirective); if (beanBuilder == null) { - result = (T) DestBeanCreator.create(creationDirective); + result = (T) destBeanCreator.create(creationDirective); mapToDestObject(classMap, srcObj, result, bypassSuperMappings, mapId); } else { mapToDestObject(classMap, srcObj, beanBuilder, bypassSuperMappings, mapId); @@ -248,7 +262,7 @@ private void mapToDestObject(ClassMap classMap, Object srcObj, Object destObj, b } private void map(ClassMap classMap, Object srcObj, Object destObj, boolean bypassSuperMappings, List<String> mappedParentFields, String mapId) { - srcObj = MappingUtils.deProxy(srcObj); + srcObj = MappingUtils.deProxy(srcObj, beanContainer); // 1596766 - Recursive object mapping issue. Prevent recursive mapping // infinite loop. Keep a record of mapped fields @@ -392,7 +406,7 @@ private void mapFromFieldMap(Object srcObj, Object destObj, Object srcFieldValue destFieldValue = mapOrRecurseObject(srcObj, srcFieldValue, destFieldType, fieldMapping, destObj); } else { Class<?> srcFieldClass = srcFieldValue != null ? srcFieldValue.getClass() : fieldMapping.getSrcFieldType(srcObj.getClass()); - destFieldValue = mapUsingCustomConverter(MappingUtils.loadClass(fieldMapping.getCustomConverter()), srcFieldClass, + destFieldValue = mapUsingCustomConverter(MappingUtils.loadClass(fieldMapping.getCustomConverter(), beanContainer), srcFieldClass, srcFieldValue, destFieldType, destObj, fieldMapping, false); } @@ -507,7 +521,7 @@ private <T extends Enum<T>> T mapEnum(Enum<T> srcFieldValue, Class<T> destFieldT } private Object mapCustomObject(FieldMap fieldMap, Object destObj, Class<?> destFieldType, String destFieldName, Object srcFieldValue) { - srcFieldValue = MappingUtils.deProxy(srcFieldValue); + srcFieldValue = MappingUtils.deProxy(srcFieldValue, beanContainer); // Custom java bean. Need to make sure that the destination object is not // already instantiated. @@ -560,7 +574,7 @@ private Object mapCollection(Object srcObj, Object srcCollectionValue, FieldMap if (fieldMap.getDestHintContainer() == null) { Class<?> genericType = fieldMap.getGenericType(BuilderUtil.unwrapDestClassFromBuilder(destObj)); if (genericType != null) { - HintContainer destHintContainer = new HintContainer(); + HintContainer destHintContainer = new HintContainer(beanContainer); destHintContainer.setHintName(genericType.getName()); FieldMap cloneFieldMap = (FieldMap) fieldMap.clone(); cloneFieldMap.setDestHintContainer(destHintContainer); // should affect only this time as fieldMap is cloned @@ -620,7 +634,7 @@ private Object mapMap(Object srcObj, Map srcMapValue, FieldMap fieldMap, Object Map result; Map destinationMap = (Map) fieldMap.getDestValue(destObj); if (destinationMap == null) { - result = DestBeanCreator.create(srcMapValue.getClass()); + result = destBeanCreator.create(srcMapValue.getClass()); } else { result = destinationMap; if (fieldMap.isRemoveOrphans()) { @@ -1066,8 +1080,8 @@ private Collection<ClassMap> checkForSuperTypeMapping(Class<?> srcClass, Class<? // Need to call getRealSuperclass because proxied data objects will not return correct // superclass when using basic reflection - List<Class<?>> superSrcClasses = MappingUtils.getSuperClassesAndInterfaces(srcClass); - List<Class<?>> superDestClasses = MappingUtils.getSuperClassesAndInterfaces(destClass); + List<Class<?>> superSrcClasses = MappingUtils.getSuperClassesAndInterfaces(srcClass, beanContainer); + List<Class<?>> superDestClasses = MappingUtils.getSuperClassesAndInterfaces(destClass, beanContainer); // add the actual classes to check for mappings between the original and the opposite // super classes @@ -1139,7 +1153,7 @@ private ClassMap getClassMap(Class<?> srcClass, Class<?> destClass, String mapId // default as an explicit mapping must not // exist. The create default class map method will also add all default // mappings that it can determine. - mapping = ClassMapBuilder.createDefaultClassMap(globalConfiguration, srcClass, destClass); + mapping = classMapBuilder.createDefaultClassMap(globalConfiguration, srcClass, destClass); classMappings.addDefault(srcClass, destClass, mapping); } diff --git a/core/src/main/java/org/dozer/builder/DestBeanBuilderCreator.java b/core/src/main/java/org/dozer/builder/DestBeanBuilderCreator.java index 80965779f..9c176a1fb 100644 --- a/core/src/main/java/org/dozer/builder/DestBeanBuilderCreator.java +++ b/core/src/main/java/org/dozer/builder/DestBeanBuilderCreator.java @@ -16,6 +16,7 @@ package org.dozer.builder; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -31,13 +32,13 @@ public final class DestBeanBuilderCreator { * Elements of this collections should have very specific isApplicable method to avoid application to class, * which should be processed by another builder */ - private static final List<BeanBuilderCreationStrategy> pluggedStrategies = new ArrayList<BeanBuilderCreationStrategy>(); + private final List<BeanBuilderCreationStrategy> pluggedStrategies = new ArrayList<BeanBuilderCreationStrategy>(); - private DestBeanBuilderCreator() { + public DestBeanBuilderCreator() { } - public static BeanBuilder create(BeanCreationDirective directive) { + public BeanBuilder create(BeanCreationDirective directive) { for (BeanBuilderCreationStrategy strategy : new CopyOnWriteArrayList<BeanBuilderCreationStrategy>(pluggedStrategies)) { if (strategy.isApplicable(directive)) { return strategy.create(directive); @@ -47,7 +48,7 @@ public static BeanBuilder create(BeanCreationDirective directive) { return null; } - public static void addPluggedStrategy(BeanBuilderCreationStrategy beanBuilderCreationStrategy) { - pluggedStrategies.add(beanBuilderCreationStrategy); + public void addPluggedStrategies(Collection<BeanBuilderCreationStrategy> beanBuilderCreationStrategies) { + pluggedStrategies.addAll(beanBuilderCreationStrategies); } } diff --git a/core/src/main/java/org/dozer/cache/DozerCache.java b/core/src/main/java/org/dozer/cache/DozerCache.java index 935a8f5ac..5fb32a3d6 100644 --- a/core/src/main/java/org/dozer/cache/DozerCache.java +++ b/core/src/main/java/org/dozer/cache/DozerCache.java @@ -22,7 +22,6 @@ import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import org.dozer.stats.GlobalStatistics; import org.dozer.stats.StatisticType; import org.dozer.stats.StatisticsManager; @@ -38,14 +37,15 @@ public class DozerCache<KeyType, ValueType> implements Cache<KeyType, ValueType> private final LRUMap cacheMap; - StatisticsManager statMgr = GlobalStatistics.getInstance().getStatsMgr(); + StatisticsManager statMgr; - public DozerCache(final String name, final int maximumSize) { + public DozerCache(final String name, final int maximumSize, StatisticsManager statMgr) { if (maximumSize < 1) { throw new IllegalArgumentException("Dozer cache max size must be greater than 0"); } this.name = name; this.cacheMap = new LRUMap(maximumSize); // TODO This should be in Collections.synchronizedMap() + this.statMgr = statMgr; } public void clear() { diff --git a/core/src/main/java/org/dozer/cache/DozerCacheManager.java b/core/src/main/java/org/dozer/cache/DozerCacheManager.java index e18141d88..c2842f5a4 100644 --- a/core/src/main/java/org/dozer/cache/DozerCacheManager.java +++ b/core/src/main/java/org/dozer/cache/DozerCacheManager.java @@ -22,6 +22,7 @@ import java.util.Map.Entry; import java.util.Set; +import org.dozer.stats.StatisticsManager; import org.dozer.util.MappingUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,6 +38,12 @@ public final class DozerCacheManager implements CacheManager { private final Map<String, Cache> cachesMap = new HashMap<String, Cache>(); + private final StatisticsManager statisticsManager; + + public DozerCacheManager(StatisticsManager statisticsManager) { + this.statisticsManager = statisticsManager; + } + public Collection<Cache> getCaches() { return new HashSet<Cache>(cachesMap.values()); } @@ -50,7 +57,7 @@ public Cache getCache(String name) { } public void addCache(String name, int maxElementsInMemory) { - addCache(new DozerCache(name, maxElementsInMemory)); + addCache(new DozerCache(name, maxElementsInMemory, statisticsManager)); } public void addCache(Cache cache) { diff --git a/core/src/main/java/org/dozer/classmap/ClassMapBuilder.java b/core/src/main/java/org/dozer/classmap/ClassMapBuilder.java index f2427eb32..a12a8394b 100644 --- a/core/src/main/java/org/dozer/classmap/ClassMapBuilder.java +++ b/core/src/main/java/org/dozer/classmap/ClassMapBuilder.java @@ -31,10 +31,13 @@ import org.dozer.classmap.generator.ClassLevelFieldMappingGenerator; import org.dozer.classmap.generator.GeneratorUtils; import org.dozer.classmap.generator.MappingType; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.DozerField; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.GenericFieldMap; import org.dozer.fieldmap.MapFieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.DozerConstants; import org.dozer.util.MappingOptions; import org.dozer.util.MappingUtils; @@ -53,27 +56,27 @@ public final class ClassMapBuilder { private static final Logger log = LoggerFactory.getLogger(ClassMapBuilder.class); - static final List<ClassMappingGenerator> buildTimeGenerators = new ArrayList<ClassMappingGenerator>(); - static final List<ClassMappingGenerator> runTimeGenerators = new ArrayList<ClassMappingGenerator>(); + private final List<ClassMappingGenerator> buildTimeGenerators = new ArrayList<>(); + private final List<ClassMappingGenerator> runTimeGenerators = new ArrayList<>(); + private final BeanContainer beanContainer; - static { - buildTimeGenerators.add(new ClassLevelFieldMappingGenerator()); - buildTimeGenerators.add(new AnnotationPropertiesGenerator()); - buildTimeGenerators.add(new AnnotationFieldsGenerator()); + public ClassMapBuilder(BeanContainer beanContainer, DestBeanCreator destBeanCreator, BeanMappingGenerator beanMappingGenerator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + + buildTimeGenerators.add(new ClassLevelFieldMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); + buildTimeGenerators.add(new AnnotationPropertiesGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); + buildTimeGenerators.add(new AnnotationFieldsGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); buildTimeGenerators.add(new AnnotationClassesGenerator()); - buildTimeGenerators.add(new MapMappingGenerator()); - buildTimeGenerators.add(new BeanMappingGenerator()); - buildTimeGenerators.add(new CollectionMappingGenerator()); + buildTimeGenerators.add(new MapMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); + buildTimeGenerators.add(beanMappingGenerator); + buildTimeGenerators.add(new CollectionMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); - runTimeGenerators.add(new ClassLevelFieldMappingGenerator()); - runTimeGenerators.add(new AnnotationPropertiesGenerator()); - runTimeGenerators.add(new AnnotationFieldsGenerator()); + runTimeGenerators.add(new ClassLevelFieldMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); + runTimeGenerators.add(new AnnotationPropertiesGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); + runTimeGenerators.add(new AnnotationFieldsGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); runTimeGenerators.add(new AnnotationClassesGenerator()); - runTimeGenerators.add(new MapMappingGenerator()); - runTimeGenerators.add(new BeanMappingGenerator()); - } - - private ClassMapBuilder() { + runTimeGenerators.add(new MapMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory)); + runTimeGenerators.add(beanMappingGenerator); } // TODO Cover with test cases @@ -92,12 +95,12 @@ private ClassMapBuilder() { * @param destClass type to convert to * @return information about the classes being mapped */ - public static ClassMap createDefaultClassMap(Configuration globalConfiguration, Class<?> srcClass, Class<?> destClass) { + public ClassMap createDefaultClassMap(Configuration globalConfiguration, Class<?> srcClass, Class<?> destClass) { ClassMap classMap = new ClassMap(globalConfiguration); classMap.setSrcClass(new DozerClass(srcClass.getName(), srcClass, globalConfiguration.getBeanFactory(), null, null, null, null, - globalConfiguration.getMapNull(), globalConfiguration.getMapEmptyString(), false)); + globalConfiguration.getMapNull(), globalConfiguration.getMapEmptyString(), false, beanContainer)); classMap.setDestClass(new DozerClass(destClass.getName(), destClass, globalConfiguration.getBeanFactory(), null, null, null, - null, globalConfiguration.getMapNull(), globalConfiguration.getMapEmptyString(), false)); + null, globalConfiguration.getMapNull(), globalConfiguration.getMapEmptyString(), false, beanContainer)); generateMapping(classMap, globalConfiguration, buildTimeGenerators); return classMap; @@ -109,7 +112,7 @@ public static ClassMap createDefaultClassMap(Configuration globalConfiguration, * @param classMappings information about the classes being mapped * @param globalConfiguration configuration of Dozer */ - public static void addDefaultFieldMappings(ClassMappings classMappings, Configuration globalConfiguration) { + public void addDefaultFieldMappings(ClassMappings classMappings, Configuration globalConfiguration) { Set<Entry<String, ClassMap>> entries = classMappings.getAll().entrySet(); for (Entry<String, ClassMap> entry : entries) { ClassMap classMap = entry.getValue(); @@ -117,7 +120,7 @@ public static void addDefaultFieldMappings(ClassMappings classMappings, Configur } } - private static void generateMapping(ClassMap classMap, Configuration configuration, List<ClassMappingGenerator> mappingGenerators) { + private void generateMapping(ClassMap classMap, Configuration configuration, List<ClassMappingGenerator> mappingGenerators) { if (!classMap.isWildcard()) { return; } @@ -148,6 +151,16 @@ public interface ClassMappingGenerator { public static class MapMappingGenerator implements ClassMappingGenerator { + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public MapMappingGenerator(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + public boolean accepts(ClassMap classMap) { Class<?> srcClass = classMap.getSrcClassToMap(); Class<?> destClass = classMap.getDestClassToMap(); @@ -172,7 +185,7 @@ public boolean apply(ClassMap classMap, Configuration configuration) { for (PropertyDescriptor property : properties) { String fieldName = property.getName(); - if (GeneratorUtils.shouldIgnoreField(fieldName, srcClass, destClass)) { + if (GeneratorUtils.shouldIgnoreField(fieldName, srcClass, destClass, beanContainer)) { continue; } @@ -186,7 +199,7 @@ public boolean apply(ClassMap classMap, Configuration configuration) { continue; } - FieldMap fieldMap = new MapFieldMap(classMap); + FieldMap fieldMap = new MapFieldMap(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); DozerField srcField = new DozerField(MappingUtils.isSupportedMap(srcClass) ? DozerConstants.SELF_KEYWORD : fieldName, null); srcField.setKey(fieldName); @@ -219,6 +232,16 @@ public boolean apply(ClassMap classMap, Configuration configuration) { public static class CollectionMappingGenerator implements ClassMappingGenerator { + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public CollectionMappingGenerator(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + public boolean accepts(ClassMap classMap) { Class<?> srcClass = classMap.getSrcClassToMap(); Class<?> destClass = classMap.getDestClassToMap(); @@ -226,7 +249,7 @@ public boolean accepts(ClassMap classMap) { } public boolean apply(ClassMap classMap, Configuration configuration) { - FieldMap fieldMap = new GenericFieldMap(classMap); + FieldMap fieldMap = new GenericFieldMap(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); DozerField selfReference = new DozerField(DozerConstants.SELF_KEYWORD, null); fieldMap.setSrcField(selfReference); fieldMap.setDestField(selfReference); @@ -340,6 +363,16 @@ private static void applyClassMappingOptions(ClassMap classMap, MappingOptions m public static class AnnotationPropertiesGenerator implements ClassMappingGenerator { + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public AnnotationPropertiesGenerator(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + public boolean accepts(ClassMap classMap) { return true; } @@ -357,7 +390,7 @@ public boolean apply(ClassMap classMap, Configuration configuration) { String pairName = mapping.value().trim(); if (requireMapping(mapping, classMap.getDestClassToMap(), propertyName, pairName)) { GeneratorUtils.addGenericMapping(MappingType.GETTER_TO_SETTER, classMap, configuration, - propertyName, pairName.isEmpty() ? propertyName : pairName); + propertyName, pairName.isEmpty() ? propertyName : pairName, beanContainer, destBeanCreator, propertyDescriptorFactory); } } } @@ -375,7 +408,7 @@ public boolean apply(ClassMap classMap, Configuration configuration) { String pairName = mapping.value().trim(); if (requireMapping(mapping, classMap.getSrcClassToMap(), propertyName, pairName)) { GeneratorUtils.addGenericMapping(MappingType.GETTER_TO_SETTER, classMap, configuration, - pairName.isEmpty() ? propertyName : pairName, propertyName); + pairName.isEmpty() ? propertyName : pairName, propertyName, beanContainer, destBeanCreator, propertyDescriptorFactory); } } } @@ -387,6 +420,16 @@ public boolean apply(ClassMap classMap, Configuration configuration) { public static class AnnotationFieldsGenerator implements ClassMappingGenerator { + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public AnnotationFieldsGenerator(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + public boolean accepts(ClassMap classMap) { return true; } @@ -401,7 +444,7 @@ public boolean apply(ClassMap classMap, Configuration configuration) { String pairName = mapping.value().trim(); if (requireMapping(mapping, classMap.getDestClassToMap(), fieldName, pairName)) { GeneratorUtils.addGenericMapping(MappingType.FIELD_TO_FIELD, classMap, configuration, - fieldName, pairName.isEmpty() ? fieldName : pairName); + fieldName, pairName.isEmpty() ? fieldName : pairName, beanContainer, destBeanCreator, propertyDescriptorFactory); } } } @@ -417,7 +460,7 @@ public boolean apply(ClassMap classMap, Configuration configuration) { String pairName = mapping.value().trim(); if (requireMapping(mapping, classMap.getSrcClassToMap(), fieldName, pairName)) { GeneratorUtils.addGenericMapping(MappingType.FIELD_TO_FIELD, classMap, configuration, - pairName.isEmpty() ? fieldName : pairName, fieldName); + pairName.isEmpty() ? fieldName : pairName, fieldName, beanContainer, destBeanCreator, propertyDescriptorFactory); } } } diff --git a/core/src/main/java/org/dozer/classmap/ClassMapKeyFactory.java b/core/src/main/java/org/dozer/classmap/ClassMapKeyFactory.java index 7e87eb6ca..cdbc28658 100644 --- a/core/src/main/java/org/dozer/classmap/ClassMapKeyFactory.java +++ b/core/src/main/java/org/dozer/classmap/ClassMapKeyFactory.java @@ -16,6 +16,8 @@ package org.dozer.classmap; import org.apache.commons.lang3.StringUtils; + +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; /** @@ -27,7 +29,10 @@ */ public final class ClassMapKeyFactory { - public ClassMapKeyFactory() { + private final BeanContainer beanContainer; + + public ClassMapKeyFactory(BeanContainer beanContainer) { + this.beanContainer = beanContainer; } public String createKey(Class<?> srcClass, Class<?> destClass) { @@ -35,8 +40,8 @@ public String createKey(Class<?> srcClass, Class<?> destClass) { } public String createKey(Class<?> srcClass, Class<?> destClass, String mapId) { - Class<?> srcRealClass = MappingUtils.getRealClass(srcClass); - Class<?> destRealClass = MappingUtils.getRealClass(destClass); + Class<?> srcRealClass = MappingUtils.getRealClass(srcClass, beanContainer); + Class<?> destRealClass = MappingUtils.getRealClass(destClass, beanContainer); StringBuilder result = new StringBuilder(140); diff --git a/core/src/main/java/org/dozer/classmap/ClassMappings.java b/core/src/main/java/org/dozer/classmap/ClassMappings.java index a5ff5d632..39fc6daea 100644 --- a/core/src/main/java/org/dozer/classmap/ClassMappings.java +++ b/core/src/main/java/org/dozer/classmap/ClassMappings.java @@ -23,6 +23,8 @@ import java.util.concurrent.ConcurrentMap; import org.apache.commons.lang3.StringUtils; + +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; /** @@ -38,9 +40,11 @@ public class ClassMappings { // Cache key --> Mapping Structure private ConcurrentMap<String, ClassMap> classMappings = new ConcurrentHashMap<String, ClassMap>(); private ClassMapKeyFactory keyFactory; + private final BeanContainer beanContainer; - public ClassMappings() { - keyFactory = new ClassMapKeyFactory(); + public ClassMappings(BeanContainer beanContainer) { + this.beanContainer = beanContainer; + keyFactory = new ClassMapKeyFactory(beanContainer); } // Default mappings. May be ovewritten due to multiple threads generating same mapping @@ -152,7 +156,7 @@ private ClassMap findInterfaceMapping(Class<?> destClass, Class<?> srcClass, Str // Destination could be an abstract type. Picking up the best concrete type to use. if ((destClass.isAssignableFrom(mappingDestClass) && isAbstract(destClass)) || (isInterfaceImplementation(destClass, mappingDestClass))) { - if (MappingUtils.getRealClass(srcClass).equals(mappingSrcClass)) { + if (MappingUtils.getRealClass(srcClass, beanContainer).equals(mappingSrcClass)) { return map; } } diff --git a/core/src/main/java/org/dozer/classmap/DozerClass.java b/core/src/main/java/org/dozer/classmap/DozerClass.java index b370b0c0f..1332fbc0f 100644 --- a/core/src/main/java/org/dozer/classmap/DozerClass.java +++ b/core/src/main/java/org/dozer/classmap/DozerClass.java @@ -18,6 +18,8 @@ import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; + +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; /** @@ -40,12 +42,14 @@ public class DozerClass { private Boolean mapNull; private Boolean mapEmptyString; private Boolean accessible; + private final BeanContainer beanContainer; - public DozerClass() { + public DozerClass(BeanContainer beanContainer) { + this.beanContainer = beanContainer; } public DozerClass(String name, Class<?> classToMap, String beanFactory, String factoryBeanId, String mapGetMethod, - String mapSetMethod, String createMethod, Boolean mapNull, Boolean mapEmptyString, Boolean accessible) { + String mapSetMethod, String createMethod, Boolean mapNull, Boolean mapEmptyString, Boolean accessible, BeanContainer beanContainer) { this.name = name; this.classToMap = classToMap; this.beanFactory = beanFactory; @@ -56,6 +60,7 @@ public DozerClass(String name, Class<?> classToMap, String beanFactory, String f this.mapNull = mapNull; this.mapEmptyString = mapEmptyString; this.accessible = accessible; + this.beanContainer = beanContainer; } public String getBeanFactory() { @@ -76,7 +81,7 @@ public String getName() { public void setName(String name) { this.name = name; - classToMap = MappingUtils.loadClass(name); + classToMap = MappingUtils.loadClass(name, beanContainer); } public String getFactoryBeanId() { diff --git a/core/src/test/java/org/dozer/stats/GlobalStatisticsTest.java b/core/src/main/java/org/dozer/classmap/generator/BeanFieldsDetector.java similarity index 56% rename from core/src/test/java/org/dozer/stats/GlobalStatisticsTest.java rename to core/src/main/java/org/dozer/classmap/generator/BeanFieldsDetector.java index 5939bc0bf..15178122e 100644 --- a/core/src/test/java/org/dozer/stats/GlobalStatisticsTest.java +++ b/core/src/main/java/org/dozer/classmap/generator/BeanFieldsDetector.java @@ -13,21 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.dozer.stats; +package org.dozer.classmap.generator; -import org.dozer.AbstractDozerTest; -import org.junit.Test; +import java.util.Set; -/** - * @author tierney.matt - */ -public class GlobalStatisticsTest extends AbstractDozerTest { +public interface BeanFieldsDetector { + + boolean accepts(Class<?> clazz); - @Test - public void testGetInstance() throws Exception { - GlobalStatistics mgr = GlobalStatistics.getInstance(); + Set<String> getReadableFieldNames(Class<?> clazz); - assertEquals("stat mgrs should be equal", mgr, GlobalStatistics.getInstance()); - assertSame("stat mgrs should be the same instance", mgr, GlobalStatistics.getInstance()); - } + Set<String> getWritableFieldNames(Class<?> clazz); } diff --git a/core/src/main/java/org/dozer/classmap/generator/BeanMappingGenerator.java b/core/src/main/java/org/dozer/classmap/generator/BeanMappingGenerator.java index 5cf9904f6..7b1bde8ba 100644 --- a/core/src/main/java/org/dozer/classmap/generator/BeanMappingGenerator.java +++ b/core/src/main/java/org/dozer/classmap/generator/BeanMappingGenerator.java @@ -16,6 +16,7 @@ package org.dozer.classmap.generator; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; @@ -23,6 +24,9 @@ import org.dozer.classmap.ClassMap; import org.dozer.classmap.ClassMapBuilder; import org.dozer.classmap.Configuration; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.CollectionUtils; /** @@ -30,12 +34,22 @@ */ public class BeanMappingGenerator implements ClassMapBuilder.ClassMappingGenerator { - static final List<BeanFieldsDetector> pluggedFieldDetectors = new ArrayList<BeanFieldsDetector>(); + final List<BeanFieldsDetector> pluggedFieldDetectors = new ArrayList<BeanFieldsDetector>(); - static final List<BeanFieldsDetector> availableFieldDetectors = new ArrayList<BeanFieldsDetector>() {{ + final List<BeanFieldsDetector> availableFieldDetectors = new ArrayList<BeanFieldsDetector>() {{ add(new JavaBeanFieldsDetector()); }}; + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public BeanMappingGenerator(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + public boolean accepts(ClassMap classMap) { return true; } @@ -49,7 +63,7 @@ public boolean apply(ClassMap classMap, Configuration configuration) { Set<String> commonFieldNames = CollectionUtils.intersection(srcFieldNames, destFieldNames); for (String fieldName : commonFieldNames) { - if (GeneratorUtils.shouldIgnoreField(fieldName, srcClass, destClass)) { + if (GeneratorUtils.shouldIgnoreField(fieldName, srcClass, destClass, beanContainer)) { continue; } @@ -58,12 +72,12 @@ public boolean apply(ClassMap classMap, Configuration configuration) { continue; } - GeneratorUtils.addGenericMapping(MappingType.GETTER_TO_SETTER, classMap, configuration, fieldName, fieldName); + GeneratorUtils.addGenericMapping(MappingType.GETTER_TO_SETTER, classMap, configuration, fieldName, fieldName, beanContainer, destBeanCreator, propertyDescriptorFactory); } return false; } - private static BeanFieldsDetector getAcceptsFieldsDetector(Class<?> clazz) { + private BeanFieldsDetector getAcceptsFieldsDetector(Class<?> clazz) { BeanFieldsDetector detector = getAcceptsFieldDetector(clazz, pluggedFieldDetectors); if (detector == null) { detector = getAcceptsFieldDetector(clazz, availableFieldDetectors); @@ -72,7 +86,7 @@ private static BeanFieldsDetector getAcceptsFieldsDetector(Class<?> clazz) { return detector; } - private static BeanFieldsDetector getAcceptsFieldDetector(Class<?> clazz, List<BeanFieldsDetector> detectors) { + private BeanFieldsDetector getAcceptsFieldDetector(Class<?> clazz, List<BeanFieldsDetector> detectors) { for (BeanFieldsDetector detector : new CopyOnWriteArrayList<BeanFieldsDetector>(detectors)) { if (detector.accepts(clazz)) { return detector; @@ -82,13 +96,7 @@ private static BeanFieldsDetector getAcceptsFieldDetector(Class<?> clazz, List<B return null; } - public static void addPluggedFieldDetector(BeanFieldsDetector protobufBeanFieldsDetector) { - pluggedFieldDetectors.add(protobufBeanFieldsDetector); - } - - protected interface BeanFieldsDetector { - boolean accepts(Class<?> clazz); - Set<String> getReadableFieldNames(Class<?> clazz); - Set<String> getWritableFieldNames(Class<?> clazz); + public void addPluggedFieldDetectors(Collection<BeanFieldsDetector> beanFieldsDetectors) { + pluggedFieldDetectors.addAll(beanFieldsDetectors); } } diff --git a/core/src/main/java/org/dozer/classmap/generator/ClassLevelFieldMappingGenerator.java b/core/src/main/java/org/dozer/classmap/generator/ClassLevelFieldMappingGenerator.java index 964319a9e..d3fc2d9b1 100644 --- a/core/src/main/java/org/dozer/classmap/generator/ClassLevelFieldMappingGenerator.java +++ b/core/src/main/java/org/dozer/classmap/generator/ClassLevelFieldMappingGenerator.java @@ -23,7 +23,10 @@ import org.dozer.classmap.ClassMap; import org.dozer.classmap.ClassMapBuilder; import org.dozer.classmap.Configuration; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.CollectionUtils; /** @@ -32,6 +35,16 @@ */ public class ClassLevelFieldMappingGenerator implements ClassMapBuilder.ClassMappingGenerator { + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public ClassLevelFieldMappingGenerator(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + /** {@inheritDoc} */ @Override public boolean accepts(ClassMap classMap) { @@ -41,7 +54,7 @@ public boolean accepts(ClassMap classMap) { /** {@inheritDoc} */ @Override public boolean apply(ClassMap classMap, Configuration configuration) { - BeanMappingGenerator.BeanFieldsDetector beanFieldsDetector = new JavaBeanFieldsDetector(); + BeanFieldsDetector beanFieldsDetector = new JavaBeanFieldsDetector(); Set<String> destFieldNames = getDeclaredFieldNames(classMap.getDestClassToMap()); Set<String> destWritablePropertyNames = beanFieldsDetector.getWritableFieldNames(classMap.getDestClassToMap()); @@ -72,7 +85,7 @@ private void mapFieldAppropriately(ClassMap classMap, Configuration configuratio } GeneratorUtils.addGenericMapping(mappingType, classMap, configuration, - mutualFieldName, mutualFieldName); + mutualFieldName, mutualFieldName, beanContainer, destBeanCreator, propertyDescriptorFactory); } private Set<String> getDeclaredFieldNames(Class<?> srcType) { diff --git a/core/src/main/java/org/dozer/classmap/generator/GeneratorUtils.java b/core/src/main/java/org/dozer/classmap/generator/GeneratorUtils.java index 7081af43e..4b447c083 100644 --- a/core/src/main/java/org/dozer/classmap/generator/GeneratorUtils.java +++ b/core/src/main/java/org/dozer/classmap/generator/GeneratorUtils.java @@ -17,9 +17,12 @@ import org.dozer.classmap.ClassMap; import org.dozer.classmap.Configuration; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.DozerField; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.GenericFieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.MappingUtils; /** @@ -32,20 +35,21 @@ public final class GeneratorUtils { private GeneratorUtils() {} - public static boolean shouldIgnoreField(String fieldName, Class<?> srcType, Class<?> destType) { + public static boolean shouldIgnoreField(String fieldName, Class<?> srcType, Class<?> destType, BeanContainer beanContainer) { if (CLASS.equals(fieldName)) { return true; } if ((CALLBACK.equals(fieldName) || CALLBACKS.equals(fieldName)) - && (MappingUtils.isProxy(srcType) || MappingUtils.isProxy(destType))) { + && (MappingUtils.isProxy(srcType, beanContainer) || MappingUtils.isProxy(destType, beanContainer))) { return true; } return false; } public static void addGenericMapping(MappingType mappingType, ClassMap classMap, - Configuration configuration, String srcName, String destName) { - FieldMap fieldMap = new GenericFieldMap(classMap); + Configuration configuration, String srcName, String destName, BeanContainer beanContainer, + DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + FieldMap fieldMap = new GenericFieldMap(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); DozerField srcField = new DozerField(srcName, null); DozerField destField = new DozerField(destName, null); fieldMap.setSrcField(srcField); diff --git a/core/src/main/java/org/dozer/classmap/generator/JavaBeanFieldsDetector.java b/core/src/main/java/org/dozer/classmap/generator/JavaBeanFieldsDetector.java index 556e8e951..ebcc39bd1 100644 --- a/core/src/main/java/org/dozer/classmap/generator/JavaBeanFieldsDetector.java +++ b/core/src/main/java/org/dozer/classmap/generator/JavaBeanFieldsDetector.java @@ -24,7 +24,7 @@ /** * @author Dmitry Spikhalskiy */ -public class JavaBeanFieldsDetector implements BeanMappingGenerator.BeanFieldsDetector { +public class JavaBeanFieldsDetector implements BeanFieldsDetector { public boolean accepts(Class<?> clazz) { return true; } diff --git a/core/src/main/java/org/dozer/config/BeanContainer.java b/core/src/main/java/org/dozer/config/BeanContainer.java index 35244c72e..38282c8fc 100644 --- a/core/src/main/java/org/dozer/config/BeanContainer.java +++ b/core/src/main/java/org/dozer/config/BeanContainer.java @@ -28,12 +28,6 @@ */ public class BeanContainer { - private static final BeanContainer instance = new BeanContainer(); - - public static BeanContainer getInstance() { - return instance; - } - DozerClassLoader classLoader = new DefaultClassLoader(getClass().getClassLoader()); DozerClassLoader tccl = new DefaultClassLoader(Thread.currentThread().getContextClassLoader()); DozerProxyResolver proxyResolver = new DefaultProxyResolver(); diff --git a/core/src/main/java/org/dozer/config/GlobalSettings.java b/core/src/main/java/org/dozer/config/GlobalSettings.java index 73908297d..f5482e97f 100644 --- a/core/src/main/java/org/dozer/config/GlobalSettings.java +++ b/core/src/main/java/org/dozer/config/GlobalSettings.java @@ -41,8 +41,6 @@ public final class GlobalSettings { private final Logger log = LoggerFactory.getLogger(GlobalSettings.class); - private static final GlobalSettings instance = new GlobalSettings(); - private String loadedByFileName; private boolean statisticsEnabled = DozerConstants.DEFAULT_STATISTICS_ENABLED; private int converterByDestTypeCacheMaxSize = DozerConstants.DEFAULT_CONVERTER_BY_DEST_TYPE_CACHE_MAX_SIZE; @@ -53,15 +51,10 @@ public final class GlobalSettings { private String classLoaderBeanName = DozerConstants.DEFAULT_CLASS_LOADER_BEAN; private String proxyResolverBeanName = DozerConstants.DEFAULT_PROXY_RESOLVER_BEAN; - public static GlobalSettings getInstance() { - return instance; - } - - static GlobalSettings createNew() { - return new GlobalSettings(); - } + private DozerClassLoader classLoader; - private GlobalSettings() { + public GlobalSettings(DozerClassLoader classLoader) { + this.classLoader = classLoader; loadGlobalSettings(); } @@ -110,7 +103,6 @@ private synchronized void loadGlobalSettings() { log.info("Trying to find Dozer configuration file: {}", propFileName); // Load prop file. Prop file is optional, so if it's not found just use defaults - DozerClassLoader classLoader = BeanContainer.getInstance().getClassLoader(); URL url = classLoader.loadResource(propFileName); if (url == null) { log.warn("Dozer configuration file not found: {}. Using defaults for all Dozer global properties.", propFileName); diff --git a/core/src/main/java/org/dozer/converters/JAXBElementConverter.java b/core/src/main/java/org/dozer/converters/JAXBElementConverter.java index c0c6067d2..270aa52e7 100644 --- a/core/src/main/java/org/dozer/converters/JAXBElementConverter.java +++ b/core/src/main/java/org/dozer/converters/JAXBElementConverter.java @@ -22,6 +22,8 @@ import org.apache.commons.beanutils.Converter; import org.apache.commons.lang3.StringUtils; + +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; import org.dozer.util.ReflectionUtils; @@ -39,11 +41,13 @@ public class JAXBElementConverter implements Converter { private String destObjClass; private String destFieldName; private DateFormat dateFormat; + private final BeanContainer beanContainer; - public JAXBElementConverter(String destObjClass, String destFieldName, DateFormat dateFormat) { + public JAXBElementConverter(String destObjClass, String destFieldName, DateFormat dateFormat, BeanContainer beanContainer) { this.destObjClass = destObjClass; this.destFieldName = destFieldName; this.dateFormat = dateFormat; + this.beanContainer = beanContainer; } /** @@ -52,10 +56,10 @@ public JAXBElementConverter(String destObjClass, String destFieldName, DateForma * @param destObjClass type to convert to * @return instance of ObjectFactory */ - private static Object objectFactory(String destObjClass) { + private static Object objectFactory(String destObjClass, BeanContainer beanContainer) { String objectFactoryClassName = destObjClass.substring(0, destObjClass.lastIndexOf(".")) + ".ObjectFactory"; if (objectFactory == null || objectFactoryClass == null || !objectFactoryClass.getCanonicalName().equals(objectFactoryClassName)) { - objectFactoryClass = MappingUtils.loadClass(objectFactoryClassName); + objectFactoryClass = MappingUtils.loadClass(objectFactoryClassName, beanContainer); objectFactory = ReflectionUtils.newInstance(objectFactoryClass); } @@ -75,7 +79,7 @@ private static Object objectFactory(String destObjClass) { public Object convert(Class type, Object value) { Object result; - Object factory = objectFactory(destObjClass); + Object factory = objectFactory(destObjClass, beanContainer); Class<?> factoryClass = factory.getClass(); Class<?> destClass = value.getClass(); Class<?> valueClass = value.getClass(); @@ -83,7 +87,7 @@ public Object convert(Class type, Object value) { String methodName = "create" + destObjClass.substring(destObjClass.lastIndexOf(".") + 1) + StringUtils.capitalize(destFieldName); Method method = null; try { - method = ReflectionUtils.findAMethod(factoryClass, methodName); + method = ReflectionUtils.findAMethod(factoryClass, methodName, beanContainer); Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterClass : parameterTypes) { if (!valueClass.equals(parameterClass)) { @@ -122,12 +126,12 @@ public Object convert(Class type, Object value) { * @return bean id */ public String getBeanId() { - Class<?> factoryClass = objectFactory(destObjClass).getClass(); + Class<?> factoryClass = objectFactory(destObjClass, beanContainer).getClass(); Class<?> destClass = null; String methodName = "create" + destObjClass.substring(destObjClass.lastIndexOf(".") + 1) + StringUtils.capitalize(destFieldName); try { - Method method = ReflectionUtils.findAMethod(factoryClass, methodName); + Method method = ReflectionUtils.findAMethod(factoryClass, methodName, beanContainer); Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterClass : parameterTypes) { destClass = parameterClass; diff --git a/core/src/main/java/org/dozer/converters/PrimitiveOrWrapperConverter.java b/core/src/main/java/org/dozer/converters/PrimitiveOrWrapperConverter.java index 84fed762f..e55dc2932 100644 --- a/core/src/main/java/org/dozer/converters/PrimitiveOrWrapperConverter.java +++ b/core/src/main/java/org/dozer/converters/PrimitiveOrWrapperConverter.java @@ -33,6 +33,8 @@ import org.apache.commons.beanutils.converters.DoubleConverter; import org.apache.commons.beanutils.converters.FloatConverter; import org.apache.commons.lang3.ClassUtils; + +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; /** @@ -62,6 +64,12 @@ public class PrimitiveOrWrapperConverter { CONVERTER_MAP.put(Class.class, new ClassConverter()); } + private final BeanContainer beanContainer; + + public PrimitiveOrWrapperConverter(BeanContainer beanContainer) { + this.beanContainer = beanContainer; + } + public Object convert(Object srcFieldValue, Class destFieldClass, DateFormatContainer dateFormatContainer) { return convert(srcFieldValue, destFieldClass, dateFormatContainer, null, null); } @@ -102,7 +110,7 @@ private Converter getPrimitiveOrWrapperConverter(Class destClass, DateFormatCont } else if (MappingUtils.isEnumType(destClass)) { result = new EnumConverter(); } else if (JAXBElement.class.isAssignableFrom(destClass) && destFieldName != null) { - result = new JAXBElementConverter(destObj.getClass().getCanonicalName(), destFieldName, dateFormatContainer.getDateFormat()); + result = new JAXBElementConverter(destObj.getClass().getCanonicalName(), destFieldName, dateFormatContainer.getDateFormat(), beanContainer); } } return result == null ? new StringConstructorConverter(dateFormatContainer) : result; diff --git a/core/src/main/java/org/dozer/factory/ConstructionStrategies.java b/core/src/main/java/org/dozer/factory/ConstructionStrategies.java index 7a8414db6..b536e56b8 100644 --- a/core/src/main/java/org/dozer/factory/ConstructionStrategies.java +++ b/core/src/main/java/org/dozer/factory/ConstructionStrategies.java @@ -49,53 +49,66 @@ */ public final class ConstructionStrategies { - private static final BeanCreationStrategy byCreateMethod = new ConstructionStrategies.ByCreateMethod(); - private static final BeanCreationStrategy byGetInstance = new ConstructionStrategies.ByGetInstance(); - private static final BeanCreationStrategy byInterface = new ConstructionStrategies.ByInterface(); - private static final BeanCreationStrategy xmlBeansBased = new ConstructionStrategies.XMLBeansBased(); - private static final BeanCreationStrategy jaxbBeansBased = new ConstructionStrategies.JAXBBeansBased(); - private static final BeanCreationStrategy constructorBased = new ConstructionStrategies.ByConstructor(); - private static final ConstructionStrategies.ByFactory byFactory = new ConstructionStrategies.ByFactory(); - private static final BeanCreationStrategy xmlGregorianCalendar = new ConstructionStrategies.XmlGregorian(); - - private ConstructionStrategies() { - + private final BeanCreationStrategy byCreateMethod; + private final BeanCreationStrategy byGetInstance; + private final BeanCreationStrategy byInterface; + private final BeanCreationStrategy xmlBeansBased; + private final BeanCreationStrategy jaxbBeansBased; + private final BeanCreationStrategy constructorBased; + private final ConstructionStrategies.ByFactory byFactory; + private final BeanCreationStrategy xmlGregorianCalendar; + + public ConstructionStrategies(BeanContainer beanContainer) { + byCreateMethod = new ByCreateMethod(beanContainer); + byGetInstance = new ByGetInstance(beanContainer); + byInterface = new ByInterface(); + xmlBeansBased = new XMLBeansBased(beanContainer); + jaxbBeansBased = new JAXBBeansBased(beanContainer); + constructorBased = new ByConstructor(); + byFactory = new ByFactory(beanContainer); + xmlGregorianCalendar = new XmlGregorian(); } - public static BeanCreationStrategy byCreateMethod() { + public BeanCreationStrategy byCreateMethod() { return byCreateMethod; } - public static BeanCreationStrategy byGetInstance() { + public BeanCreationStrategy byGetInstance() { return byGetInstance; } - public static BeanCreationStrategy byInterface() { + public BeanCreationStrategy byInterface() { return byInterface; } - public static BeanCreationStrategy xmlBeansBased() { + public BeanCreationStrategy xmlBeansBased() { return xmlBeansBased; } - public static BeanCreationStrategy jaxbBeansBased() { + public BeanCreationStrategy jaxbBeansBased() { return jaxbBeansBased; } - public static BeanCreationStrategy byConstructor() { + public BeanCreationStrategy byConstructor() { return constructorBased; } - public static ByFactory byFactory() { + public ByFactory byFactory() { return byFactory; } - public static BeanCreationStrategy xmlGregorianCalendar() { + public BeanCreationStrategy xmlGregorianCalendar() { return xmlGregorianCalendar; } static class ByCreateMethod implements BeanCreationStrategy { + private final BeanContainer beanContainer; + + ByCreateMethod(BeanContainer beanContainer) { + this.beanContainer = beanContainer; + } + public boolean isApplicable(BeanCreationDirective directive) { String createMethod = directive.getCreateMethod(); return !MappingUtils.isBlankOrNull(createMethod); @@ -109,7 +122,7 @@ public Object create(BeanCreationDirective directive) { if (createMethod.contains(".")) { String methodName = createMethod.substring(createMethod.lastIndexOf(".") + 1, createMethod.length()); String typeName = createMethod.substring(0, createMethod.lastIndexOf(".")); - DozerClassLoader loader = BeanContainer.getInstance().getClassLoader(); + DozerClassLoader loader = beanContainer.getClassLoader(); Class type = loader.loadClass(typeName); method = findMethod(type, methodName); } else { @@ -132,6 +145,10 @@ private Method findMethod(Class<?> actualClass, String createMethod) { static class ByGetInstance extends ByCreateMethod { + ByGetInstance(BeanContainer beanContainer) { + super(beanContainer); + } + // TODO Investigate what else could be here @Override @@ -152,6 +169,11 @@ static class ByFactory implements BeanCreationStrategy { private final Logger log = LoggerFactory.getLogger(ByFactory.class); private final ConcurrentMap<String, BeanFactory> factoryCache = new ConcurrentHashMap<String, BeanFactory>(); + private final BeanContainer beanContainer; + + ByFactory(BeanContainer beanContainer) { + this.beanContainer = beanContainer; + } public boolean isApplicable(BeanCreationDirective directive) { String factoryName = directive.getFactoryName(); @@ -168,7 +190,7 @@ public Object create(BeanCreationDirective directive) { BeanFactory factory = factoryCache.get(factoryName); if (factory == null) { - Class<?> factoryClass = MappingUtils.loadClass(factoryName); + Class<?> factoryClass = MappingUtils.loadClass(factoryName, beanContainer); if (!BeanFactory.class.isAssignableFrom(factoryClass)) { MappingUtils.throwMappingException("Custom bean factory must implement " + BeanFactory.class.getName() @@ -180,7 +202,7 @@ public Object create(BeanCreationDirective directive) { factoryCache.put(factoryName, factory); } - Object result = factory.createBean(directive.getSrcObject(), directive.getSrcClass(), beanId); + Object result = factory.createBean(directive.getSrcObject(), directive.getSrcClass(), beanId, beanContainer); log.debug("Bean instance created with custom factory -->\n Bean Type: {}\n Factory Name: {}", result.getClass().getName(), factoryName); @@ -225,13 +247,15 @@ static class XMLBeansBased implements BeanCreationStrategy { final BeanFactory xmlBeanFactory; boolean xmlBeansAvailable; private Class<?> xmlObjectType; + private final BeanContainer beanContainer; - XMLBeansBased() { - this(new XMLBeanFactory()); + XMLBeansBased(BeanContainer beanContainer) { + this(new XMLBeanFactory(), beanContainer); } - XMLBeansBased(XMLBeanFactory xmlBeanFactory) { + XMLBeansBased(XMLBeanFactory xmlBeanFactory, BeanContainer beanContainer) { this.xmlBeanFactory = xmlBeanFactory; + this.beanContainer = beanContainer; try { xmlObjectType = Class.forName("org.apache.xmlbeans.XmlObject"); xmlBeansAvailable = true; @@ -252,7 +276,7 @@ public Object create(BeanCreationDirective directive) { Class<?> classToCreate = directive.getActualClass(); String factoryBeanId = directive.getFactoryId(); String beanId = !MappingUtils.isBlankOrNull(factoryBeanId) ? factoryBeanId : classToCreate.getName(); - return xmlBeanFactory.createBean(directive.getSrcObject(), directive.getSrcClass(), beanId); + return xmlBeanFactory.createBean(directive.getSrcObject(), directive.getSrcClass(), beanId, beanContainer); } } @@ -262,13 +286,15 @@ static class JAXBBeansBased implements BeanCreationStrategy { final BeanFactory jaxbBeanFactory; boolean jaxbBeansAvailable; private Class<?> jaxbObjectType; + private final BeanContainer beanContainer; - JAXBBeansBased() { - this(new JAXBBeanFactory()); + JAXBBeansBased(BeanContainer beanContainer) { + this(new JAXBBeanFactory(), beanContainer); } - JAXBBeansBased(JAXBBeanFactory jaxbBeanFactory) { + JAXBBeansBased(JAXBBeanFactory jaxbBeanFactory, BeanContainer beanContainer) { this.jaxbBeanFactory = jaxbBeanFactory; + this.beanContainer = beanContainer; try { jaxbObjectType = Class.forName("javax.xml.bind.JAXBElement"); jaxbBeansAvailable = true; @@ -288,9 +314,9 @@ public boolean isApplicable(BeanCreationDirective directive) { public Object create(BeanCreationDirective directive) { JAXBElementConverter jaxbElementConverter = new JAXBElementConverter( (directive.getDestObj() != null) ? directive.getDestObj().getClass().getCanonicalName() : directive.getActualClass().getCanonicalName(), directive.getFieldName(), - null); + null, beanContainer); String beanId = jaxbElementConverter.getBeanId(); - Object destValue = jaxbBeanFactory.createBean(directive.getSrcObject(), directive.getSrcClass(), beanId); + Object destValue = jaxbBeanFactory.createBean(directive.getSrcObject(), directive.getSrcClass(), beanId, beanContainer); return jaxbElementConverter.convert(jaxbObjectType, (destValue != null) ? destValue : directive.getSrcObject()); } } diff --git a/core/src/main/java/org/dozer/factory/DestBeanCreator.java b/core/src/main/java/org/dozer/factory/DestBeanCreator.java index 0586ba213..49534c0c4 100644 --- a/core/src/main/java/org/dozer/factory/DestBeanCreator.java +++ b/core/src/main/java/org/dozer/factory/DestBeanCreator.java @@ -22,6 +22,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import org.dozer.BeanFactory; +import org.dozer.config.BeanContainer; /** * Internal class that contains the logic used to create a new instance of the destination object being mapped. Performs @@ -37,29 +38,34 @@ public final class DestBeanCreator { static final List<BeanCreationStrategy> pluggedStrategies = new ArrayList<BeanCreationStrategy>(); // order in this collection determines resolving priority - static final BeanCreationStrategy[] availableStrategies = new BeanCreationStrategy[]{ - ConstructionStrategies.byCreateMethod(), - ConstructionStrategies.byGetInstance(), - ConstructionStrategies.xmlGregorianCalendar(), - ConstructionStrategies.byInterface(), - ConstructionStrategies.xmlBeansBased(), - ConstructionStrategies.jaxbBeansBased(), - ConstructionStrategies.byFactory(), - ConstructionStrategies.byConstructor() - }; + private final BeanCreationStrategy[] availableStrategies; + private final ConstructionStrategies constructionStrategies; + private final BeanContainer beanContainer; - private DestBeanCreator() { + public DestBeanCreator(BeanContainer beanContainer) { + this.constructionStrategies = new ConstructionStrategies(beanContainer); + this.beanContainer = beanContainer; + this.availableStrategies = new BeanCreationStrategy[]{ + this.constructionStrategies.byCreateMethod(), + this.constructionStrategies.byGetInstance(), + this.constructionStrategies.xmlGregorianCalendar(), + this.constructionStrategies.byInterface(), + this.constructionStrategies.xmlBeansBased(), + this.constructionStrategies.jaxbBeansBased(), + this.constructionStrategies.byFactory(), + this.constructionStrategies.byConstructor() + }; } - public static <T> T create(Class<T> targetClass) { + public <T> T create(Class<T> targetClass) { return (T) create(targetClass, null); } - public static Object create(Class<?> targetClass, Class<?> alternateClass) { + public Object create(Class<?> targetClass, Class<?> alternateClass) { return create(new BeanCreationDirective(null, null, targetClass, alternateClass, null, null, null)); } - public static Object create(BeanCreationDirective directive) { + public Object create(BeanCreationDirective directive) { Object result = applyStrategies(directive, pluggedStrategies); if (result == null) { result = applyStrategies(directive, Arrays.asList(availableStrategies)); @@ -68,7 +74,7 @@ public static Object create(BeanCreationDirective directive) { return result; } - private static Object applyStrategies(BeanCreationDirective directive, List<BeanCreationStrategy> strategies) { + private Object applyStrategies(BeanCreationDirective directive, List<BeanCreationStrategy> strategies) { // TODO create method lookup by annotation/convention // TODO Cache ConstructionStrategy (reuse caching infrastructure) // TODO Check resulting type in each method @@ -83,11 +89,11 @@ private static Object applyStrategies(BeanCreationDirective directive, List<Bean return null; } - public static void setStoredFactories(Map<String, BeanFactory> factories) { - ConstructionStrategies.byFactory().setStoredFactories(factories); + public void setStoredFactories(Map<String, BeanFactory> factories) { + constructionStrategies.byFactory().setStoredFactories(factories); } - public static void addPluggedStrategy(BeanCreationStrategy strategy) { + public void addPluggedStrategy(BeanCreationStrategy strategy) { pluggedStrategies.add(strategy); } diff --git a/core/src/main/java/org/dozer/factory/JAXBBeanFactory.java b/core/src/main/java/org/dozer/factory/JAXBBeanFactory.java index a8a76cc61..9012661f3 100644 --- a/core/src/main/java/org/dozer/factory/JAXBBeanFactory.java +++ b/core/src/main/java/org/dozer/factory/JAXBBeanFactory.java @@ -18,6 +18,7 @@ import java.lang.reflect.Method; import org.dozer.BeanFactory; +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; import org.dozer.util.ReflectionUtils; import org.slf4j.Logger; @@ -44,7 +45,7 @@ public class JAXBBeanFactory implements BeanFactory { * @return A implementation of the destination interface */ @Override - public Object createBean(Object srcObj, Class<?> srcObjClass, String beanId) { + public Object createBean(Object srcObj, Class<?> srcObjClass, String beanId, BeanContainer beanContainer) { log.debug("createBean(Object, Class, String) - start [{}]", beanId); int indexOf = beanId.indexOf(INNER_CLASS_DELIMITER); @@ -55,7 +56,7 @@ public Object createBean(Object srcObj, Class<?> srcObjClass, String beanId) { } Object result; - Class<?> objectFactory = MappingUtils.loadClass(beanId.substring(0, beanId.lastIndexOf(".")) + ".ObjectFactory"); + Class<?> objectFactory = MappingUtils.loadClass(beanId.substring(0, beanId.lastIndexOf(".")) + ".ObjectFactory", beanContainer); Object factory = ReflectionUtils.newInstance(objectFactory); Method method = null; try { diff --git a/core/src/main/java/org/dozer/factory/XMLBeanFactory.java b/core/src/main/java/org/dozer/factory/XMLBeanFactory.java index 8a56f4914..c8a18ccf6 100644 --- a/core/src/main/java/org/dozer/factory/XMLBeanFactory.java +++ b/core/src/main/java/org/dozer/factory/XMLBeanFactory.java @@ -18,6 +18,7 @@ import java.lang.reflect.Method; import org.dozer.BeanFactory; +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; import org.dozer.util.ReflectionUtils; @@ -40,9 +41,9 @@ public class XMLBeanFactory implements BeanFactory { * the name of the destination interface class * @return A implementation of the destination interface */ - public Object createBean(Object srcObj, Class<?> srcObjClass, String beanId) { + public Object createBean(Object srcObj, Class<?> srcObjClass, String beanId, BeanContainer beanContainer) { Object result; - Class<?> destClass = MappingUtils.loadClass(beanId); + Class<?> destClass = MappingUtils.loadClass(beanId, beanContainer); Class<?>[] innerClasses = destClass.getClasses(); Class<?> factory = null; for (Class<?> innerClass : innerClasses) { diff --git a/core/src/main/java/org/dozer/fieldmap/CustomGetSetMethodFieldMap.java b/core/src/main/java/org/dozer/fieldmap/CustomGetSetMethodFieldMap.java index b46f864bf..b139b1385 100644 --- a/core/src/main/java/org/dozer/fieldmap/CustomGetSetMethodFieldMap.java +++ b/core/src/main/java/org/dozer/fieldmap/CustomGetSetMethodFieldMap.java @@ -16,6 +16,9 @@ package org.dozer.fieldmap; import org.dozer.classmap.ClassMap; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; /** * Only intended for internal use. @@ -26,7 +29,7 @@ * */ public class CustomGetSetMethodFieldMap extends FieldMap { - public CustomGetSetMethodFieldMap(ClassMap classMap) { - super(classMap); + public CustomGetSetMethodFieldMap(ClassMap classMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + super(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); } } diff --git a/core/src/main/java/org/dozer/fieldmap/ExcludeFieldMap.java b/core/src/main/java/org/dozer/fieldmap/ExcludeFieldMap.java index de270a59b..ac5c6d3e9 100755 --- a/core/src/main/java/org/dozer/fieldmap/ExcludeFieldMap.java +++ b/core/src/main/java/org/dozer/fieldmap/ExcludeFieldMap.java @@ -16,6 +16,9 @@ package org.dozer.fieldmap; import org.dozer.classmap.ClassMap; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; /** * Only intended for internal use. @@ -27,8 +30,8 @@ */ public class ExcludeFieldMap extends FieldMap { - public ExcludeFieldMap(ClassMap classMap) { - super(classMap); + public ExcludeFieldMap(ClassMap classMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + super(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); } } \ No newline at end of file diff --git a/core/src/main/java/org/dozer/fieldmap/FieldMap.java b/core/src/main/java/org/dozer/fieldmap/FieldMap.java index 4fb41f2a3..557573f0c 100755 --- a/core/src/main/java/org/dozer/fieldmap/FieldMap.java +++ b/core/src/main/java/org/dozer/fieldmap/FieldMap.java @@ -27,6 +27,8 @@ import org.dozer.classmap.DozerClass; import org.dozer.classmap.MappingDirection; import org.dozer.classmap.RelationshipType; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.propertydescriptor.DozerPropertyDescriptor; import org.dozer.propertydescriptor.GetterSetterPropertyDescriptor; import org.dozer.propertydescriptor.PropertyDescriptorFactory; @@ -49,6 +51,10 @@ public abstract class FieldMap implements Cloneable { private final Logger log = LoggerFactory.getLogger(FieldMap.class); + protected final BeanContainer beanContainer; + protected final DestBeanCreator destBeanCreator; + protected final PropertyDescriptorFactory propertyDescriptorFactory; + private ClassMap classMap; private DozerField srcField; private DozerField destField; @@ -69,8 +75,11 @@ public abstract class FieldMap implements Cloneable { private final ConcurrentMap<Class<?>, DozerPropertyDescriptor> srcPropertyDescriptorMap = new ConcurrentHashMap<Class<?>, DozerPropertyDescriptor>(); // For Caching Purposes private final ConcurrentMap<Class<?>, DozerPropertyDescriptor> destPropertyDescriptorMap = new ConcurrentHashMap<Class<?>, DozerPropertyDescriptor>(); - public FieldMap(ClassMap classMap) { + public FieldMap(ClassMap classMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { this.classMap = classMap; + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; } public ClassMap getClassMap() { @@ -381,11 +390,11 @@ protected DozerPropertyDescriptor getSrcPropertyDescriptor(Class<?> runtimeSrcCl if (result == null) { String srcFieldMapGetMethod = getSrcFieldMapGetMethod(); String srcFieldMapSetMethod = getSrcFieldMapSetMethod(); - DozerPropertyDescriptor descriptor = PropertyDescriptorFactory.getPropertyDescriptor(runtimeSrcClass, + DozerPropertyDescriptor descriptor = propertyDescriptorFactory.getPropertyDescriptor(runtimeSrcClass, getSrcFieldTheGetMethod(), getSrcFieldTheSetMethod(), srcFieldMapGetMethod, srcFieldMapSetMethod, isSrcFieldAccessible(), isSrcFieldIndexed(), getSrcFieldIndex(), getSrcFieldName(), getSrcFieldKey(), isSrcSelfReferencing(), getDestFieldName(), getSrcDeepIndexHintContainer(), - getDestDeepIndexHintContainer(), classMap.getSrcClassBeanFactory()); + getDestDeepIndexHintContainer(), classMap.getSrcClassBeanFactory(), beanContainer, destBeanCreator); this.srcPropertyDescriptorMap.putIfAbsent(runtimeSrcClass, descriptor); result = descriptor; } @@ -401,11 +410,12 @@ protected DozerPropertyDescriptor getDestPropertyDescriptor(Class<?> runtimeDest DozerPropertyDescriptor result = this.destPropertyDescriptorMap.get(runtimeDestClass); if (result == null) { - DozerPropertyDescriptor descriptor = PropertyDescriptorFactory.getPropertyDescriptor(runtimeDestClass, + DozerPropertyDescriptor descriptor = propertyDescriptorFactory.getPropertyDescriptor(runtimeDestClass, getDestFieldTheGetMethod(), getDestFieldTheSetMethod(), getDestFieldMapGetMethod(), getDestFieldMapSetMethod(), isDestFieldAccessible(), isDestFieldIndexed(), getDestFieldIndex(), getDestFieldName(), getDestFieldKey(), isDestSelfReferencing(), getSrcFieldName(), - getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer(), classMap.getDestClassBeanFactory()); + getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer(), classMap.getDestClassBeanFactory(), + beanContainer, destBeanCreator); this.destPropertyDescriptorMap.putIfAbsent(runtimeDestClass, descriptor); result = descriptor; diff --git a/core/src/main/java/org/dozer/fieldmap/GenericFieldMap.java b/core/src/main/java/org/dozer/fieldmap/GenericFieldMap.java index 35ddb45a7..663941353 100755 --- a/core/src/main/java/org/dozer/fieldmap/GenericFieldMap.java +++ b/core/src/main/java/org/dozer/fieldmap/GenericFieldMap.java @@ -16,6 +16,9 @@ package org.dozer.fieldmap; import org.dozer.classmap.ClassMap; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; /** * Only intended for internal use. @@ -26,7 +29,7 @@ * */ public class GenericFieldMap extends FieldMap { - public GenericFieldMap(ClassMap classMap) { - super(classMap); + public GenericFieldMap(ClassMap classMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + super(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); } } diff --git a/core/src/main/java/org/dozer/fieldmap/HintContainer.java b/core/src/main/java/org/dozer/fieldmap/HintContainer.java index f94dc1921..5f81b378d 100755 --- a/core/src/main/java/org/dozer/fieldmap/HintContainer.java +++ b/core/src/main/java/org/dozer/fieldmap/HintContainer.java @@ -21,6 +21,8 @@ import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; + +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; /** @@ -34,6 +36,11 @@ public class HintContainer { private String hintName; private List<Class<?>> hints; + private final BeanContainer beanContainer; + + public HintContainer(BeanContainer beanContainer) { + this.beanContainer = beanContainer; + } public Class<?> getHint() { Class<?> result; @@ -60,7 +67,7 @@ public List<Class<?>> getHints() { while (st.hasMoreElements()) { String theHintName = st.nextToken().trim(); - Class<?> clazz = MappingUtils.loadClass(theHintName); + Class<?> clazz = MappingUtils.loadClass(theHintName, beanContainer); list.add(clazz); } hints = list; @@ -81,7 +88,7 @@ public Class<?> getHint(Class<?> clazz, List<Class<?>> clazzHints) { .throwMappingException("When using multiple source and destination hints there must be exactly the same number of hints on the source and the destination."); } int count = 0; - String myClazName = MappingUtils.getRealClass(clazz).getName(); + String myClazName = MappingUtils.getRealClass(clazz, beanContainer).getName(); int size = clazzHints.size(); for (int i = 0; i < size; i++) { Class<?> element = clazzHints.get(i); diff --git a/core/src/main/java/org/dozer/fieldmap/MapFieldMap.java b/core/src/main/java/org/dozer/fieldmap/MapFieldMap.java index d311f494a..33a017227 100644 --- a/core/src/main/java/org/dozer/fieldmap/MapFieldMap.java +++ b/core/src/main/java/org/dozer/fieldmap/MapFieldMap.java @@ -16,11 +16,13 @@ package org.dozer.fieldmap; import org.dozer.classmap.ClassMap; +import org.dozer.config.BeanContainer; import org.dozer.factory.DestBeanCreator; import org.dozer.propertydescriptor.DozerPropertyDescriptor; import org.dozer.propertydescriptor.FieldPropertyDescriptor; import org.dozer.propertydescriptor.JavaBeanPropertyDescriptor; import org.dozer.propertydescriptor.MapPropertyDescriptor; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.DozerConstants; import org.dozer.util.MappingUtils; @@ -36,13 +38,13 @@ */ public class MapFieldMap extends FieldMap { - public MapFieldMap(ClassMap classMap) { - super(classMap); + public MapFieldMap(ClassMap classMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + super(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); } - public MapFieldMap(FieldMap fieldMap) { + public MapFieldMap(FieldMap fieldMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { //Create from existing field map - super(fieldMap.getClassMap()); + super(fieldMap.getClassMap(), beanContainer, destBeanCreator, propertyDescriptorFactory); setCopyByReference(fieldMap.isCopyByReference()); setCustomConverter(fieldMap.getCustomConverter()); setCustomConverterId(fieldMap.getCustomConverterId()); @@ -103,7 +105,7 @@ public Object getSrcFieldValue(Object srcObj) { String key = getSrcFieldKey() != null ? getSrcFieldKey() : getDestFieldName(); propDescriptor = new MapPropertyDescriptor(actualType, getSrcFieldName(), isSrcFieldIndexed(), getDestFieldIndex(), - setMethod, getMethod, key, getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer()); + setMethod, getMethod, key, getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer(), beanContainer, destBeanCreator); } else { propDescriptor = super.getSrcPropertyDescriptor(srcObj.getClass()); } @@ -123,10 +125,10 @@ private PrepareTargetObjectResult prepareTargetObject(Object destObj) { DozerPropertyDescriptor pd; if (isDestFieldAccessible()) { pd = new FieldPropertyDescriptor(destObj.getClass(), getDestFieldName(), isDestFieldIndexed(), getDestFieldIndex(), - getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer()); + getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer(), destBeanCreator); } else { pd = new JavaBeanPropertyDescriptor(destObj.getClass(), getDestFieldName(), isDestFieldIndexed(), getDestFieldIndex(), - getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer()); + getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer(), beanContainer, destBeanCreator); } Class<?> c = pd.getPropertyType(); @@ -145,14 +147,14 @@ private PrepareTargetObjectResult prepareTargetObject(Object destObj) { } //TODO: add support for custom factory/create method in conjunction with Map backed properties - targetObject = DestBeanCreator.create(c, destObj.getClass()); + targetObject = destBeanCreator.create(c, destObj.getClass()); pd.setPropertyValue(destObj, targetObject, this); } return new PrepareTargetObjectResult(targetObject, new MapPropertyDescriptor(c, getDestFieldName(), isDestFieldIndexed(), getDestFieldIndex(), MappingUtils.isSupportedMap(c) ? "put" : getDestFieldMapSetMethod(), MappingUtils.isSupportedMap(c) ? "get" : getDestFieldMapGetMethod(), getDestFieldKey() != null ? getDestFieldKey() - : getSrcFieldName(), getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer())); + : getSrcFieldName(), getSrcDeepIndexHintContainer(), getDestDeepIndexHintContainer(), beanContainer, destBeanCreator)); } @@ -161,10 +163,10 @@ private Class<?> determineActualPropertyType(String fieldName, boolean isIndexed DozerPropertyDescriptor pd; if ((isDestObj && isDestFieldAccessible()) || (!isDestObj && isSrcFieldAccessible())) { pd = new FieldPropertyDescriptor(targetObj.getClass(), fieldName, isIndexed, index, getSrcDeepIndexHintContainer(), - getDestDeepIndexHintContainer()); + getDestDeepIndexHintContainer(), destBeanCreator); } else { pd = new JavaBeanPropertyDescriptor(targetObj.getClass(), fieldName, isIndexed, index, getSrcDeepIndexHintContainer(), - getDestDeepIndexHintContainer()); + getDestDeepIndexHintContainer(), beanContainer, destBeanCreator); } return pd.getPropertyType(); diff --git a/core/src/main/java/org/dozer/jmx/DozerAdminController.java b/core/src/main/java/org/dozer/jmx/DozerAdminController.java index 3e16a3226..91bec6713 100644 --- a/core/src/main/java/org/dozer/jmx/DozerAdminController.java +++ b/core/src/main/java/org/dozer/jmx/DozerAdminController.java @@ -25,15 +25,21 @@ */ public class DozerAdminController implements DozerAdminControllerMBean { + private final GlobalSettings globalSettings; + + public DozerAdminController(GlobalSettings globalSettings) { + this.globalSettings = globalSettings; + } + public String getCurrentVersion() { return DozerConstants.CURRENT_VERSION; } public boolean isStatisticsEnabled() { - return GlobalSettings.getInstance().isStatisticsEnabled(); + return globalSettings.isStatisticsEnabled(); } public void setStatisticsEnabled(boolean statisticsEnabled) { - GlobalSettings.getInstance().setStatisticsEnabled(statisticsEnabled); + globalSettings.setStatisticsEnabled(statisticsEnabled); } } diff --git a/core/src/main/java/org/dozer/jmx/DozerStatisticsController.java b/core/src/main/java/org/dozer/jmx/DozerStatisticsController.java index 33019f99b..d000edf7e 100644 --- a/core/src/main/java/org/dozer/jmx/DozerStatisticsController.java +++ b/core/src/main/java/org/dozer/jmx/DozerStatisticsController.java @@ -19,7 +19,6 @@ import java.util.TreeSet; import org.dozer.config.GlobalSettings; -import org.dozer.stats.GlobalStatistics; import org.dozer.stats.StatisticEntry; import org.dozer.stats.StatisticType; import org.dozer.stats.StatisticsManager; @@ -31,18 +30,24 @@ */ public class DozerStatisticsController implements DozerStatisticsControllerMBean { - private final StatisticsManager statsMgr = GlobalStatistics.getInstance().getStatsMgr(); + private final StatisticsManager statsMgr; + private final GlobalSettings globalSettings; + + public DozerStatisticsController(StatisticsManager statsMgr, GlobalSettings globalSettings) { + this.statsMgr = statsMgr; + this.globalSettings = globalSettings; + } public void clearAll() { statsMgr.clearAll(); } public boolean isStatisticsEnabled() { - return GlobalSettings.getInstance().isStatisticsEnabled(); + return globalSettings.isStatisticsEnabled(); } public void setStatisticsEnabled(boolean statisticsEnabled) { - GlobalSettings.getInstance().setStatisticsEnabled(statisticsEnabled); + globalSettings.setStatisticsEnabled(statisticsEnabled); } public long getMappingSuccessCount() { diff --git a/core/src/main/java/org/dozer/loader/CustomMappingsLoader.java b/core/src/main/java/org/dozer/loader/CustomMappingsLoader.java index 391a94aff..63b49d712 100644 --- a/core/src/main/java/org/dozer/loader/CustomMappingsLoader.java +++ b/core/src/main/java/org/dozer/loader/CustomMappingsLoader.java @@ -28,6 +28,7 @@ import org.dozer.classmap.ClassMappings; import org.dozer.classmap.Configuration; import org.dozer.classmap.MappingFileData; +import org.dozer.config.BeanContainer; import org.dozer.converters.CustomConverterContainer; import org.dozer.converters.CustomConverterDescription; import org.dozer.util.MappingUtils; @@ -42,13 +43,21 @@ */ public class CustomMappingsLoader { - private static final MappingsParser mappingsParser = MappingsParser.getInstance(); + private final MappingsParser mappingsParser; + private final ClassMapBuilder classMapBuilder; + private final BeanContainer beanContainer; + + public CustomMappingsLoader(MappingsParser mappingsParser, ClassMapBuilder classMapBuilder, BeanContainer beanContainer) { + this.mappingsParser = mappingsParser; + this.classMapBuilder = classMapBuilder; + this.beanContainer = beanContainer; + } public LoadMappingsResult load(List<MappingFileData> mappings) { Configuration globalConfiguration = findConfiguration(mappings); - ClassMappings customMappings = new ClassMappings(); + ClassMappings customMappings = new ClassMappings(beanContainer); // Decorate the raw ClassMap objects and create ClassMap "prime" instances for (MappingFileData mappingFileData : mappings) { List<ClassMap> classMaps = mappingFileData.getClassMaps(); @@ -58,7 +67,7 @@ public LoadMappingsResult load(List<MappingFileData> mappings) { // Add default mappings using matching property names if wildcard policy // is true. The addDefaultFieldMappings will check the wildcard policy of each classmap - ClassMapBuilder.addDefaultFieldMappings(customMappings, globalConfiguration); + classMapBuilder.addDefaultFieldMappings(customMappings, globalConfiguration); Set<CustomConverterDescription> customConverterDescriptions = new LinkedHashSet<CustomConverterDescription>(); diff --git a/core/src/main/java/org/dozer/loader/DozerBuilder.java b/core/src/main/java/org/dozer/loader/DozerBuilder.java index 030444965..242af47d0 100644 --- a/core/src/main/java/org/dozer/loader/DozerBuilder.java +++ b/core/src/main/java/org/dozer/loader/DozerBuilder.java @@ -28,7 +28,9 @@ import org.dozer.classmap.MappingDirection; import org.dozer.classmap.MappingFileData; import org.dozer.classmap.RelationshipType; +import org.dozer.config.BeanContainer; import org.dozer.converters.CustomConverterDescription; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.CustomGetSetMethodFieldMap; import org.dozer.fieldmap.DozerField; import org.dozer.fieldmap.ExcludeFieldMap; @@ -36,6 +38,7 @@ import org.dozer.fieldmap.GenericFieldMap; import org.dozer.fieldmap.HintContainer; import org.dozer.fieldmap.MapFieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.DozerConstants; import org.dozer.util.MappingUtils; @@ -54,6 +57,15 @@ public class DozerBuilder { MappingFileData data = new MappingFileData(); private final List<MappingBuilder> mappingBuilders = new ArrayList<MappingBuilder>(); + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public DozerBuilder(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } public MappingFileData build() { for (MappingBuilder builder : mappingBuilders) { @@ -65,14 +77,14 @@ public MappingFileData build() { public ConfigurationBuilder configuration() { Configuration configuration = new Configuration(); data.setConfiguration(configuration); - return new ConfigurationBuilder(configuration); + return new ConfigurationBuilder(configuration, beanContainer); } public MappingBuilder mapping() { Configuration configuration = data.getConfiguration(); ClassMap classMap = new ClassMap(configuration); data.getClassMaps().add(classMap); - MappingBuilder mappingDefinitionBuilder = new MappingBuilder(classMap); + MappingBuilder mappingDefinitionBuilder = new MappingBuilder(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); mappingBuilders.add(mappingDefinitionBuilder); return mappingDefinitionBuilder; } @@ -81,9 +93,15 @@ public static class MappingBuilder { private ClassMap classMap; private final List<FieldBuider> fieldBuilders = new ArrayList<FieldBuider>(); + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; - public MappingBuilder(ClassMap classMap) { + public MappingBuilder(ClassMap classMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { this.classMap = classMap; + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; } public MappingBuilder dateFormat(String dateFormat) { @@ -138,38 +156,38 @@ public MappingBuilder type(MappingDirection type) { } public ClassDefinitionBuilder classA(String typeName) { - Class<?> type = MappingUtils.loadClass(typeName); + Class<?> type = MappingUtils.loadClass(typeName, beanContainer); return classA(type); } public ClassDefinitionBuilder classA(Class type) { - DozerClass classDefinition = new DozerClass(); + DozerClass classDefinition = new DozerClass(beanContainer); classDefinition.setName(type.getName()); classMap.setSrcClass(classDefinition); return new ClassDefinitionBuilder(classDefinition); } public ClassDefinitionBuilder classB(String typeName) { - Class<?> type = MappingUtils.loadClass(typeName); + Class<?> type = MappingUtils.loadClass(typeName, beanContainer); return classB(type); } public ClassDefinitionBuilder classB(Class type) { - DozerClass classDefinition = new DozerClass(); + DozerClass classDefinition = new DozerClass(beanContainer); classDefinition.setName(type.getName()); classMap.setDestClass(classDefinition); return new ClassDefinitionBuilder(classDefinition); } public FieldExclusionBuilder fieldExclude() { - ExcludeFieldMap excludeFieldMap = new ExcludeFieldMap(classMap); + ExcludeFieldMap excludeFieldMap = new ExcludeFieldMap(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); FieldExclusionBuilder builder = new FieldExclusionBuilder(excludeFieldMap); fieldBuilders.add(builder); return builder; } public FieldMappingBuilder field() { - FieldMappingBuilder builder = new FieldMappingBuilder(classMap); + FieldMappingBuilder builder = new FieldMappingBuilder(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); fieldBuilders.add(builder); return builder; } @@ -241,8 +259,15 @@ public static class FieldMappingBuilder implements FieldBuider { private String customConverterParam; private boolean copyByReferenceSet; - public FieldMappingBuilder(ClassMap classMap) { + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public FieldMappingBuilder(ClassMap classMap, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { this.classMap = classMap; + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; } public FieldDefinitionBuilder a(String name) { @@ -278,25 +303,25 @@ public void removeOrphans(boolean value) { } public void srcHintContainer(String hint) { - HintContainer hintContainer = new HintContainer(); + HintContainer hintContainer = new HintContainer(beanContainer); hintContainer.setHintName(hint); this.srcHintContainer = hintContainer; } public void destHintContainer(String hint) { - HintContainer hintContainer = new HintContainer(); + HintContainer hintContainer = new HintContainer(beanContainer); hintContainer.setHintName(hint); this.destHintContainer = hintContainer; } public void srcDeepIndexHintContainer(String hint) { - HintContainer hintContainer = new HintContainer(); + HintContainer hintContainer = new HintContainer(beanContainer); hintContainer.setHintName(hint); this.srcDeepIndexHintContainer = hintContainer; } public void destDeepIndexHintContainer(String hint) { - HintContainer hintContainer = new HintContainer(); + HintContainer hintContainer = new HintContainer(beanContainer); hintContainer.setHintName(hint); this.destDeepIndexHintContainer = hintContainer; } @@ -331,11 +356,11 @@ public void build() { FieldMap result; if (srcField.isMapTypeCustomGetterSetterField() || destField.isMapTypeCustomGetterSetterField() || classMap.isSrcClassMapTypeCustomGetterSetter() || classMap.isDestClassMapTypeCustomGetterSetter()) { - result = new MapFieldMap(classMap); + result = new MapFieldMap(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); } else if (srcField.isCustomGetterSetterField() || destField.isCustomGetterSetterField()) { - result = new CustomGetSetMethodFieldMap(classMap); + result = new CustomGetSetMethodFieldMap(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); } else { - result = new GenericFieldMap(classMap); + result = new GenericFieldMap(classMap, beanContainer, destBeanCreator, propertyDescriptorFactory); } result.setSrcField(srcField); @@ -494,8 +519,11 @@ public static class ConfigurationBuilder { private CustomConverterDescription converterDescription; - public ConfigurationBuilder(Configuration configuration) { + private final BeanContainer beanContainer; + + public ConfigurationBuilder(Configuration configuration, BeanContainer beanContainer) { this.configuration = configuration; + this.beanContainer = beanContainer; } public void stopOnErrors(Boolean value) { @@ -535,7 +563,7 @@ public void beanFactory(String name) { } public CustomConverterBuilder customConverter(String type) { - Class<?> aClass = MappingUtils.loadClass(type); + Class<?> aClass = MappingUtils.loadClass(type, beanContainer); return customConverter(aClass); } @@ -544,7 +572,7 @@ public CustomConverterBuilder customConverter(Class type) { converterDescription = new CustomConverterDescription(); converterDescription.setType(type); configuration.getCustomConverters().addConverter(converterDescription); - return new CustomConverterBuilder(converterDescription); + return new CustomConverterBuilder(converterDescription, beanContainer); } public ConfigurationBuilder copyByReference(String typeMask) { @@ -554,7 +582,7 @@ public ConfigurationBuilder copyByReference(String typeMask) { } public ConfigurationBuilder allowedException(String type) { - Class<?> exceptionType = MappingUtils.loadClass(type); + Class<?> exceptionType = MappingUtils.loadClass(type, beanContainer); return allowedException(exceptionType); } @@ -572,13 +600,15 @@ public ConfigurationBuilder allowedException(Class type) { public static class CustomConverterBuilder { private CustomConverterDescription converterDescription; + private final BeanContainer beanContainer; - public CustomConverterBuilder(CustomConverterDescription converterDescription) { + public CustomConverterBuilder(CustomConverterDescription converterDescription, BeanContainer beanContainer) { this.converterDescription = converterDescription; + this.beanContainer = beanContainer; } public CustomConverterBuilder classA(String type) { - Class<?> aClass = MappingUtils.loadClass(type); + Class<?> aClass = MappingUtils.loadClass(type, beanContainer); return classA(aClass); } @@ -588,7 +618,7 @@ public CustomConverterBuilder classA(Class type) { } public CustomConverterBuilder classB(String type) { - Class<?> aClass = MappingUtils.loadClass(type); + Class<?> aClass = MappingUtils.loadClass(type, beanContainer); return classB(aClass); } diff --git a/core/src/main/java/org/dozer/loader/MappingsParser.java b/core/src/main/java/org/dozer/loader/MappingsParser.java index 575344303..c47ef6893 100644 --- a/core/src/main/java/org/dozer/loader/MappingsParser.java +++ b/core/src/main/java/org/dozer/loader/MappingsParser.java @@ -23,11 +23,14 @@ import org.dozer.classmap.ClassMappings; import org.dozer.classmap.Configuration; import org.dozer.classmap.MappingDirection; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.DozerField; import org.dozer.fieldmap.ExcludeFieldMap; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.GenericFieldMap; import org.dozer.fieldmap.MapFieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.DozerConstants; import org.dozer.util.MappingUtils; import org.dozer.util.ReflectionUtils; @@ -44,13 +47,14 @@ */ public final class MappingsParser { - private static final MappingsParser INSTANCE = new MappingsParser(); + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; - public static MappingsParser getInstance() { - return INSTANCE; - } - - private MappingsParser() { + public MappingsParser(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; } /** @@ -64,7 +68,7 @@ public ClassMappings processMappings(List<ClassMap> classMaps, Configuration glo if (globalConfiguration == null) { throw new IllegalArgumentException("Global configuration parameter cannot be null"); } - ClassMappings result = new ClassMappings(); + ClassMappings result = new ClassMappings(beanContainer); if (classMaps == null || classMaps.size() == 0) { return result; } @@ -91,7 +95,7 @@ public ClassMappings processMappings(List<ClassMap> classMaps, Configuration glo result.add(classMap.getSrcClassToMap(), classMap.getDestClassToMap(), classMap.getMapId(), classMap); // now create class map prime classMapPrime = new ClassMap(globalConfiguration); - MappingUtils.reverseFields(classMap, classMapPrime); + MappingUtils.reverseFields(classMap, classMapPrime, beanContainer); if (classMap.getFieldMaps() != null) { List<FieldMap> fms = classMap.getFieldMaps(); @@ -107,7 +111,7 @@ public ClassMappings processMappings(List<ClassMap> classMaps, Configuration glo if ( ( isSupportedMap(classMap.getDestClassToMap()) ^ isSupportedMap(classMap.getSrcClassToMap()) ) || ( isSupportedMap(fieldMap.getDestFieldType(classMap.getDestClassToMap())) ^ isSupportedMap(fieldMap.getSrcFieldType(classMap.getSrcClassToMap())) ) ) { - FieldMap fm = new MapFieldMap(fieldMap); + FieldMap fm = new MapFieldMap(fieldMap, beanContainer, destBeanCreator, propertyDescriptorFactory); classMap.removeFieldMapping(fieldMap); classMap.addFieldMapping(fm); fieldMap = fm; @@ -139,7 +143,7 @@ public ClassMappings processMappings(List<ClassMap> classMaps, Configuration glo // check to see if it is only an exclude one way if (fieldMapPrime instanceof ExcludeFieldMap && MappingDirection.ONE_WAY.equals(fieldMap.getType())) { // need to make a generic field map for the other direction - fieldMapPrime = new GenericFieldMap(classMapPrime); + fieldMapPrime = new GenericFieldMap(classMapPrime, beanContainer, destBeanCreator, propertyDescriptorFactory); } // reverse the fields MappingUtils.reverseFields(fieldMap, fieldMapPrime); @@ -153,7 +157,7 @@ public ClassMappings processMappings(List<ClassMap> classMaps, Configuration glo } } else { // if it is a one-way field map make the other field map excluded // make a prime field map - fieldMapPrime = new ExcludeFieldMap(classMapPrime); + fieldMapPrime = new ExcludeFieldMap(classMapPrime, beanContainer, destBeanCreator, propertyDescriptorFactory); MappingUtils.reverseFields(fieldMap, fieldMapPrime); MappingUtils.applyGlobalCopyByReference(globalConfiguration, fieldMap, classMap); } @@ -168,7 +172,7 @@ public ClassMappings processMappings(List<ClassMap> classMaps, Configuration glo MappingUtils.applyGlobalCopyByReference(globalConfiguration, oneWayFieldMap, classMap); // check to see if we need to exclude the map if (MappingDirection.ONE_WAY.equals(oneWayFieldMap.getType())) { - fieldMapPrime = new ExcludeFieldMap(classMapPrime); + fieldMapPrime = new ExcludeFieldMap(classMapPrime, beanContainer, destBeanCreator, propertyDescriptorFactory); MappingUtils.reverseFields(oneWayFieldMap, fieldMapPrime); classMapPrime.addFieldMapping(fieldMapPrime); } diff --git a/core/src/main/java/org/dozer/loader/api/BeanMappingBuilder.java b/core/src/main/java/org/dozer/loader/api/BeanMappingBuilder.java index d25f550b7..eb4251f3b 100644 --- a/core/src/main/java/org/dozer/loader/api/BeanMappingBuilder.java +++ b/core/src/main/java/org/dozer/loader/api/BeanMappingBuilder.java @@ -16,7 +16,10 @@ package org.dozer.loader.api; import org.dozer.classmap.MappingFileData; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.loader.DozerBuilder; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.DozerConstants; /** @@ -36,8 +39,8 @@ public BeanMappingBuilder() { * For internal use * @return mappings created with given builder */ - public MappingFileData build() { - dozerBuilder = new DozerBuilder(); + public MappingFileData build(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + dozerBuilder = new DozerBuilder(beanContainer, destBeanCreator, propertyDescriptorFactory); configure(); return dozerBuilder.build(); } diff --git a/core/src/main/java/org/dozer/loader/xml/DozerResolver.java b/core/src/main/java/org/dozer/loader/xml/DozerResolver.java index 422fef66a..fe36c19ef 100644 --- a/core/src/main/java/org/dozer/loader/xml/DozerResolver.java +++ b/core/src/main/java/org/dozer/loader/xml/DozerResolver.java @@ -17,7 +17,6 @@ import java.io.IOException; import java.net.HttpURLConnection; -import java.net.MalformedURLException; import java.net.URL; import org.xml.sax.EntityResolver; @@ -46,6 +45,12 @@ public class DozerResolver implements EntityResolver { private static final String VERSION_5_XSD = "http://dozer.sourceforge.net/schema/beanmapping.xsd"; private static final String VERSION_6_XSD = "http://dozermapper.github.io/schema/bean-mapping.xsd"; + private final BeanContainer beanContainer; + + public DozerResolver(BeanContainer beanContainer) { + this.beanContainer = beanContainer; + } + public InputSource resolveEntity(String publicId, String systemId) { InputSource source = null; @@ -93,7 +98,7 @@ private InputSource resolveFromClassPath(String publicId, String systemId) throw log.debug("Trying to locate [{}] in classpath", fileName); //Attempt to find via user defined class loader - DozerClassLoader classLoader = BeanContainer.getInstance().getClassLoader(); + DozerClassLoader classLoader = beanContainer.getClassLoader(); URL url = classLoader.loadResource(fileName); if (url == null) { //Attempt to find via dozer-schema jar diff --git a/core/src/main/java/org/dozer/loader/xml/MappingFileReader.java b/core/src/main/java/org/dozer/loader/xml/MappingFileReader.java index 1631d6ac4..bc7d17e23 100644 --- a/core/src/main/java/org/dozer/loader/xml/MappingFileReader.java +++ b/core/src/main/java/org/dozer/loader/xml/MappingFileReader.java @@ -39,13 +39,15 @@ public class MappingFileReader implements MappingsSource<URL> { private final Logger log = LoggerFactory.getLogger(MappingFileReader.class); private final MappingStreamReader streamReader; + private final BeanContainer beanContainer; - public MappingFileReader(XMLParserFactory parserFactory) { - streamReader = new MappingStreamReader(parserFactory); + public MappingFileReader(XMLParserFactory parserFactory, XMLParser xmlParser, BeanContainer beanContainer) { + this.streamReader = new MappingStreamReader(parserFactory, xmlParser); + this.beanContainer = beanContainer; } public MappingFileData read(String fileName) { - DozerClassLoader classLoader = BeanContainer.getInstance().getClassLoader(); + DozerClassLoader classLoader = beanContainer.getClassLoader(); URL url = classLoader.loadResource(fileName); return read(url); } diff --git a/core/src/main/java/org/dozer/loader/xml/MappingStreamReader.java b/core/src/main/java/org/dozer/loader/xml/MappingStreamReader.java index 2ef61404a..6fb48de19 100644 --- a/core/src/main/java/org/dozer/loader/xml/MappingStreamReader.java +++ b/core/src/main/java/org/dozer/loader/xml/MappingStreamReader.java @@ -41,9 +41,9 @@ public class MappingStreamReader implements MappingsSource<InputStream> { private final DocumentBuilder documentBuilder; private final MappingsSource<Document> parser; - public MappingStreamReader(XMLParserFactory parserFactory) { - this.documentBuilder = parserFactory.createParser(); - this.parser = new XMLParser(); + public MappingStreamReader(XMLParserFactory parserFactory, XMLParser xmlParser) { + this.documentBuilder = parserFactory.createParser(); + this.parser = xmlParser; } public MappingFileData read(InputStream xmlStream) { diff --git a/core/src/main/java/org/dozer/loader/xml/XMLParser.java b/core/src/main/java/org/dozer/loader/xml/XMLParser.java index b24c2b2d5..c74e12a41 100644 --- a/core/src/main/java/org/dozer/loader/xml/XMLParser.java +++ b/core/src/main/java/org/dozer/loader/xml/XMLParser.java @@ -26,8 +26,11 @@ import org.dozer.classmap.MappingFileData; import org.dozer.classmap.RelationshipType; import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.loader.DozerBuilder; import org.dozer.loader.MappingsSource; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -97,18 +100,22 @@ public class XMLParser implements MappingsSource<Document> { private static final String CUSTOM_CONVERTER_ID_ATTRIBUTE = "custom-converter-id"; private static final String CUSTOM_CONVERTER_PARAM_ATTRIBUTE = "custom-converter-param"; - private final ElementReader elementReader; + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; - public XMLParser() { - this.elementReader = BeanContainer.getInstance().getElementReader(); + public XMLParser(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; } private String getAttribute(Element element, String attribute) { - return elementReader.getAttribute(element, attribute); + return beanContainer.getElementReader().getAttribute(element, attribute); } private String getNodeValue(Element element) { - return elementReader.getNodeValue(element); + return beanContainer.getElementReader().getNodeValue(element); } private void debugElement(Element element) { @@ -122,7 +129,7 @@ private void debugElement(Element element) { * @return mapping container */ public MappingFileData read(Document document) { - DozerBuilder builder = new DozerBuilder(); + DozerBuilder builder = new DozerBuilder(beanContainer, destBeanCreator, propertyDescriptorFactory); Element theRoot = document.getDocumentElement(); NodeList nl = theRoot.getChildNodes(); @@ -442,7 +449,7 @@ private void parseVariables(Element element) { debugElement(ele); if (VARIABLE_ELEMENT.equals(ele.getNodeName())) { - ELEngine engine = BeanContainer.getInstance().getElEngine(); + ELEngine engine = beanContainer.getElEngine(); if (engine != null) { String name = getAttribute(ele, NAME_ATTRIBUTE); String value = getNodeValue(ele); diff --git a/core/src/main/java/org/dozer/loader/xml/XMLParserFactory.java b/core/src/main/java/org/dozer/loader/xml/XMLParserFactory.java index f74ae6d4e..e5a084bba 100644 --- a/core/src/main/java/org/dozer/loader/xml/XMLParserFactory.java +++ b/core/src/main/java/org/dozer/loader/xml/XMLParserFactory.java @@ -25,6 +25,8 @@ import org.xml.sax.helpers.DefaultHandler; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,13 +40,10 @@ public final class XMLParserFactory { private static final String SCHEMA_FEATURE = "http://apache.org/xml/features/validation/schema"; - private static final XMLParserFactory instance = new XMLParserFactory(); - - public static XMLParserFactory getInstance() { - return instance; - } + private final BeanContainer beanContainer; - private XMLParserFactory() { + public XMLParserFactory(BeanContainer beanContainer) { + this.beanContainer = beanContainer; } public DocumentBuilder createParser() { @@ -85,7 +84,7 @@ private DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfi private DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory) throws ParserConfigurationException { DocumentBuilder docBuilder = factory.newDocumentBuilder(); docBuilder.setErrorHandler(new DozerDefaultHandler()); - docBuilder.setEntityResolver(new DozerResolver()); + docBuilder.setEntityResolver(new DozerResolver(beanContainer)); return docBuilder; } diff --git a/core/src/main/java/org/dozer/osgi/Activator.java b/core/src/main/java/org/dozer/osgi/Activator.java index 1a672c2fb..bb15f4b93 100644 --- a/core/src/main/java/org/dozer/osgi/Activator.java +++ b/core/src/main/java/org/dozer/osgi/Activator.java @@ -15,8 +15,7 @@ */ package org.dozer.osgi; -import org.dozer.DozerInitializer; -import org.dozer.config.BeanContainer; +import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.slf4j.Logger; @@ -28,12 +27,15 @@ public final class Activator implements BundleActivator { private final Logger log = LoggerFactory.getLogger(Activator.class); + private static Bundle bundle; public void start(BundleContext bundleContext) throws Exception { log.info("Starting Dozer OSGi bundle"); - OSGiClassLoader classLoader = new OSGiClassLoader(bundleContext); - BeanContainer.getInstance().setClassLoader(classLoader); - DozerInitializer.getInstance().init(Activator.class.getClassLoader()); + bundle = bundleContext.getBundle(); + } + + public static Bundle getBundle() { + return bundle; } public void stop(BundleContext bundleContext) throws Exception { diff --git a/core/src/main/java/org/dozer/propertydescriptor/CustomGetSetPropertyDescriptor.java b/core/src/main/java/org/dozer/propertydescriptor/CustomGetSetPropertyDescriptor.java index 53ffc620b..4efd7828f 100644 --- a/core/src/main/java/org/dozer/propertydescriptor/CustomGetSetPropertyDescriptor.java +++ b/core/src/main/java/org/dozer/propertydescriptor/CustomGetSetPropertyDescriptor.java @@ -18,6 +18,8 @@ import java.lang.ref.SoftReference; import java.lang.reflect.Method; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.HintContainer; import org.dozer.util.MappingUtils; import org.dozer.util.ReflectionUtils; @@ -40,8 +42,9 @@ public class CustomGetSetPropertyDescriptor extends JavaBeanPropertyDescriptor { private SoftReference<Method> readMethod; public CustomGetSetPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, String customSetMethod, - String customGetMethod, HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { - super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + String customGetMethod, HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, + BeanContainer beanContainer, DestBeanCreator destBeanCreator) { + super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); this.customSetMethod = customSetMethod; this.customGetMethod = customGetMethod; } @@ -50,7 +53,7 @@ public CustomGetSetPropertyDescriptor(Class<?> clazz, String fieldName, boolean public Method getWriteMethod() throws NoSuchMethodException { if (writeMethod == null || writeMethod.get() == null) { if (customSetMethod != null && !MappingUtils.isDeepMapping(fieldName)) { - Method method = ReflectionUtils.findAMethod(clazz, customSetMethod); + Method method = ReflectionUtils.findAMethod(clazz, customSetMethod, beanContainer); writeMethod = new SoftReference<Method>(method); } else { return super.getWriteMethod(); @@ -63,7 +66,7 @@ public Method getWriteMethod() throws NoSuchMethodException { protected Method getReadMethod() throws NoSuchMethodException { if (readMethod == null || readMethod.get() == null) { if (customGetMethod != null) { - Method method = ReflectionUtils.findAMethod(clazz, customGetMethod); + Method method = ReflectionUtils.findAMethod(clazz, customGetMethod, beanContainer); readMethod = new SoftReference<Method>(method); } else { return super.getReadMethod(); diff --git a/core/src/main/java/org/dozer/propertydescriptor/FieldPropertyDescriptor.java b/core/src/main/java/org/dozer/propertydescriptor/FieldPropertyDescriptor.java index 65333d2af..6ff52706c 100644 --- a/core/src/main/java/org/dozer/propertydescriptor/FieldPropertyDescriptor.java +++ b/core/src/main/java/org/dozer/propertydescriptor/FieldPropertyDescriptor.java @@ -17,7 +17,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Type; - import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.HintContainer; @@ -37,10 +36,13 @@ public class FieldPropertyDescriptor extends AbstractPropertyDescriptor implements DozerPropertyDescriptor { private final DozerPropertyDescriptor[] descriptorChain; + private final DestBeanCreator destBeanCreator; public FieldPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, - HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { + HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, + DestBeanCreator destBeanCreator) { super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + this.destBeanCreator = destBeanCreator; String[] tokens = fieldName.split(DozerConstants.DEEP_FIELD_DELIMITER_REGEXP); descriptorChain = new DozerPropertyDescriptor[tokens.length]; @@ -82,7 +84,7 @@ public void setPropertyValue(Object bean, Object value, FieldMap fieldMap) { if (i != descriptorChain.length - 1) { Object currentValue = descriptor.getPropertyValue(intermediateResult); if (currentValue == null) { - currentValue = DestBeanCreator.create(descriptor.getPropertyType()); + currentValue = destBeanCreator.create(descriptor.getPropertyType()); descriptor.setPropertyValue(intermediateResult, currentValue, fieldMap); } intermediateResult = currentValue; diff --git a/core/src/main/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptor.java b/core/src/main/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptor.java index 275ab6b18..13311c862 100644 --- a/core/src/main/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptor.java +++ b/core/src/main/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptor.java @@ -21,6 +21,7 @@ import java.util.Collection; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.factory.BeanCreationDirective; import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; @@ -48,10 +49,15 @@ public abstract class GetterSetterPropertyDescriptor extends AbstractPropertyDes private final Logger log = LoggerFactory.getLogger(GetterSetterPropertyDescriptor.class); private Class<?> propertyType; + protected final BeanContainer beanContainer; + protected final DestBeanCreator destBeanCreator; public GetterSetterPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, - HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { + HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, + BeanContainer beanContainer, DestBeanCreator destBeanCreator) { super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; } protected abstract Method getWriteMethod() throws NoSuchMethodException; @@ -166,7 +172,7 @@ protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, } Object o = null; if (clazz.isArray()) { - o = MappingUtils.prepareIndexedCollection(clazz, null, DestBeanCreator.create(clazz.getComponentType()), + o = MappingUtils.prepareIndexedCollection(clazz, null, destBeanCreator.create(clazz.getComponentType()), hierarchyElement.getIndex()); } else if (Collection.class.isAssignableFrom(clazz)) { @@ -179,15 +185,15 @@ protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, hintIndex += 1; } - o = MappingUtils.prepareIndexedCollection(clazz, null, DestBeanCreator.create(collectionEntryType), hierarchyElement + o = MappingUtils.prepareIndexedCollection(clazz, null, destBeanCreator.create(collectionEntryType), hierarchyElement .getIndex()); } else { try { - o = DestBeanCreator.create(clazz); + o = destBeanCreator.create(clazz); } catch (Exception e) { //lets see if they have a factory we can try as a last ditch. If not...throw the exception: if (fieldMap.getClassMap().getDestClassBeanFactory() != null) { - o = DestBeanCreator.create(new BeanCreationDirective(null, fieldMap.getClassMap().getSrcClassToMap(), clazz, clazz, fieldMap.getClassMap() + o = destBeanCreator.create(new BeanCreationDirective(null, fieldMap.getClassMap().getSrcClassToMap(), clazz, clazz, fieldMap.getClassMap() .getDestClassBeanFactory(), fieldMap.getClassMap().getDestClassBeanFactoryId(), null)); } else { MappingUtils.throwMappingException(e); @@ -227,7 +233,7 @@ protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, } - value = MappingUtils.prepareIndexedCollection(pd.getPropertyType(), value, DestBeanCreator.create(collectionEntryType), hierarchyElement.getIndex()); + value = MappingUtils.prepareIndexedCollection(pd.getPropertyType(), value, destBeanCreator.create(collectionEntryType), hierarchyElement.getIndex()); //value = MappingUtils.prepareIndexedCollection(pd.getPropertyType(), value, DestBeanCreator.create(collectionEntryType), hierarchyElement.getIndex()); ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[]{value}); } @@ -259,7 +265,7 @@ protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, method = pd.getWriteMethod(); } else { try { - method = ReflectionUtils.findAMethod(parentObj.getClass(), getSetMethodName()); + method = ReflectionUtils.findAMethod(parentObj.getClass(), getSetMethodName(), beanContainer); } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } diff --git a/core/src/main/java/org/dozer/propertydescriptor/JavaBeanPropertyDescriptor.java b/core/src/main/java/org/dozer/propertydescriptor/JavaBeanPropertyDescriptor.java index ba84447f8..f98426949 100644 --- a/core/src/main/java/org/dozer/propertydescriptor/JavaBeanPropertyDescriptor.java +++ b/core/src/main/java/org/dozer/propertydescriptor/JavaBeanPropertyDescriptor.java @@ -19,6 +19,9 @@ import java.lang.reflect.Method; import org.apache.commons.beanutils.PropertyUtils; + +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.HintContainer; import org.dozer.util.MappingUtils; import org.dozer.util.ReflectionUtils; @@ -37,8 +40,9 @@ public class JavaBeanPropertyDescriptor extends GetterSetterPropertyDescriptor { private boolean propertyDescriptorsRefreshed; public JavaBeanPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, - HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { - super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, + BeanContainer beanContainer, DestBeanCreator destBeanCreator) { + super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); } @Override diff --git a/core/src/main/java/org/dozer/propertydescriptor/MapPropertyDescriptor.java b/core/src/main/java/org/dozer/propertydescriptor/MapPropertyDescriptor.java index bff221555..cac289b3f 100644 --- a/core/src/main/java/org/dozer/propertydescriptor/MapPropertyDescriptor.java +++ b/core/src/main/java/org/dozer/propertydescriptor/MapPropertyDescriptor.java @@ -19,6 +19,8 @@ import java.lang.reflect.Method; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.HintContainer; import org.dozer.util.MappingUtils; @@ -50,8 +52,9 @@ public class MapPropertyDescriptor extends GetterSetterPropertyDescriptor { private SoftReference<Method> readMethod; public MapPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, String setMethod, String getMethod, - String key, HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { - super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + String key, HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, + BeanContainer beanContainer, DestBeanCreator destBeanCreator) { + super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); this.setMethodName = setMethod; this.getMethodName = getMethod; this.key = key; diff --git a/core/src/main/java/org/dozer/propertydescriptor/PropertyDescriptorFactory.java b/core/src/main/java/org/dozer/propertydescriptor/PropertyDescriptorFactory.java index 318af201e..c1d3ef40a 100644 --- a/core/src/main/java/org/dozer/propertydescriptor/PropertyDescriptorFactory.java +++ b/core/src/main/java/org/dozer/propertydescriptor/PropertyDescriptorFactory.java @@ -16,10 +16,13 @@ package org.dozer.propertydescriptor; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.lang3.StringUtils; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.HintContainer; import org.dozer.util.DozerConstants; import org.dozer.util.MappingUtils; @@ -32,18 +35,19 @@ */ public final class PropertyDescriptorFactory { - private static final List<PropertyDescriptorCreationStrategy> pluggedDescriptorCreationStrategies = + private final List<PropertyDescriptorCreationStrategy> pluggedDescriptorCreationStrategies = new ArrayList<PropertyDescriptorCreationStrategy>(); - private PropertyDescriptorFactory() { + public PropertyDescriptorFactory() { } - public static DozerPropertyDescriptor getPropertyDescriptor(Class<?> clazz, String theGetMethod, String theSetMethod, - String mapGetMethod, String mapSetMethod, boolean isAccessible, - boolean isIndexed, int index, String name, String key, boolean isSelfReferencing, - String oppositeFieldName, HintContainer srcDeepIndexHintContainer, - HintContainer destDeepIndexHintContainer, String beanFactory) { + public DozerPropertyDescriptor getPropertyDescriptor(Class<?> clazz, String theGetMethod, String theSetMethod, + String mapGetMethod, String mapSetMethod, boolean isAccessible, + boolean isIndexed, int index, String name, String key, boolean isSelfReferencing, + String oppositeFieldName, HintContainer srcDeepIndexHintContainer, + HintContainer destDeepIndexHintContainer, String beanFactory, + BeanContainer beanContainer, DestBeanCreator destBeanCreator) { DozerPropertyDescriptor desc = null; // Raw Map types or custom map-get-method/set specified @@ -53,13 +57,13 @@ public static DozerPropertyDescriptor getPropertyDescriptor(Class<?> clazz, Stri // If no mapSetMethod is defined, default to "put" String setMethod = StringUtils.isBlank(mapSetMethod) ? "put" : mapSetMethod; - + // If no mapGetMethod is defined, default to "get". String getMethod = StringUtils.isBlank(mapGetMethod) ? "get" : mapGetMethod; desc = new MapPropertyDescriptor(clazz, name, isIndexed, index, setMethod, getMethod, key != null ? key : oppositeFieldName, - srcDeepIndexHintContainer, destDeepIndexHintContainer); + srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); // Copy by reference(Not mapped backed properties which also use 'this' // identifier for a different purpose) @@ -68,16 +72,16 @@ public static DozerPropertyDescriptor getPropertyDescriptor(Class<?> clazz, Stri // Access field directly and bypass getter/setters } else if (isAccessible) { - desc = new FieldPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + desc = new FieldPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer, destBeanCreator); // Custom get-method/set specified } else if (theSetMethod != null || theGetMethod != null) { desc = new CustomGetSetPropertyDescriptor(clazz, name, isIndexed, index, theSetMethod, theGetMethod, - srcDeepIndexHintContainer, destDeepIndexHintContainer); + srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); // If this object is an XML Bean - then use the XmlBeanPropertyDescriptor } else if (beanFactory != null && beanFactory.equals(DozerConstants.XML_BEAN_FACTORY)) { - desc = new XmlBeanPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + desc = new XmlBeanPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); } if (desc != null) { @@ -97,13 +101,13 @@ public static DozerPropertyDescriptor getPropertyDescriptor(Class<?> clazz, Stri if (desc == null) { // Everything else. It must be a normal bean with normal custom get/set methods - desc = new JavaBeanPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + desc = new JavaBeanPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); } return desc; } - public static void addPluggedPropertyDescriptorCreationStrategy(PropertyDescriptorCreationStrategy strategy) { - pluggedDescriptorCreationStrategies.add(strategy); + public void addPluggedPropertyDescriptorCreationStrategies(Collection<PropertyDescriptorCreationStrategy> strategies) { + pluggedDescriptorCreationStrategies.addAll(strategies); } } diff --git a/core/src/main/java/org/dozer/propertydescriptor/XmlBeanPropertyDescriptor.java b/core/src/main/java/org/dozer/propertydescriptor/XmlBeanPropertyDescriptor.java index 4aa97819e..c5aa187d2 100644 --- a/core/src/main/java/org/dozer/propertydescriptor/XmlBeanPropertyDescriptor.java +++ b/core/src/main/java/org/dozer/propertydescriptor/XmlBeanPropertyDescriptor.java @@ -18,6 +18,8 @@ /** * @author Stuntmunkee */ +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.HintContainer; @@ -32,13 +34,13 @@ public class XmlBeanPropertyDescriptor implements DozerPropertyDescriptor { private final JavaBeanPropertyDescriptor isSetFieldPropertyDescriptor; public XmlBeanPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, - HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { + HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, BeanContainer beanContainer, DestBeanCreator destBeanCreator) { fieldPropertyDescriptor = new JavaBeanPropertyDescriptor(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, - destDeepIndexHintContainer); + destDeepIndexHintContainer, beanContainer, destBeanCreator); isSetFieldPropertyDescriptor = new JavaBeanPropertyDescriptor(clazz, getIsSetFieldName(fieldName), isIndexed, index, - srcDeepIndexHintContainer, destDeepIndexHintContainer); + srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator); } public Class<?> getPropertyType() { diff --git a/core/src/main/java/org/dozer/stats/GlobalStatistics.java b/core/src/main/java/org/dozer/stats/GlobalStatistics.java deleted file mode 100644 index c688b760c..000000000 --- a/core/src/main/java/org/dozer/stats/GlobalStatistics.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2005-2017 Dozer Project - * - * 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.dozer.stats; - -/** - * Internal singleton class that holds global statistics. Only intended for internal use. - * - * @author tierney.matt - */ -public final class GlobalStatistics { - private static GlobalStatistics singleton = new GlobalStatistics(); - - private final StatisticsManager statsMgr; - - private GlobalStatistics() { - statsMgr = new StatisticsManagerImpl(); - } - - public static GlobalStatistics getInstance() { - return singleton; - } - - public StatisticsManager getStatsMgr() { - return statsMgr; - } -} diff --git a/core/src/main/java/org/dozer/stats/StatisticsManagerImpl.java b/core/src/main/java/org/dozer/stats/StatisticsManagerImpl.java index 6dec75ccc..d544205a8 100644 --- a/core/src/main/java/org/dozer/stats/StatisticsManagerImpl.java +++ b/core/src/main/java/org/dozer/stats/StatisticsManagerImpl.java @@ -36,7 +36,13 @@ public final class StatisticsManagerImpl implements StatisticsManager { private final Logger log = LoggerFactory.getLogger(StatisticsManagerImpl.class); private final ConcurrentMap<StatisticType, Statistic> statisticsMap = new ConcurrentHashMap<StatisticType, Statistic>(); - private boolean isStatisticsEnabled = GlobalSettings.getInstance().isStatisticsEnabled(); + private final GlobalSettings globalSettings; + private boolean isStatisticsEnabled; + + public StatisticsManagerImpl(GlobalSettings globalSettings) { + this.isStatisticsEnabled = globalSettings.isStatisticsEnabled(); + this.globalSettings = globalSettings; + } public void clearAll() { statisticsMap.clear(); @@ -58,7 +64,7 @@ public boolean isStatisticsEnabled() { public void setStatisticsEnabled(boolean statisticsEnabled) { this.isStatisticsEnabled = statisticsEnabled; - GlobalSettings.getInstance().setStatisticsEnabled(statisticsEnabled); + globalSettings.setStatisticsEnabled(statisticsEnabled); } public Set<StatisticType> getStatisticTypes() { diff --git a/core/src/main/java/org/dozer/util/DeepHierarchyUtils.java b/core/src/main/java/org/dozer/util/DeepHierarchyUtils.java index f3b34efaa..fd89b2233 100644 --- a/core/src/main/java/org/dozer/util/DeepHierarchyUtils.java +++ b/core/src/main/java/org/dozer/util/DeepHierarchyUtils.java @@ -18,6 +18,8 @@ import java.util.Collection; import java.util.StringTokenizer; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.HintContainer; import org.dozer.propertydescriptor.DozerPropertyDescriptor; import org.dozer.propertydescriptor.PropertyDescriptorFactory; @@ -32,11 +34,13 @@ private DeepHierarchyUtils() { } // Copy-paste from GetterSetterPropertyDescriptor - public static Object getDeepFieldValue(Object srcObj, String fieldName, boolean isIndexed, int index, HintContainer srcDeepIndexHintContainer) { + public static Object getDeepFieldValue(Object srcObj, String fieldName, boolean isIndexed, int index, HintContainer srcDeepIndexHintContainer, + BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { // follow deep field hierarchy. If any values are null along the way, then return null Object parentObj = srcObj; Object hierarchyValue = parentObj; - DozerPropertyDescriptor[] hierarchy = getDeepFieldHierarchy(srcObj.getClass(), fieldName, srcDeepIndexHintContainer); + DozerPropertyDescriptor[] hierarchy = getDeepFieldHierarchy(srcObj.getClass(), fieldName, srcDeepIndexHintContainer, beanContainer, + destBeanCreator, propertyDescriptorFactory); for (DozerPropertyDescriptor hierarchyElement : hierarchy) { hierarchyValue = hierarchyElement.getPropertyValue(parentObj); @@ -53,19 +57,22 @@ public static Object getDeepFieldValue(Object srcObj, String fieldName, boolean return hierarchyValue; } - public static Class<?> getDeepFieldType(Class<?> clazz, String fieldName, HintContainer deepIndexHintContainer) { + public static Class<?> getDeepFieldType(Class<?> clazz, String fieldName, HintContainer deepIndexHintContainer, BeanContainer beanContainer, + DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { // follow deep field hierarchy. If any values are null along the way, then return null - DozerPropertyDescriptor[] hierarchy = getDeepFieldHierarchy(clazz, fieldName, deepIndexHintContainer); + DozerPropertyDescriptor[] hierarchy = getDeepFieldHierarchy(clazz, fieldName, deepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); return hierarchy[hierarchy.length - 1].getPropertyType(); } - public static Class<?> getDeepGenericType(Class<?> clazz, String fieldName, HintContainer deepIndexHintContainer) { + public static Class<?> getDeepGenericType(Class<?> clazz, String fieldName, HintContainer deepIndexHintContainer, BeanContainer beanContainer, + DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { // follow deep field hierarchy. If any values are null along the way, then return null - DozerPropertyDescriptor[] hierarchy = getDeepFieldHierarchy(clazz, fieldName, deepIndexHintContainer); + DozerPropertyDescriptor[] hierarchy = getDeepFieldHierarchy(clazz, fieldName, deepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); return hierarchy[hierarchy.length - 1].genericType(); } - private static DozerPropertyDescriptor[] getDeepFieldHierarchy(Class<?> parentClass, String field, HintContainer deepIndexHintContainer) { + private static DozerPropertyDescriptor[] getDeepFieldHierarchy(Class<?> parentClass, String field, HintContainer deepIndexHintContainer, + BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { if (!MappingUtils.isDeepMapping(field)) { MappingUtils.throwMappingException("Field does not contain deep field delimiter"); } @@ -85,10 +92,10 @@ private static DozerPropertyDescriptor[] getDeepFieldHierarchy(Class<?> parentCl collectionIndex = Integer.parseInt(aFieldName.substring(aFieldName.indexOf("[") + 1, aFieldName.indexOf("]"))); } - DozerPropertyDescriptor propDescriptor = PropertyDescriptorFactory.getPropertyDescriptor(latestClass, null, null, null, null, false, + DozerPropertyDescriptor propDescriptor = propertyDescriptorFactory.getPropertyDescriptor(latestClass, null, null, null, null, false, collectionIndex > -1, collectionIndex, theFieldName, null, false, null, null, null, - null); //we can pass null as a hint container - if genericType return null - we will use hintContainer in the underlying if + null, beanContainer, destBeanCreator); //we can pass null as a hint container - if genericType return null - we will use hintContainer in the underlying if if (propDescriptor == null) { MappingUtils.throwMappingException("Exception occurred determining deep field hierarchy for Class --> " diff --git a/core/src/main/java/org/dozer/util/MappingUtils.java b/core/src/main/java/org/dozer/util/MappingUtils.java index ec87ec891..302117b7e 100755 --- a/core/src/main/java/org/dozer/util/MappingUtils.java +++ b/core/src/main/java/org/dozer/util/MappingUtils.java @@ -162,16 +162,16 @@ public static void reverseFields(FieldMap source, FieldMap reversed) { reversed.setDestDeepIndexHintContainer(source.getSrcDeepIndexHintContainer()); } - public static void reverseFields(ClassMap source, ClassMap destination) { + public static void reverseFields(ClassMap source, ClassMap destination, BeanContainer beanContainer) { // reverse the fields destination.setSrcClass(new DozerClass(source.getDestClassName(), source.getDestClassToMap(), source.getDestClassBeanFactory(), source.getDestClassBeanFactoryId(), source.getDestClassMapGetMethod(), source.getDestClassMapSetMethod(), source.getDestClass().getCreateMethod(), - source.isDestMapNull(), source.isDestMapEmptyString(), source.getDestClass().isAccessible())); + source.isDestMapNull(), source.isDestMapEmptyString(), source.getDestClass().isAccessible(), beanContainer)); destination.setDestClass(new DozerClass(source.getSrcClassName(), source.getSrcClassToMap(), source.getSrcClassBeanFactory(), source.getSrcClassBeanFactoryId(), source.getSrcClassMapGetMethod(), source.getSrcClassMapSetMethod(), source.getSrcClass().getCreateMethod(), - source.isSrcMapNull(), source.isSrcMapEmptyString(), source.getSrcClass().isAccessible())); + source.isSrcMapNull(), source.isSrcMapEmptyString(), source.getSrcClass().isAccessible(), beanContainer)); destination.setType(source.getType()); destination.setWildcard(source.isWildcard()); destination.setTrimStrings(source.isTrimStrings()); @@ -218,27 +218,23 @@ public static void applyGlobalCopyByReference(Configuration globalConfig, FieldM } } - public static Class<?> loadClass(String name) { - BeanContainer container = BeanContainer.getInstance(); - DozerClassLoader loader = container.getClassLoader(); + public static Class<?> loadClass(String name, BeanContainer beanContainer) { + DozerClassLoader loader = beanContainer.getClassLoader(); return loader.loadClass(name); } - public static Class<?> getRealClass(Class<?> clazz) { - BeanContainer container = BeanContainer.getInstance(); - DozerProxyResolver proxyResolver = container.getProxyResolver(); + public static Class<?> getRealClass(Class<?> clazz, BeanContainer beanContainer) { + DozerProxyResolver proxyResolver = beanContainer.getProxyResolver(); return proxyResolver.getRealClass(clazz); } - public static <T> T deProxy(T object) { - BeanContainer container = BeanContainer.getInstance(); - DozerProxyResolver proxyResolver = container.getProxyResolver(); + public static <T> T deProxy(T object, BeanContainer beanContainer) { + DozerProxyResolver proxyResolver = beanContainer.getProxyResolver(); return proxyResolver.unenhanceObject(object); } - public static boolean isProxy(Class<?> clazz) { - BeanContainer container = BeanContainer.getInstance(); - DozerProxyResolver proxyResolver = container.getProxyResolver(); + public static boolean isProxy(Class<?> clazz, BeanContainer beanContainer) { + DozerProxyResolver proxyResolver = beanContainer.getProxyResolver(); return proxyResolver.isProxy(clazz); } @@ -344,12 +340,12 @@ public static boolean isEnumType(Class<?> srcFieldClass, Class<?> destFieldType) return isEnumType(srcFieldClass) && isEnumType(destFieldType); } - public static List<Class<?>> getSuperClassesAndInterfaces(Class<?> srcClass) { + public static List<Class<?>> getSuperClassesAndInterfaces(Class<?> srcClass, BeanContainer beanContainer) { List<Class<?>> superClasses = new ArrayList<Class<?>>(); - Class<?> realClass = getRealClass(srcClass); + Class<?> realClass = getRealClass(srcClass, beanContainer); // Add all super classes first - Class<?> superClass = getRealClass(realClass).getSuperclass(); + Class<?> superClass = getRealClass(realClass, beanContainer).getSuperclass(); while (!isBaseClass(superClass)) { superClasses.add(superClass); superClass = superClass.getSuperclass(); @@ -360,9 +356,9 @@ public static List<Class<?>> getSuperClassesAndInterfaces(Class<?> srcClass) { // Linked hash set so duplicated are not added but insertion order is kept LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<Class<?>>(); - interfaces.addAll(getInterfaceHierarchy(realClass)); + interfaces.addAll(getInterfaceHierarchy(realClass, beanContainer)); for (Class<?> clazz : superClasses) { - interfaces.addAll(getInterfaceHierarchy(clazz)); + interfaces.addAll(getInterfaceHierarchy(clazz, beanContainer)); } superClasses.addAll(interfaces); @@ -370,9 +366,9 @@ public static List<Class<?>> getSuperClassesAndInterfaces(Class<?> srcClass) { } @SuppressWarnings("unchecked") - public static List<Class<?>> getInterfaceHierarchy(Class<?> srcClass) { + public static List<Class<?>> getInterfaceHierarchy(Class<?> srcClass, BeanContainer beanContainer) { final List<Class<?>> result = new LinkedList<Class<?>>(); - Class<?> realClass = getRealClass(srcClass); + Class<?> realClass = getRealClass(srcClass, beanContainer); final LinkedList<Class> interfacesToProcess = new LinkedList<Class>(); diff --git a/core/src/main/java/org/dozer/util/MappingValidator.java b/core/src/main/java/org/dozer/util/MappingValidator.java index 3af3c9614..558b25260 100644 --- a/core/src/main/java/org/dozer/util/MappingValidator.java +++ b/core/src/main/java/org/dozer/util/MappingValidator.java @@ -52,15 +52,15 @@ public static void validateMappingRequest(Object srcObj, Class<?> destClass) { } } - public static URL validateURL(String fileName) { - DozerClassLoader classLoader = BeanContainer.getInstance().getClassLoader(); + public static URL validateURL(String fileName, BeanContainer beanContainer) { + DozerClassLoader classLoader = beanContainer.getClassLoader(); if (fileName == null) { MappingUtils.throwMappingException("File name is null"); } URL url = classLoader.loadResource(fileName); if (url == null) { - DozerClassLoader tccl = BeanContainer.getInstance().getTCCL(); + DozerClassLoader tccl = beanContainer.getTCCL(); url = tccl.loadResource(fileName); if (url == null) { MappingUtils.throwMappingException("Unable to locate dozer mapping file [" + fileName + "] in the classpath!"); diff --git a/core/src/main/java/org/dozer/util/ReflectionUtils.java b/core/src/main/java/org/dozer/util/ReflectionUtils.java index d192c21ad..3021ab06b 100644 --- a/core/src/main/java/org/dozer/util/ReflectionUtils.java +++ b/core/src/main/java/org/dozer/util/ReflectionUtils.java @@ -31,6 +31,7 @@ import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.fieldmap.HintContainer; import org.dozer.propertydescriptor.DeepHierarchyElement; @@ -230,7 +231,7 @@ private static Method findMethod(Class<?> clazz, String methodName) { * @return found method * @throws NoSuchMethodException if no method found */ - public static Method findAMethod(Class<?> clazz, String methodName) throws NoSuchMethodException { + public static Method findAMethod(Class<?> clazz, String methodName, BeanContainer beanContainer) throws NoSuchMethodException { StringTokenizer tokenizer = new StringTokenizer(methodName, "("); String m = tokenizer.nextToken(); Method result; @@ -238,7 +239,7 @@ public static Method findAMethod(Class<?> clazz, String methodName) throws NoSuc if (tokenizer.hasMoreElements()) { StringTokenizer tokens = new StringTokenizer(tokenizer.nextToken(), ")"); String params = tokens.hasMoreTokens() ? tokens.nextToken() : null; - result = findMethodWithParam(clazz, m, params); + result = findMethodWithParam(clazz, m, params, beanContainer); } else { result = findMethod(clazz, methodName); } @@ -248,14 +249,14 @@ public static Method findAMethod(Class<?> clazz, String methodName) throws NoSuc return result; } - private static Method findMethodWithParam(Class<?> parentDestClass, String methodName, String params) + private static Method findMethodWithParam(Class<?> parentDestClass, String methodName, String params, BeanContainer beanContainer) throws NoSuchMethodException { List<Class<?>> list = new ArrayList<Class<?>>(); if (params != null) { StringTokenizer tokenizer = new StringTokenizer(params, ","); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); - list.add(MappingUtils.loadClass(token)); + list.add(MappingUtils.loadClass(token, beanContainer)); } } return getMethod(parentDestClass, methodName, list.toArray(new Class[list.size()])); diff --git a/core/src/main/java/org/dozer/util/RuntimeUtils.java b/core/src/main/java/org/dozer/util/RuntimeUtils.java new file mode 100644 index 000000000..ac988ef5e --- /dev/null +++ b/core/src/main/java/org/dozer/util/RuntimeUtils.java @@ -0,0 +1,50 @@ +/* + * Copyright 2005-2017 Dozer Project + * + * 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.dozer.util; + +import org.dozer.osgi.Activator; + +/** + * Utility class to provide various information about runtime in which Dozer is executed. + */ +public final class RuntimeUtils { + + private RuntimeUtils() { + } + + private static Boolean isOSGi; + + /** + * Returns {@code true} if Dozer is executed in OSGi container. + * + * @return if Dozer is in OSGi container. + */ + public static boolean isOSGi() { + if (isOSGi == null) { + try { + // first verify that framework classes are available (otherwise loading of Activator will fail) + Class.forName("org.osgi.framework.Bundle"); + + // then verify that bundle is started (client code could add framework classes into classpath) + isOSGi = Activator.getBundle() != null; + + } catch (ClassNotFoundException e) { + isOSGi = Boolean.FALSE; + } + } + return isOSGi; + } +} diff --git a/core/src/test/java/org/dozer/DozerBeanMapperTest.java b/core/src/test/java/org/dozer/DozerBeanMapperTest.java index ede549205..3309e3847 100644 --- a/core/src/test/java/org/dozer/DozerBeanMapperTest.java +++ b/core/src/test/java/org/dozer/DozerBeanMapperTest.java @@ -18,6 +18,7 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -28,7 +29,21 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.beanutils.PropertyUtils; + +import org.dozer.builder.DestBeanBuilderCreator; +import org.dozer.classmap.ClassMapBuilder; +import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.config.BeanContainer; +import org.dozer.config.GlobalSettings; +import org.dozer.factory.DestBeanCreator; +import org.dozer.loader.CustomMappingsLoader; +import org.dozer.loader.MappingsParser; import org.dozer.loader.api.BeanMappingBuilder; +import org.dozer.loader.xml.XMLParser; +import org.dozer.loader.xml.XMLParserFactory; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; +import org.dozer.stats.StatisticsManagerImpl; +import org.dozer.util.DefaultClassLoader; import org.dozer.vo.TestObject; import org.dozer.vo.generics.deepindex.TestObjectPrime; import org.junit.After; @@ -50,7 +65,7 @@ public class DozerBeanMapperTest extends Assert { @Before public void setUp() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); exceptions = new ArrayList<Throwable>(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { @@ -93,7 +108,7 @@ public Object call() throws Exception { @Test public void shouldBeThreadSafe() throws Exception { - mapper.setMappingFiles(Arrays.asList("dozerBeanMapping.xml")); + mapper.setMappingFiles(Arrays.asList("testDozerBeanMapping.xml")); final CountDownLatch latch = new CountDownLatch(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { @@ -115,6 +130,23 @@ public void run() { class CallTrackingMapper extends DozerBeanMapper { AtomicInteger calls = new AtomicInteger(0); + CallTrackingMapper() { + // todo this is awful, but will be removed when DozerBeanMapper is immutable (#400) + super(Collections.emptyList(), + new GlobalSettings(new DefaultClassLoader(DozerBeanMapperTest.class.getClassLoader())), + new CustomMappingsLoader( + new MappingsParser(new BeanContainer(), new DestBeanCreator(new BeanContainer()), new PropertyDescriptorFactory()), + new ClassMapBuilder(new BeanContainer(), new DestBeanCreator(new BeanContainer()), + new BeanMappingGenerator(new BeanContainer(), new DestBeanCreator(new BeanContainer()), new PropertyDescriptorFactory()), new PropertyDescriptorFactory()), + new BeanContainer()), + new XMLParserFactory(new BeanContainer()), + new StatisticsManagerImpl(new GlobalSettings(new DefaultClassLoader(DozerBeanMapperTest.class.getClassLoader()))), + new DozerInitializer(), new BeanContainer(), + new XMLParser(new BeanContainer(), new DestBeanCreator(new BeanContainer()), new PropertyDescriptorFactory()), new DestBeanCreator(new BeanContainer()), + new DestBeanBuilderCreator(), + new BeanMappingGenerator(new BeanContainer(), new DestBeanCreator(new BeanContainer()), new PropertyDescriptorFactory()), new PropertyDescriptorFactory()); + } + @Override void loadCustomMappings() { calls.incrementAndGet(); diff --git a/core/src/test/java/org/dozer/DozerInitializerTest.java b/core/src/test/java/org/dozer/DozerInitializerTest.java index 330546456..b0676a151 100644 --- a/core/src/test/java/org/dozer/DozerInitializerTest.java +++ b/core/src/test/java/org/dozer/DozerInitializerTest.java @@ -15,52 +15,75 @@ */ package org.dozer; +import org.dozer.builder.DestBeanBuilderCreator; +import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.config.BeanContainer; import org.dozer.config.GlobalSettings; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; +import org.dozer.stats.StatisticsManager; +import org.dozer.stats.StatisticsManagerImpl; +import org.dozer.util.DefaultClassLoader; import org.dozer.util.DozerConstants; + import org.junit.After; import org.junit.Before; import org.junit.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DozerInitializerTest extends AbstractDozerTest { + private GlobalSettings globalSettings; + private DozerInitializer instance; + private StatisticsManager statisticsManager; + private BeanContainer beanContainer; + private DestBeanBuilderCreator destBeanBuilderCreator; + private BeanMappingGenerator beanMappingGenerator; + private PropertyDescriptorFactory propertyDescriptorFactory; + private DestBeanCreator destBeanCreator; @Before public void setUp() throws Exception { - instance = DozerInitializer.getInstance(); - instance.destroy(); + beanContainer = new BeanContainer(); + globalSettings = new GlobalSettings(new DefaultClassLoader(DozerInitializerTest.class.getClassLoader())); + statisticsManager = new StatisticsManagerImpl(globalSettings); + destBeanBuilderCreator = new DestBeanBuilderCreator(); + propertyDescriptorFactory = new PropertyDescriptorFactory(); + destBeanCreator = new DestBeanCreator(beanContainer); + beanMappingGenerator = new BeanMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory); + instance = new DozerInitializer(); + instance.destroy(globalSettings); } @After public void tearDown() throws Exception { - instance.destroy(); + instance.destroy(globalSettings); } @Test public void testIsInitialized() { assertFalse(instance.isInitialized()); - instance.init(); + instance.init(globalSettings, statisticsManager, beanContainer, destBeanBuilderCreator, beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); assertTrue(instance.isInitialized()); - instance.destroy(); + instance.destroy(globalSettings); assertFalse(instance.isInitialized()); } @Test public void testDoubleCalls() { - instance.destroy(); + instance.destroy(globalSettings); assertFalse(instance.isInitialized()); - instance.init(); - instance.init(); + instance.init(globalSettings, statisticsManager, beanContainer, destBeanBuilderCreator, beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); + instance.init(globalSettings, statisticsManager, beanContainer, destBeanBuilderCreator, beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); assertTrue(instance.isInitialized()); - instance.destroy(); - instance.destroy(); + instance.destroy(globalSettings); + instance.destroy(globalSettings); assertFalse(instance.isInitialized()); } @@ -70,7 +93,8 @@ public void testBeanIsMissing() { when(settings.getClassLoaderName()).thenReturn(DozerConstants.DEFAULT_CLASS_LOADER_BEAN); when(settings.getProxyResolverName()).thenReturn("no.such.class.Found"); - instance.initialize(settings, getClass().getClassLoader()); + instance.initialize(settings, getClass().getClassLoader(), statisticsManager, beanContainer, destBeanBuilderCreator, + beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); fail(); } @@ -80,7 +104,8 @@ public void testBeanIsNotAssignable() { when(settings.getClassLoaderName()).thenReturn("java.lang.String"); when(settings.getProxyResolverName()).thenReturn(DozerConstants.DEFAULT_PROXY_RESOLVER_BEAN); - instance.initialize(settings, getClass().getClassLoader()); + instance.initialize(settings, getClass().getClassLoader(), statisticsManager, beanContainer, destBeanBuilderCreator, + beanMappingGenerator, propertyDescriptorFactory, destBeanCreator); fail(); } } diff --git a/core/src/test/java/org/dozer/MappingProcessorArrayTest.java b/core/src/test/java/org/dozer/MappingProcessorArrayTest.java index f2c8ac5ad..66634d7a5 100644 --- a/core/src/test/java/org/dozer/MappingProcessorArrayTest.java +++ b/core/src/test/java/org/dozer/MappingProcessorArrayTest.java @@ -73,7 +73,7 @@ public void testPrimitiveArrayCopy() { data[i] = i; } test.setData(data); - DozerBeanMapper dozer = new DozerBeanMapper(); + DozerBeanMapper dozer = DozerBeanMapperBuilder.buildDefault(); PrimitiveArray result = dozer.map(test, PrimitiveArray.class); long start = System.currentTimeMillis(); @@ -93,7 +93,9 @@ public void testReferenceCopy() { data[i] = new MyDate(i); } test.setData(data); - DozerBeanMapper dozer = new DozerBeanMapper(Arrays.asList("mappings/mappingProcessorArrayTest.xml")); + DozerBeanMapper dozer = DozerBeanMapperBuilder.create() + .withMappingFiles("mappings/mappingProcessorArrayTest.xml") + .build(); FinalCopyByReferenceDest result = dozer.map(test, FinalCopyByReferenceDest.class); long start = System.currentTimeMillis(); diff --git a/core/src/test/java/org/dozer/MappingProcessorTest.java b/core/src/test/java/org/dozer/MappingProcessorTest.java index a2901bdde..f53930bf0 100644 --- a/core/src/test/java/org/dozer/MappingProcessorTest.java +++ b/core/src/test/java/org/dozer/MappingProcessorTest.java @@ -40,7 +40,7 @@ public void setUp() { @Test public void testTwiceObjectToObjectConvert() { - DozerBeanMapper mapper = new DozerBeanMapper(); + DozerBeanMapper mapper = DozerBeanMapperBuilder.buildDefault(); Mapper mappingProcessor = mapper.getMappingProcessor(); A src = new A(); diff --git a/core/src/test/java/org/dozer/Version5XSDTest.java b/core/src/test/java/org/dozer/Version5XSDTest.java index 9544ca485..e70232f26 100644 --- a/core/src/test/java/org/dozer/Version5XSDTest.java +++ b/core/src/test/java/org/dozer/Version5XSDTest.java @@ -15,8 +15,6 @@ */ package org.dozer; -import java.util.Arrays; - import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; @@ -38,7 +36,9 @@ public void testOldXSDNaming() { testOldXSDNaming.expectMessage(Matchers.containsString(message)); testOldXSDNaming.expect(MappingException.class); - DozerBeanMapper mapper = new DozerBeanMapper(Arrays.asList("non-strict/v5-xsd.xml")); + DozerBeanMapper mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("non-strict/v5-xsd.xml") + .build(); mapper.getMappingMetadata(); } } diff --git a/core/src/test/java/org/dozer/cache/DozerCacheManagerTest.java b/core/src/test/java/org/dozer/cache/DozerCacheManagerTest.java index ae20c8867..c0a80af4c 100644 --- a/core/src/test/java/org/dozer/cache/DozerCacheManagerTest.java +++ b/core/src/test/java/org/dozer/cache/DozerCacheManagerTest.java @@ -20,24 +20,37 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.stats.StatisticsManager; + import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; /** * @author tierney.matt */ public class DozerCacheManagerTest extends AbstractDozerTest { + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Mock + private StatisticsManager statisticsManager; + private DozerCacheManager cacheMgr; @Override @Before public void setUp() throws Exception { - cacheMgr = new DozerCacheManager(); + cacheMgr = new DozerCacheManager(statisticsManager); } @Test public void testCreateNew() throws Exception { - DozerCacheManager cacheMgr2 = new DozerCacheManager(); + DozerCacheManager cacheMgr2 = new DozerCacheManager(statisticsManager); assertFalse("cache mgrs should not be equal", cacheMgr.equals(cacheMgr2)); assertNotSame("cache mgrs should not be same instance", cacheMgr, cacheMgr2); @@ -78,7 +91,7 @@ public void testAddDuplicateCachesNonSingleton() throws Exception { // You should be able to add caches with the same name to non singleton instances // of the cache manager because they each have their own copies of caches to manage. // The caches are uniquely identified by the cache managers by using the instance id. - DozerCacheManager cacheMgr2 = new DozerCacheManager(); + DozerCacheManager cacheMgr2 = new DozerCacheManager(statisticsManager); // add cache to each cache mgr instance String cacheName = getRandomString(); @@ -113,7 +126,7 @@ public void testGetStatisticTypes() { @Test public void testClearAllCacheEntries() { String name = getRandomString(); - Cache<String, String> cache = new DozerCache<String, String>(name, 5); + Cache<String, String> cache = new DozerCache<String, String>(name, 5, statisticsManager); cache.put(getRandomString(), "value"); cacheMgr.addCache(cache); @@ -125,8 +138,8 @@ public void testClearAllCacheEntries() { @Test public void testGetCaches() { String name = getRandomString(); - Cache<String, String> cache = new DozerCache<String, String>(name, 5); - Cache<String, String> cache2 = new DozerCache<String, String>(name + "2", 5); + Cache<String, String> cache = new DozerCache<String, String>(name, 5, statisticsManager); + Cache<String, String> cache2 = new DozerCache<String, String>(name + "2", 5, statisticsManager); cacheMgr.addCache(cache); cacheMgr.addCache(cache2); diff --git a/core/src/test/java/org/dozer/cache/DozerCacheTest.java b/core/src/test/java/org/dozer/cache/DozerCacheTest.java index 277758626..9ecbc5481 100644 --- a/core/src/test/java/org/dozer/cache/DozerCacheTest.java +++ b/core/src/test/java/org/dozer/cache/DozerCacheTest.java @@ -16,16 +16,28 @@ package org.dozer.cache; import org.dozer.AbstractDozerTest; +import org.dozer.stats.StatisticsManager; + +import org.junit.Rule; import org.junit.Test; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; /** * @author tierney.matt */ public class DozerCacheTest extends AbstractDozerTest { + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Mock + private StatisticsManager statisticsManager; + @Test public void testPutGetFromCache() throws Exception { - Cache cache = new DozerCache(getRandomString(), 50); + Cache cache = new DozerCache(getRandomString(), 50, statisticsManager); int numCacheEntriesToAdd = 45; for (int i = 0; i < numCacheEntriesToAdd; i++) { Object key = String.valueOf(i); @@ -43,7 +55,7 @@ public void testPutGetFromCache() throws Exception { @Test public void testMaximumCacheSize() throws Exception { int maxSize = 25; - Cache cache = new DozerCache(getRandomString(), maxSize); + Cache cache = new DozerCache(getRandomString(), maxSize, statisticsManager); // Add a bunch of entries to cache to verify the cache doesnt grow larger than specified max size for (int i = 0; i < maxSize + 125; i++) { cache.put("testkey" + i, "testvalue" + i); @@ -54,7 +66,7 @@ public void testMaximumCacheSize() throws Exception { @Test(expected = IllegalArgumentException.class) public void testMaximumCacheSize_Zero() throws Exception { int maxSize = 0; - Cache cache = new DozerCache(getRandomString(), maxSize); + Cache cache = new DozerCache(getRandomString(), maxSize, statisticsManager); // Add a bunch of entries to cache to verify the cache doesnt grow larger than specified max size for (int i = 0; i < maxSize + 5; i++) { cache.put("testkey" + i, "testvalue" + i); @@ -64,7 +76,7 @@ public void testMaximumCacheSize_Zero() throws Exception { @Test public void testClear() throws Exception { - Cache<Object, String> cache = new DozerCache<Object, String>(getRandomString(), 50); + Cache<Object, String> cache = new DozerCache<Object, String>(getRandomString(), 50, statisticsManager); Object key = CacheKeyFactory.createKey(String.class, Integer.class); cache.put(key, "testvalue"); @@ -76,27 +88,27 @@ public void testClear() throws Exception { @Test public void testGetMaxSize() { int maxSize = 550; - Cache cache = new DozerCache(getRandomString(), maxSize); + Cache cache = new DozerCache(getRandomString(), maxSize, statisticsManager); assertEquals("invalid max size", maxSize, cache.getMaxSize()); } @Test(expected = IllegalArgumentException.class) public void testGetNull() { - Cache cache = new DozerCache(getRandomString(), 5); + Cache cache = new DozerCache(getRandomString(), 5, statisticsManager); cache.get(null); } @Test(expected = IllegalArgumentException.class) public void testPutNull() { - Cache cache = new DozerCache(getRandomString(), 5); + Cache cache = new DozerCache(getRandomString(), 5, statisticsManager); cache.put(null, null); } @Test public void testAddEntries() { - DozerCache cache = new DozerCache(getRandomString(), 5); - DozerCache<String, String> cache2 = new DozerCache<String, String>(getRandomString(), 5); + DozerCache cache = new DozerCache(getRandomString(), 5, statisticsManager); + DozerCache<String, String> cache2 = new DozerCache<String, String>(getRandomString(), 5, statisticsManager); cache2.put("A", "B"); cache2.put("B", "C"); diff --git a/core/src/test/java/org/dozer/classmap/ClassMapBuilderTest.java b/core/src/test/java/org/dozer/classmap/ClassMapBuilderTest.java index 978b32d3c..6ecdc3a3c 100644 --- a/core/src/test/java/org/dozer/classmap/ClassMapBuilderTest.java +++ b/core/src/test/java/org/dozer/classmap/ClassMapBuilderTest.java @@ -19,7 +19,10 @@ import org.dozer.AbstractDozerTest; import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.DozerConstants; import org.junit.Before; import org.junit.Test; @@ -36,9 +39,12 @@ public class ClassMapBuilderTest extends AbstractDozerTest { @Before public void setUp() throws Exception { - collectionMappingGenerator = new ClassMapBuilder.CollectionMappingGenerator(); - mapMappingGenerator = new ClassMapBuilder.MapMappingGenerator(); - beanMappingGenerator = new BeanMappingGenerator(); + BeanContainer beanContainer = new BeanContainer(); + DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + PropertyDescriptorFactory propertyDescriptorFactory = new PropertyDescriptorFactory(); + collectionMappingGenerator = new ClassMapBuilder.CollectionMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory); + mapMappingGenerator = new ClassMapBuilder.MapMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory); + beanMappingGenerator = new BeanMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory); configuration = new Configuration(); } diff --git a/core/src/test/java/org/dozer/classmap/ClassMapKeyFactoryTest.java b/core/src/test/java/org/dozer/classmap/ClassMapKeyFactoryTest.java index 90216c799..b101e9671 100644 --- a/core/src/test/java/org/dozer/classmap/ClassMapKeyFactoryTest.java +++ b/core/src/test/java/org/dozer/classmap/ClassMapKeyFactoryTest.java @@ -16,6 +16,8 @@ package org.dozer.classmap; import org.dozer.AbstractDozerTest; +import org.dozer.config.BeanContainer; + import org.junit.Before; import org.junit.Test; @@ -28,7 +30,8 @@ public class ClassMapKeyFactoryTest extends AbstractDozerTest { @Before public void setUp() throws Exception { - factory = new ClassMapKeyFactory(); + BeanContainer beanContainer = new BeanContainer(); + factory = new ClassMapKeyFactory(beanContainer); } @Test diff --git a/core/src/test/java/org/dozer/classmap/ClassMapTest.java b/core/src/test/java/org/dozer/classmap/ClassMapTest.java index 9ad763b4c..903ab2c65 100644 --- a/core/src/test/java/org/dozer/classmap/ClassMapTest.java +++ b/core/src/test/java/org/dozer/classmap/ClassMapTest.java @@ -19,8 +19,12 @@ import java.util.List; import org.dozer.AbstractDozerTest; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.GenericFieldMap; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Before; import org.junit.Test; @@ -30,19 +34,24 @@ public class ClassMapTest extends AbstractDozerTest { private ClassMap classMap; - private Configuration globalConfiguration; + private BeanContainer beanContainer; + private DestBeanCreator destBeanCreator; + private PropertyDescriptorFactory propertyDescriptorFactory; @Override @Before public void setUp() throws Exception { - globalConfiguration = new Configuration(); + Configuration globalConfiguration = new Configuration(); classMap = new ClassMap(globalConfiguration); + beanContainer = new BeanContainer(); + destBeanCreator = new DestBeanCreator(beanContainer); + propertyDescriptorFactory = new PropertyDescriptorFactory(); } @Test public void testAddFieldMappings() throws Exception { ClassMap cm = new ClassMap(null); - GenericFieldMap fm = new GenericFieldMap(cm); + GenericFieldMap fm = new GenericFieldMap(cm, beanContainer, destBeanCreator, propertyDescriptorFactory); cm.addFieldMapping(fm); @@ -54,7 +63,7 @@ public void testAddFieldMappings() throws Exception { @Test public void testSetFieldMappings() throws Exception { ClassMap cm = new ClassMap(null); - GenericFieldMap fm = new GenericFieldMap(cm); + GenericFieldMap fm = new GenericFieldMap(cm, beanContainer, destBeanCreator, propertyDescriptorFactory); List<FieldMap> fmList = new ArrayList<FieldMap>(); fmList.add(fm); diff --git a/core/src/test/java/org/dozer/classmap/ClassMappingsTest.java b/core/src/test/java/org/dozer/classmap/ClassMappingsTest.java index 7e0922346..a109c0ff0 100644 --- a/core/src/test/java/org/dozer/classmap/ClassMappingsTest.java +++ b/core/src/test/java/org/dozer/classmap/ClassMappingsTest.java @@ -19,6 +19,8 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; + import org.junit.Before; import org.junit.Test; @@ -34,7 +36,7 @@ public class ClassMappingsTest extends AbstractDozerTest{ @Before public void setUp() { - classMappings = new ClassMappings(); + classMappings = new ClassMappings(new BeanContainer()); } @Test diff --git a/core/src/test/java/org/dozer/classmap/generator/GeneratorUtilsTest.java b/core/src/test/java/org/dozer/classmap/generator/GeneratorUtilsTest.java index 55d928fec..79ead9f51 100644 --- a/core/src/test/java/org/dozer/classmap/generator/GeneratorUtilsTest.java +++ b/core/src/test/java/org/dozer/classmap/generator/GeneratorUtilsTest.java @@ -18,6 +18,7 @@ import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; +import org.dozer.config.BeanContainer; import org.dozer.functional_tests.runner.ProxyDataObjectInstantiator; import org.junit.Test; @@ -29,12 +30,13 @@ public class GeneratorUtilsTest { @Test public void ignoreTechnicalFields() throws Exception { Object proxy = ProxyDataObjectInstantiator.INSTANCE.newInstance(Object.class); + BeanContainer beanContainer = new BeanContainer(); - assertTrue(GeneratorUtils.shouldIgnoreField("callback", proxy.getClass(), Object.class)); - assertFalse(GeneratorUtils.shouldIgnoreField("callback", Object.class, Object.class)); - assertTrue(GeneratorUtils.shouldIgnoreField("callbacks", proxy.getClass(), Object.class)); - assertFalse(GeneratorUtils.shouldIgnoreField("callbacks", Object.class, Object.class)); - assertTrue(GeneratorUtils.shouldIgnoreField("class", Object.class, Object.class)); - assertFalse(GeneratorUtils.shouldIgnoreField("a", proxy.getClass(), Object.class)); + assertTrue(GeneratorUtils.shouldIgnoreField("callback", proxy.getClass(), Object.class, beanContainer)); + assertFalse(GeneratorUtils.shouldIgnoreField("callback", Object.class, Object.class, beanContainer)); + assertTrue(GeneratorUtils.shouldIgnoreField("callbacks", proxy.getClass(), Object.class, beanContainer)); + assertFalse(GeneratorUtils.shouldIgnoreField("callbacks", Object.class, Object.class, beanContainer)); + assertTrue(GeneratorUtils.shouldIgnoreField("class", Object.class, Object.class, beanContainer)); + assertFalse(GeneratorUtils.shouldIgnoreField("a", proxy.getClass(), Object.class, beanContainer)); } } diff --git a/core/src/test/java/org/dozer/config/GlobalSettingsTest.java b/core/src/test/java/org/dozer/config/GlobalSettingsTest.java index d2409934a..6f3f16648 100644 --- a/core/src/test/java/org/dozer/config/GlobalSettingsTest.java +++ b/core/src/test/java/org/dozer/config/GlobalSettingsTest.java @@ -16,6 +16,8 @@ package org.dozer.config; import org.dozer.AbstractDozerTest; +import org.dozer.util.DefaultClassLoader; +import org.dozer.util.DozerClassLoader; import org.dozer.util.DozerConstants; import org.junit.Before; import org.junit.Test; @@ -25,6 +27,8 @@ */ public class GlobalSettingsTest extends AbstractDozerTest { + private DozerClassLoader classLoader = new DefaultClassLoader(GlobalSettingsTest.class.getClassLoader()); + @Before public void setUp() { System.setProperty(DozerConstants.CONFIG_FILE_SYS_PROP, ""); @@ -32,7 +36,7 @@ public void setUp() { @Test public void testLoadDefaultPropFile_Default() { - GlobalSettings globalSettings = GlobalSettings.createNew(); + GlobalSettings globalSettings = new GlobalSettings(classLoader); assertNotNull("loaded by name should not be null", globalSettings.getLoadedByFileName()); assertEquals("invalid loaded by file name", DozerConstants.DEFAULT_CONFIG_FILE, globalSettings.getLoadedByFileName()); } @@ -41,7 +45,7 @@ public void testLoadDefaultPropFile_Default() { public void testLoadDefaultPropFile_NotFound() { String propFileName = String.valueOf(System.currentTimeMillis()); System.setProperty(DozerConstants.CONFIG_FILE_SYS_PROP, propFileName); - GlobalSettings globalSettings = GlobalSettings.createNew(); + GlobalSettings globalSettings = new GlobalSettings(classLoader); // assert all global settings equal the default values assertNull("loaded by file name should be null", globalSettings.getLoadedByFileName()); @@ -62,7 +66,7 @@ public void testLoadPropFile_SpecifiedViaSysProp() { String propFileName = "samplecustomdozer.properties"; System.setProperty(DozerConstants.CONFIG_FILE_SYS_PROP, propFileName); - GlobalSettings globalSettings = GlobalSettings.createNew(); + GlobalSettings globalSettings = new GlobalSettings(classLoader); assertNotNull("loaded by name should not be null", globalSettings.getLoadedByFileName()); assertEquals("invalid load by file name", propFileName, globalSettings.getLoadedByFileName()); diff --git a/core/src/test/java/org/dozer/converters/CustomConverterContainerTest.java b/core/src/test/java/org/dozer/converters/CustomConverterContainerTest.java index 81ddee4d3..59620f17a 100644 --- a/core/src/test/java/org/dozer/converters/CustomConverterContainerTest.java +++ b/core/src/test/java/org/dozer/converters/CustomConverterContainerTest.java @@ -21,8 +21,11 @@ import org.dozer.AbstractDozerTest; import org.dozer.cache.CacheKeyFactory; import org.dozer.cache.DozerCache; +import org.dozer.stats.StatisticsManager; + import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; /** * @author tierney.matt @@ -37,7 +40,7 @@ public class CustomConverterContainerTest extends AbstractDozerTest { @Before public void setUp() throws Exception { ccc = new CustomConverterContainer(); - cache = new DozerCache("NAME", 10); + cache = new DozerCache("NAME", 10, Mockito.mock(StatisticsManager.class)); converters = new ArrayList<CustomConverterDescription>(); ccc.setConverters(converters); } diff --git a/core/src/test/java/org/dozer/converters/JAXBElementConverterTest.java b/core/src/test/java/org/dozer/converters/JAXBElementConverterTest.java index f1f3cfffb..07f91c950 100644 --- a/core/src/test/java/org/dozer/converters/JAXBElementConverterTest.java +++ b/core/src/test/java/org/dozer/converters/JAXBElementConverterTest.java @@ -26,6 +26,7 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.vo.jaxb.employee.EmployeeType; import org.dozer.vo.jaxb.employee.EmployeeWithInnerClass; import org.junit.Before; @@ -41,15 +42,17 @@ public class JAXBElementConverterTest extends AbstractDozerTest { public static final int DAY = 1; private JAXBElementConverter converter; + private BeanContainer beanContainer; @Before public void setUp() throws Exception { super.setUp(); + beanContainer = new BeanContainer(); } @Test public void stringToJAXBElementConversion() throws Exception { - converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); Object conversion = converter.convert(JAXBElement.class, "dummy"); assertNotNull(conversion); assertEquals("javax.xml.bind.JAXBElement", conversion.getClass().getCanonicalName()); @@ -59,7 +62,7 @@ public void stringToJAXBElementConversion() throws Exception { @Test public void xmlgregoriancalendarToJAXBElementConversion() throws Exception { - converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); DatatypeFactory instance = DatatypeFactory.newInstance(); XMLGregorianCalendar calendar = instance.newXMLGregorianCalendar(new GregorianCalendar(2001, 1, 1)); Object conversion = converter.convert(JAXBElement.class, calendar); @@ -71,7 +74,7 @@ public void xmlgregoriancalendarToJAXBElementConversion() throws Exception { @Test public void calendarToJAXBElementConversion() throws Exception { - converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); Calendar calendar = new GregorianCalendar(2001, 1, 1); Object conversion = converter.convert(JAXBElement.class, calendar); assertNotNull(conversion); @@ -84,7 +87,7 @@ public void calendarToJAXBElementConversion() throws Exception { @Test public void dateToJAXBElementConversion() throws Exception { - converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); Date calendar = new Date(YEAR, MONTH, DAY); Object conversion = converter.convert(JAXBElement.class, calendar); assertNotNull(conversion); @@ -97,7 +100,7 @@ public void dateToJAXBElementConversion() throws Exception { @Test public void dateToJAXBElementStringConversion() throws Exception { - converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); Date calendar = new Date(YEAR, MONTH, DAY); Object conversion = converter.convert(JAXBElement.class, calendar); assertNotNull(conversion); @@ -108,7 +111,7 @@ public void dateToJAXBElementStringConversion() throws Exception { @Test public void calendarToJAXBElementStringConversion() throws Exception { - converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); Calendar calendar = new GregorianCalendar(2001, 1, 1); Object conversion = converter.convert(JAXBElement.class, calendar); assertNotNull(conversion); @@ -119,13 +122,13 @@ public void calendarToJAXBElementStringConversion() throws Exception { @Test(expected = MappingException.class) public void createFieldNotFoundException() throws Exception { - converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "vds", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "vds", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); converter.convert(JAXBElement.class, "dummy"); } @Test public void stringTypeBeanId() throws Exception { - converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "parentName", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); String beanId = converter.getBeanId(); assertNotNull(beanId); assertEquals("java.lang.String", beanId); @@ -133,7 +136,7 @@ public void stringTypeBeanId() throws Exception { @Test public void xmlgregoriancalendarTypeBeanId() throws Exception { - converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeType.class.getCanonicalName(), "birthDate", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); String beanId = converter.getBeanId(); assertNotNull(beanId); assertEquals("javax.xml.datatype.XMLGregorianCalendar", beanId); @@ -141,7 +144,7 @@ public void xmlgregoriancalendarTypeBeanId() throws Exception { @Test(expected = MappingException.class) public void beanIdFieldNotFoundException() throws Exception { - converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "vds", new SimpleDateFormat("dd.MM.yyyy")); + converter = new JAXBElementConverter(EmployeeWithInnerClass.class.getCanonicalName(), "vds", new SimpleDateFormat("dd.MM.yyyy"), beanContainer); converter.getBeanId(); } } diff --git a/core/src/test/java/org/dozer/converters/PrimitiveOrWrapperConverterTest.java b/core/src/test/java/org/dozer/converters/PrimitiveOrWrapperConverterTest.java index 9f139a01e..cb2da1bac 100644 --- a/core/src/test/java/org/dozer/converters/PrimitiveOrWrapperConverterTest.java +++ b/core/src/test/java/org/dozer/converters/PrimitiveOrWrapperConverterTest.java @@ -31,6 +31,8 @@ import javax.xml.datatype.XMLGregorianCalendar; import org.dozer.AbstractDozerTest; +import org.dozer.config.BeanContainer; + import org.junit.Assert; import org.junit.Test; @@ -41,7 +43,7 @@ */ public class PrimitiveOrWrapperConverterTest extends AbstractDozerTest { - private PrimitiveOrWrapperConverter converter = new PrimitiveOrWrapperConverter(); + private PrimitiveOrWrapperConverter converter = new PrimitiveOrWrapperConverter(new BeanContainer()); @Test public void testConvertPrimitiveOrWrapperEmptyString() throws Exception { diff --git a/core/src/test/java/org/dozer/factory/ConstructionStrategiesTest.java b/core/src/test/java/org/dozer/factory/ConstructionStrategiesTest.java index 9a6cc9c9a..e0416ed61 100644 --- a/core/src/test/java/org/dozer/factory/ConstructionStrategiesTest.java +++ b/core/src/test/java/org/dozer/factory/ConstructionStrategiesTest.java @@ -27,10 +27,13 @@ import org.dozer.AbstractDozerTest; import org.dozer.BeanFactory; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.vo.jaxb.employee.EmployeeWithInnerClass; import org.junit.Before; import org.junit.Test; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -53,6 +56,7 @@ public class ConstructionStrategiesTest extends AbstractDozerTest { private XMLBeanFactory xmlBeanFactory; private JAXBBeanFactory jaxbBeanFactory; + private BeanContainer beanContainer; @Before @Override @@ -60,14 +64,15 @@ public void setUp() throws Exception { super.setUp(); xmlBeanFactory = mock(XMLBeanFactory.class); jaxbBeanFactory = mock(JAXBBeanFactory.class); + beanContainer = new BeanContainer(); - byCreateMethod = new ConstructionStrategies.ByCreateMethod(); - byGetInstance = new ConstructionStrategies.ByGetInstance(); - byFactory = new ConstructionStrategies.ByFactory(); + byCreateMethod = new ConstructionStrategies.ByCreateMethod(beanContainer); + byGetInstance = new ConstructionStrategies.ByGetInstance(beanContainer); + byFactory = new ConstructionStrategies.ByFactory(beanContainer); byInterface = new ConstructionStrategies.ByInterface(); byConstructor = new ConstructionStrategies.ByConstructor(); - xmlBeansBased = new ConstructionStrategies.XMLBeansBased(xmlBeanFactory); - jaxbBeansBased = new ConstructionStrategies.JAXBBeansBased(jaxbBeanFactory); + xmlBeansBased = new ConstructionStrategies.XMLBeansBased(xmlBeanFactory, beanContainer); + jaxbBeansBased = new ConstructionStrategies.JAXBBeansBased(jaxbBeanFactory, beanContainer); directive = new BeanCreationDirective(); } @@ -212,7 +217,7 @@ public void shouldInstantiateByXmlBeansFactory() { xmlBeansBased.create(directive); - verify(xmlBeanFactory, times(1)).createBean("", String.class, "id"); + verify(xmlBeanFactory, times(1)).createBean(eq(""), eq(String.class), eq("id"), any()); } @Test @@ -224,7 +229,7 @@ public void shouldInstantiateByJaxbBeansFactory() { jaxbBeansBased.create(directive); - verify(jaxbBeanFactory, times(1)).createBean("dummy", String.class, String.class.getCanonicalName()); + verify(jaxbBeanFactory, times(1)).createBean(eq("dummy"), eq(String.class), eq(String.class.getCanonicalName()), any()); } public static final class SelfFactory { @@ -245,7 +250,7 @@ public String getName() { public static class MyBeanFactory implements BeanFactory { - public Object createBean(Object source, Class<?> sourceClass, String targetBeanId) { + public Object createBean(Object source, Class<?> sourceClass, String targetBeanId, BeanContainer beanContainer) { return ""; } diff --git a/core/src/test/java/org/dozer/factory/DestBeanCreatorTest.java b/core/src/test/java/org/dozer/factory/DestBeanCreatorTest.java index 6d31d7252..3fbf543be 100644 --- a/core/src/test/java/org/dozer/factory/DestBeanCreatorTest.java +++ b/core/src/test/java/org/dozer/factory/DestBeanCreatorTest.java @@ -20,6 +20,7 @@ import java.util.TreeMap; import org.dozer.AbstractDozerTest; +import org.dozer.config.BeanContainer; import org.dozer.vo.TestObject; import org.dozer.vo.TestObjectPrime; import org.junit.Test; @@ -29,9 +30,11 @@ */ public class DestBeanCreatorTest extends AbstractDozerTest { + private DestBeanCreator destBeanCreator = new DestBeanCreator(new BeanContainer()); + @Test public void testCreatDestBeanNoFactory() throws Exception { - TestObject bean = (TestObject) DestBeanCreator.create(new BeanCreationDirective(null, null, TestObject.class, null, null, null, null)); + TestObject bean = (TestObject) destBeanCreator.create(new BeanCreationDirective(null, null, TestObject.class, null, null, null, null)); assertNotNull(bean); assertNull(bean.getCreatedByFactoryName()); @@ -40,7 +43,7 @@ public void testCreatDestBeanNoFactory() throws Exception { @Test public void testCreatBeanFromFactory() throws Exception { String factoryName = "org.dozer.functional_tests.support.SampleCustomBeanFactory"; - TestObject bean = (TestObject) DestBeanCreator.create( + TestObject bean = (TestObject) destBeanCreator.create( new BeanCreationDirective(new TestObjectPrime(), TestObjectPrime.class, TestObject.class, null, factoryName, null, null)); assertNotNull(bean); @@ -49,10 +52,10 @@ public void testCreatBeanFromFactory() throws Exception { @Test public void testMap() { - Map map = DestBeanCreator.create(Map.class); + Map map = destBeanCreator.create(Map.class); assertTrue(map instanceof HashMap); - TreeMap treeMap = DestBeanCreator.create(TreeMap.class); + TreeMap treeMap = destBeanCreator.create(TreeMap.class); assertNotNull(treeMap); } diff --git a/core/src/test/java/org/dozer/factory/JAXBBeanFactoryTest.java b/core/src/test/java/org/dozer/factory/JAXBBeanFactoryTest.java index e4450ec26..8e393c871 100644 --- a/core/src/test/java/org/dozer/factory/JAXBBeanFactoryTest.java +++ b/core/src/test/java/org/dozer/factory/JAXBBeanFactoryTest.java @@ -17,6 +17,8 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; + import org.junit.Before; import org.junit.Test; @@ -27,34 +29,36 @@ public class JAXBBeanFactoryTest extends AbstractDozerTest { private JAXBBeanFactory factory; + private BeanContainer beanContainer; @Before public void setUp() throws Exception { factory = new JAXBBeanFactory(); + beanContainer = new BeanContainer(); } @Test public void testCreateBeanForSimpleJaxbClass() { - Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeType"); + Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeType", beanContainer); assertNotNull("Object can not be null", obj); assertEquals("org.dozer.vo.jaxb.employee.EmployeeType", obj.getClass().getName()); } @Test(expected = MappingException.class) public void testCreateBeanClassNotFoundException() { - factory.createBean(null, null, "ve.ve.DE"); + factory.createBean(null, null, "ve.ve.DE", beanContainer); } @Test public void testCreateBeanForInnerJaxbClass() { - Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address"); + Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address", beanContainer); assertNotNull(obj); assertEquals("org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address", obj.getClass().getName()); } @Test public void testCreateBeanForNestedInnerJaxbClass() { - Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address$State"); + Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address$State", beanContainer); assertNotNull(obj); assertEquals("org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address$State", obj.getClass().getName()); } diff --git a/core/src/test/java/org/dozer/fieldmap/FieldMapTest.java b/core/src/test/java/org/dozer/fieldmap/FieldMapTest.java index f75de7fac..01324e505 100644 --- a/core/src/test/java/org/dozer/fieldmap/FieldMapTest.java +++ b/core/src/test/java/org/dozer/fieldmap/FieldMapTest.java @@ -24,6 +24,10 @@ import org.dozer.AbstractDozerTest; import org.dozer.classmap.ClassMap; import org.dozer.classmap.DozerClass; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Before; import org.junit.Test; @@ -42,7 +46,8 @@ public class FieldMapTest extends AbstractDozerTest { @Before public void setUp() { classMap = mock(ClassMap.class); - fieldMap = new FieldMap(classMap) {}; + BeanContainer beanContainer = new BeanContainer(); + fieldMap = new FieldMap(classMap, beanContainer, new DestBeanCreator(beanContainer), new PropertyDescriptorFactory()) {}; DozerClass dozerClass = mock(DozerClass.class); when(classMap.getDestClass()).thenReturn(dozerClass); field = mock(DozerField.class); diff --git a/core/src/test/java/org/dozer/fieldmap/MapFieldMapTest.java b/core/src/test/java/org/dozer/fieldmap/MapFieldMapTest.java index 0fe936908..902cef8ec 100644 --- a/core/src/test/java/org/dozer/fieldmap/MapFieldMapTest.java +++ b/core/src/test/java/org/dozer/fieldmap/MapFieldMapTest.java @@ -18,6 +18,10 @@ import org.dozer.AbstractDozerTest; import org.dozer.classmap.MappingDirection; import org.dozer.classmap.RelationshipType; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Test; import static org.mockito.Mockito.mock; @@ -27,27 +31,31 @@ */ public class MapFieldMapTest extends AbstractDozerTest { + private BeanContainer beanContainer = new BeanContainer(); + private DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + private PropertyDescriptorFactory propertyDescriptorFactory = new PropertyDescriptorFactory(); + @Test public void testConstructor() { FieldMap fieldMap = mock(FieldMap.class); - MapFieldMap source = new MapFieldMap(fieldMap); + MapFieldMap source = new MapFieldMap(fieldMap, beanContainer, destBeanCreator, propertyDescriptorFactory); source.setCopyByReference(true); source.setCustomConverter("converter"); source.setCustomConverterId("coverterId"); source.setCustomConverterParam("param"); source.setDestField(new DozerField("name", "type")); - source.setDestHintContainer(new HintContainer()); - source.setDestDeepIndexHintContainer(new HintContainer()); + source.setDestHintContainer(new HintContainer(beanContainer)); + source.setDestDeepIndexHintContainer(new HintContainer(beanContainer)); source.setMapId("mapId"); source.setRelationshipType(RelationshipType.NON_CUMULATIVE); source.setRemoveOrphans(true); source.setSrcField(new DozerField("name", "type")); - source.setSrcHintContainer(new HintContainer()); - source.setSrcDeepIndexHintContainer(new HintContainer()); + source.setSrcHintContainer(new HintContainer(beanContainer)); + source.setSrcDeepIndexHintContainer(new HintContainer(beanContainer)); source.setType(MappingDirection.ONE_WAY); - MapFieldMap result = new MapFieldMap(source); + MapFieldMap result = new MapFieldMap(source, beanContainer, destBeanCreator, propertyDescriptorFactory); assertEquals(source.isCopyByReference(), result.isCopyByReference()); assertEquals(source.getCustomConverter(), result.getCustomConverter()); diff --git a/core/src/test/java/org/dozer/functional_tests/AbstractFunctionalTest.java b/core/src/test/java/org/dozer/functional_tests/AbstractFunctionalTest.java index d797c2a53..332b27c01 100644 --- a/core/src/test/java/org/dozer/functional_tests/AbstractFunctionalTest.java +++ b/core/src/test/java/org/dozer/functional_tests/AbstractFunctionalTest.java @@ -20,6 +20,7 @@ import java.util.List; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.functional_tests.runner.InstantiatorHolder; import org.dozer.functional_tests.runner.Proxied; @@ -50,7 +51,7 @@ protected DataObjectInstantiator getDataObjectInstantiator() { public void setUp() throws Exception { System.setProperty("log4j.debug", "true"); System.setProperty(DozerConstants.DEBUG_SYS_PROP, "true"); - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); } protected Mapper getMapper(String ... mappingFiles) { @@ -58,7 +59,7 @@ protected Mapper getMapper(String ... mappingFiles) { if (mappingFiles != null) { list.addAll(Arrays.asList(mappingFiles)); } - Mapper result = new DozerBeanMapper(); + Mapper result = DozerBeanMapperBuilder.buildDefault(); ((DozerBeanMapper) result).setMappingFiles(list); return result; } diff --git a/core/src/test/java/org/dozer/functional_tests/BiDirectionalMappingTest.java b/core/src/test/java/org/dozer/functional_tests/BiDirectionalMappingTest.java index ed0fe370f..8a8b8f2b3 100644 --- a/core/src/test/java/org/dozer/functional_tests/BiDirectionalMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/BiDirectionalMappingTest.java @@ -15,7 +15,7 @@ */ package org.dozer.functional_tests; -import org.dozer.DozerBeanMapperSingletonWrapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.vo.LoopObjectChild; import org.dozer.vo.LoopObjectParent; @@ -75,7 +75,9 @@ public void testManyObjects() { a.getCs()[i] = c; } - Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); + Mapper mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("testDozerBeanMapping.xml") + .build(); mapper.map(a, b); // Check if C object nr i holds value i after the mapping diff --git a/core/src/test/java/org/dozer/functional_tests/CircularDependenciesTest.java b/core/src/test/java/org/dozer/functional_tests/CircularDependenciesTest.java index 7dc4ad716..6dad96580 100644 --- a/core/src/test/java/org/dozer/functional_tests/CircularDependenciesTest.java +++ b/core/src/test/java/org/dozer/functional_tests/CircularDependenciesTest.java @@ -16,6 +16,7 @@ package org.dozer.functional_tests; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.junit.Before; import org.junit.Test; @@ -29,7 +30,7 @@ public class CircularDependenciesTest extends AbstractFunctionalTest { @Before public void setUp() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); } @Test diff --git a/core/src/test/java/org/dozer/functional_tests/ClassloaderTest.java b/core/src/test/java/org/dozer/functional_tests/ClassloaderTest.java index edd841ef0..e4f922678 100644 --- a/core/src/test/java/org/dozer/functional_tests/ClassloaderTest.java +++ b/core/src/test/java/org/dozer/functional_tests/ClassloaderTest.java @@ -15,9 +15,7 @@ */ package org.dozer.functional_tests; -import java.util.ArrayList; - -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.junit.Test; import static org.junit.Assert.assertNotNull; @@ -29,9 +27,9 @@ public class ClassloaderTest extends AbstractFunctionalTest { @Test public void testClassloader() { - ArrayList<String> files = new ArrayList<String>(); - files.add("non-strict/classloader.xml"); - mapper = new DozerBeanMapper(files); + mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("non-strict/classloader.xml") + .build(); assertNotNull(mapper); } diff --git a/core/src/test/java/org/dozer/functional_tests/ConstructorTest.java b/core/src/test/java/org/dozer/functional_tests/ConstructorTest.java index 1f8308f3d..902d63b4a 100644 --- a/core/src/test/java/org/dozer/functional_tests/ConstructorTest.java +++ b/core/src/test/java/org/dozer/functional_tests/ConstructorTest.java @@ -27,6 +27,7 @@ import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.junit.Before; import org.junit.Test; @@ -43,7 +44,7 @@ public class ConstructorTest extends AbstractFunctionalTest { @Before public void setUp() { - beanMapper = new DozerBeanMapper(); + beanMapper = DozerBeanMapperBuilder.buildDefault(); } @Test diff --git a/core/src/test/java/org/dozer/functional_tests/CustomConverterMapperAwareTest.java b/core/src/test/java/org/dozer/functional_tests/CustomConverterMapperAwareTest.java index f5c5d2ae8..167e48a8a 100644 --- a/core/src/test/java/org/dozer/functional_tests/CustomConverterMapperAwareTest.java +++ b/core/src/test/java/org/dozer/functional_tests/CustomConverterMapperAwareTest.java @@ -25,6 +25,7 @@ import org.dozer.CustomConverter; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.DozerConverter; import org.dozer.Mapper; import org.dozer.MapperAware; @@ -69,7 +70,9 @@ public void test_convert_withInjectedMapper() { @Test public void test_convert_withSubclassedConverterInstance() throws Exception { - DozerBeanMapper mapper = new DozerBeanMapper(Arrays.asList("mappings/customConverterMapperAware.xml")); + DozerBeanMapper mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("mappings/customConverterMapperAware.xml") + .build(); mapper.setCustomConverters(Arrays.<CustomConverter>asList(new Converter() { @Override public Map convertTo(List source, Map destination) { diff --git a/core/src/test/java/org/dozer/functional_tests/CustomConverterMappingTest.java b/core/src/test/java/org/dozer/functional_tests/CustomConverterMappingTest.java index 93a5a97b2..e2da64ee9 100644 --- a/core/src/test/java/org/dozer/functional_tests/CustomConverterMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/CustomConverterMappingTest.java @@ -163,7 +163,7 @@ public void testArrayToStringCustomConverter() throws Exception { @Test public void testCustomConverterMapping() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); TestCustomConverterObject obj = newInstance(TestCustomConverterObject.class); CustomDoubleObjectIF doub = newInstance(CustomDoubleObject.class); doub.setTheDouble(15); @@ -219,7 +219,7 @@ public void testCustomConverterMapping() throws Exception { @Test public void testCustomConverterWithPrimitive() throws Exception { // test primitive double - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); TestCustomConverterObjectPrime prime = newInstance(TestCustomConverterObjectPrime.class); prime.setPrimitiveDoubleAttribute(25.00); prime.setDoubleAttribute(new Double(30.00)); @@ -236,7 +236,7 @@ public void testCustomConverterWithPrimitive() throws Exception { @Test public void testCustomConverterHashMapMapping() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); TestCustomConverterHashMapObject testCustomConverterHashMapObject = newInstance(TestCustomConverterHashMapObject.class); TestObject to = newInstance(TestObject.class); to.setOne("one"); diff --git a/core/src/test/java/org/dozer/functional_tests/DeepMappingTest.java b/core/src/test/java/org/dozer/functional_tests/DeepMappingTest.java index 584c60831..b7705f946 100644 --- a/core/src/test/java/org/dozer/functional_tests/DeepMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/DeepMappingTest.java @@ -42,7 +42,7 @@ public class DeepMappingTest extends AbstractFunctionalTest { @Test public void testDeepMapping() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); SrcDeepObj src = testDataFactory.getSrcDeepObj(); DestDeepObj dest = mapper.map(src, DestDeepObj.class); SrcDeepObj src2 = mapper.map(dest, SrcDeepObj.class); @@ -54,7 +54,7 @@ public void testDeepMapping() throws Exception { @Test public void testDeepPropertyOneWay() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); House house = newInstance(House.class); Person owner = newInstance(Person.class); owner.setYourName("myName"); diff --git a/core/src/test/java/org/dozer/functional_tests/DozerBeanMapperTest.java b/core/src/test/java/org/dozer/functional_tests/DozerBeanMapperTest.java index f8cbefe1c..6b51fa9bf 100644 --- a/core/src/test/java/org/dozer/functional_tests/DozerBeanMapperTest.java +++ b/core/src/test/java/org/dozer/functional_tests/DozerBeanMapperTest.java @@ -20,7 +20,7 @@ import org.dozer.AbstractDozerTest; import org.dozer.DozerBeanMapper; -import org.dozer.DozerInitializer; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.MappingException; import org.dozer.functional_tests.runner.NoProxyDataObjectInstantiator; @@ -52,7 +52,7 @@ public class DozerBeanMapperTest extends AbstractDozerTest { @Before public void setUp() throws Exception { if (mapper == null) { - mapper = getNewMapper(new String[]{"dozerBeanMapping.xml"}); + mapper = getNewMapper(new String[]{"testDozerBeanMapping.xml"}); } } @@ -90,17 +90,16 @@ public void testGeneralMapping() throws Exception { public void testNoMappingFilesSpecified() throws Exception { // Mapper can be used without specifying any mapping files. Fields that have the same name will be mapped // automatically. - Mapper mapper = new DozerBeanMapper(); + Mapper mapper = DozerBeanMapperBuilder.buildDefault(); assertCommon(mapper); } @Test(expected=IllegalArgumentException.class) public void testDetectDuplicateMapping() throws Exception { - Mapper myMapper = null; - List<String> mappingFiles = new ArrayList<String>(); - mappingFiles.add("mappings/duplicateMapping.xml"); - myMapper = new DozerBeanMapper(mappingFiles); + Mapper myMapper = DozerBeanMapperBuilder.create() + .withMappingFiles("mappings/duplicateMapping.xml") + .build(); myMapper.map(new org.dozer.vo.SuperSuperSuperClass(), org.dozer.vo.SuperSuperSuperClassPrime.class); fail("should have thrown exception"); @@ -139,17 +138,9 @@ public void testCustomBeanFactory() throws Exception { assertEquals("testName", car.getName()); } - @Test - public void testDestroy() throws Exception { - DozerBeanMapper mapper = new DozerBeanMapper(); - assertTrue(DozerInitializer.getInstance().isInitialized()); - mapper.destroy(); - assertFalse(DozerInitializer.getInstance().isInitialized()); - } - @Test public void testGlobalNullAndEmptyString() throws Exception { - DozerBeanMapper mapperMapNull = new DozerBeanMapper(); + DozerBeanMapper mapperMapNull = DozerBeanMapperBuilder.buildDefault(); DozerBeanMapper mapperNotMapNull = (DozerBeanMapper) getNewMapper(new String[]{"mappings/customGlobalConfigWithNullAndEmptyStringTest.xml"}); Van src = new Van(); Van dest = new Van(); @@ -177,7 +168,7 @@ private Mapper getNewMapper(String[] mappingFiles) { list.add(mappingFiles[i]); } } - Mapper mapper = new DozerBeanMapper(); + Mapper mapper = DozerBeanMapperBuilder.buildDefault(); ((DozerBeanMapper) mapper).setMappingFiles(list); return mapper; } diff --git a/core/src/test/java/org/dozer/functional_tests/ExceptionHandlingFunctionalTest.java b/core/src/test/java/org/dozer/functional_tests/ExceptionHandlingFunctionalTest.java index c918e591d..3b1cc1d10 100644 --- a/core/src/test/java/org/dozer/functional_tests/ExceptionHandlingFunctionalTest.java +++ b/core/src/test/java/org/dozer/functional_tests/ExceptionHandlingFunctionalTest.java @@ -16,6 +16,7 @@ package org.dozer.functional_tests; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.MappingException; import org.dozer.loader.api.BeanMappingBuilder; import org.junit.Before; @@ -39,7 +40,7 @@ public void test_UnableToDetermineType() { @Test(expected = IllegalArgumentException.class) public void shouldFailOnDuplicateMapping() { - DozerBeanMapper mapper = new DozerBeanMapper(); + DozerBeanMapper mapper = DozerBeanMapperBuilder.buildDefault(); mapper.addMapping(new BeanMappingBuilder() { @Override protected void configure() { diff --git a/core/src/test/java/org/dozer/functional_tests/GenericsTest.java b/core/src/test/java/org/dozer/functional_tests/GenericsTest.java index 65ac3100e..63961a811 100755 --- a/core/src/test/java/org/dozer/functional_tests/GenericsTest.java +++ b/core/src/test/java/org/dozer/functional_tests/GenericsTest.java @@ -15,7 +15,7 @@ */ package org.dozer.functional_tests; -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.vo.generics.parameterized.A; import org.dozer.vo.generics.parameterized.AA; @@ -33,7 +33,7 @@ public class GenericsTest extends AbstractFunctionalTest { @Test public void testSimpleGenerics() { - Mapper mapper = new DozerBeanMapper(); + Mapper mapper = DozerBeanMapperBuilder.buildDefault(); A a = new A(); a.setId(15L); @@ -51,7 +51,7 @@ public void testSimpleGenerics() { */ @Test public void testSimpleGenericsInheritance() { - Mapper mapper = new DozerBeanMapper(); + Mapper mapper = DozerBeanMapperBuilder.buildDefault(); B b = new B(); b.setId(15); @@ -70,7 +70,7 @@ public void testSimpleGenericsInheritance() { */ @Test public void testDeepGenericInheritanceTest() throws Exception { - Mapper mapper = new DozerBeanMapper(); + Mapper mapper = DozerBeanMapperBuilder.buildDefault(); B b = new B(); b.setId(12345); @@ -83,7 +83,7 @@ public void testDeepGenericInheritanceTest() throws Exception { */ @Test public void testGenericsWithSeveralTypes() { - Mapper mapper = new DozerBeanMapper(); + Mapper mapper = DozerBeanMapperBuilder.buildDefault(); GenericTestType testType = new GenericTestType(); testType.setA(15L); diff --git a/core/src/test/java/org/dozer/functional_tests/GranularDozerBeanMapperTest.java b/core/src/test/java/org/dozer/functional_tests/GranularDozerBeanMapperTest.java index b5c9b0788..42bc85aff 100644 --- a/core/src/test/java/org/dozer/functional_tests/GranularDozerBeanMapperTest.java +++ b/core/src/test/java/org/dozer/functional_tests/GranularDozerBeanMapperTest.java @@ -597,7 +597,7 @@ public void testGlobalBeanFactoryAppliedToDefaultMappings() throws Exception { @Test public void testStringToDateMapping() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SS"); String dateStr = "01/29/1975 10:45:13:25"; TestObject sourceObj = newInstance(TestObject.class); @@ -613,7 +613,7 @@ public void testStringToDateMapping() throws Exception { @Test public void testMethodMapping() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); MethodFieldTestObject sourceObj = newInstance(MethodFieldTestObject.class); sourceObj.setIntegerStr("1500"); sourceObj.setPriceItem("3500"); @@ -632,7 +632,7 @@ public void testMethodMapping() throws Exception { @Test public void testNoReadMethod() throws Exception { // If the field doesnt have a getter/setter, dont add it is a default field to be mapped. - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); NoReadMethod src = newInstance(NoReadMethod.class); src.setNoReadMethod("somevalue"); @@ -643,7 +643,7 @@ public void testNoReadMethod() throws Exception { @Test public void testNoReadMethodSameClassTypes() throws Exception { // If the field doesnt have a getter/setter, dont add it is a default field to be mapped. - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); NoReadMethod src = newInstance(NoReadMethod.class); src.setNoReadMethod("somevalue"); @@ -654,7 +654,7 @@ public void testNoReadMethodSameClassTypes() throws Exception { @Test public void testNoReadMethod_GetterOnlyWithParams() throws Exception { // Dont use getter methods that have a param when discovering default fields to be mapped. - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); NoReadMethod src = newInstance(NoReadMethod.class); src.setOtherNoReadMethod("someValue"); @@ -664,7 +664,7 @@ public void testNoReadMethod_GetterOnlyWithParams() throws Exception { @Test public void testNoWriteMethod() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); NoWriteMethod src = newInstance(NoWriteMethod.class); src.setXXXXXX("someValue"); @@ -676,7 +676,7 @@ public void testNoWriteMethod() throws Exception { public void testNoWriteMethodSameClassTypes() throws Exception { // When mapping between identical types, if the field doesnt have a getter/setter, dont // add it is a default field to be mapped. - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); NoWriteMethod src = newInstance(NoWriteMethod.class); src.setXXXXXX("someValue"); @@ -688,7 +688,7 @@ public void testNoWriteMethodSameClassTypes() throws Exception { @Test public void testNoVoidSetters() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); NoVoidSetters src = newInstance(NoVoidSetters.class); src.setDescription("someValue"); src.setI(1); @@ -700,7 +700,7 @@ public void testNoVoidSetters() throws Exception { @Test public void testNullField() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); AnotherTestObject src = newInstance(AnotherTestObject.class); src.setField2(null); AnotherTestObjectPrime dest = newInstance(AnotherTestObjectPrime.class); @@ -712,7 +712,7 @@ public void testNullField() throws Exception { @Test public void testNullField2() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); // Test that String --> String with an empty String input value results // in the destination field being an empty String and not null. String input = ""; @@ -726,7 +726,7 @@ public void testNullField2() throws Exception { @Test public void testNullToPrimitive() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); AnotherTestObject src = newInstance(AnotherTestObject.class); AnotherTestObjectPrime prime = newInstance(AnotherTestObjectPrime.class); TestObject to = newInstance(TestObject.class); diff --git a/core/src/test/java/org/dozer/functional_tests/InheritanceAbstractClassMappingTest.java b/core/src/test/java/org/dozer/functional_tests/InheritanceAbstractClassMappingTest.java index 9302cc7fb..85dde8b64 100644 --- a/core/src/test/java/org/dozer/functional_tests/InheritanceAbstractClassMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/InheritanceAbstractClassMappingTest.java @@ -18,7 +18,7 @@ import java.util.ArrayList; import java.util.List; -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.MappingException; import org.dozer.vo.abstractinheritance.A; import org.dozer.vo.abstractinheritance.AbstractA; @@ -66,7 +66,7 @@ public void testCustomMappingForAbstractClasses() throws Exception { public void testNoCustomMappingForAbstractClasses() throws Exception { // Test that wildcard fields in abstract classes are mapped when there is no explicit abstract custom mapping // definition - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); A src = getA(); B dest = mapper.map(src, B.class); diff --git a/core/src/test/java/org/dozer/functional_tests/InheritanceMappingTest.java b/core/src/test/java/org/dozer/functional_tests/InheritanceMappingTest.java index a2a4962c9..8fa0a20fa 100644 --- a/core/src/test/java/org/dozer/functional_tests/InheritanceMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/InheritanceMappingTest.java @@ -19,7 +19,7 @@ import java.util.List; import org.apache.commons.lang3.SerializationUtils; -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.vo.NoSuperClass; import org.dozer.vo.SubClass; @@ -89,7 +89,7 @@ public void testCustomMappingForSuperClasses() throws Exception { @Test public void testNoCustomMappingForSuperClasses() throws Exception { // Test that wildcard fields in super classes are mapped when there is no explicit super custom mapping definition - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); A src = getA(); B dest = mapper.map(src, B.class); @@ -148,7 +148,7 @@ public void testNoCustomMappingForSubclasses_CustomMappingForSuperClasses() thro @Test public void testGeneralInheritance() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); // first test mapping of sub and base class to a single class org.dozer.vo.inheritance.SubClass sub = newInstance(org.dozer.vo.inheritance.SubClass.class); @@ -163,7 +163,7 @@ public void testGeneralInheritance() throws Exception { @Test public void testGeneralInheritance2() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); // test base to base and sub to sub mapping with an intermediate on the destination AnotherSubClass asub = newInstance(AnotherSubClass.class); asub.setBaseAttribute("base"); @@ -239,7 +239,7 @@ public void testGeneralInheritance2() throws Exception { @Test public void testInheritanceWithAbstractClassOrInterfaceAsDestination() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); SpecificObject so = newInstance(SpecificObject.class); so.setSuperAttr1("superAttr1"); @@ -269,7 +269,7 @@ public void testInheritanceWithAbstractClassOrInterfaceAsDestination() throws Ex @Test public void testComplexSuperClassMapping() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); SubClass obj = testDataFactory.getSubClass(); SubClassPrime objPrime = mapper.map(obj, SubClassPrime.class); SubClass obj2 = mapper.map(objPrime, SubClass.class); @@ -326,7 +326,7 @@ public void testComplexSuperClassMapping() throws Exception { @Test public void testSuperClassMapping() throws Exception { // source object does not extend a base custom data object, but destination object extends a custom data object. - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); NoSuperClass src = newInstance(NoSuperClass.class); src.setAttribute("somefieldvalue"); src.setSuperAttribute("someotherfieldvalue"); diff --git a/core/src/test/java/org/dozer/functional_tests/JAXBBeansMappingTest.java b/core/src/test/java/org/dozer/functional_tests/JAXBBeansMappingTest.java index c1f1d14e2..e7022d809 100644 --- a/core/src/test/java/org/dozer/functional_tests/JAXBBeansMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/JAXBBeansMappingTest.java @@ -24,6 +24,7 @@ import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; import org.dozer.vo.TestObject; import org.dozer.vo.jaxb.employee.EmployeeWithInnerClass; @@ -46,7 +47,7 @@ public void setUp() throws Exception { @Test public void testTrivial() { - Class<?> type = MappingUtils.loadClass("org.dozer.vo.jaxb.employee.EmployeeType"); + Class<?> type = MappingUtils.loadClass("org.dozer.vo.jaxb.employee.EmployeeType", new BeanContainer()); assertNotNull(type); } diff --git a/core/src/test/java/org/dozer/functional_tests/MapTypeTest.java b/core/src/test/java/org/dozer/functional_tests/MapTypeTest.java index 4efba2db5..47b238a5d 100644 --- a/core/src/test/java/org/dozer/functional_tests/MapTypeTest.java +++ b/core/src/test/java/org/dozer/functional_tests/MapTypeTest.java @@ -225,7 +225,7 @@ public void testVoToMap_NoCustomMappings() throws Exception { @Test public void testMapToMap() throws Exception { - Mapper mapper = getMapper(new String[] {"mappings/mapInterfaceMapping.xml", "dozerBeanMapping.xml"}); + Mapper mapper = getMapper(new String[] {"mappings/mapInterfaceMapping.xml", "testDozerBeanMapping.xml"}); TestObject to = newInstance(TestObject.class); to.setOne("one"); TestObject to2 = newInstance(TestObject.class); @@ -250,7 +250,7 @@ public void testMapToMap() throws Exception { @Test public void testMapToMapExistingDestination() throws Exception { - Mapper mapper = getMapper(new String[] {"mappings/mapInterfaceMapping.xml", "dozerBeanMapping.xml"}); + Mapper mapper = getMapper(new String[] {"mappings/mapInterfaceMapping.xml", "testDozerBeanMapping.xml"}); TestObject to = newInstance(TestObject.class); to.setOne("one"); TestObject to2 = newInstance(TestObject.class); @@ -276,7 +276,7 @@ public void testMapToMapExistingDestination() throws Exception { @Test public void testPropertyClassLevelMap() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); PropertyToMap ptm = newInstance(PropertyToMap.class); ptm.setStringProperty("stringPropertyValue"); ptm.addStringProperty2("stringProperty2Value"); @@ -297,7 +297,7 @@ public void testPropertyClassLevelMap() throws Exception { @Test public void testPropertyClassLevelMap2() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); PropertyToMap ptm = newInstance(PropertyToMap.class); ptm.setStringProperty("stringPropertyValue"); ptm.addStringProperty2("stringProperty2Value"); @@ -310,7 +310,7 @@ public void testPropertyClassLevelMap2() throws Exception { @Test public void testPropertyClassLevelMapBack() throws Exception { // Map Back - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); Map<String, Object> map = newInstance(HashMap.class); map.put("stringProperty", "stringPropertyValue"); map.put("integerProperty", new Integer("567")); @@ -329,7 +329,7 @@ public void testPropertyClassLevelMapBack() throws Exception { @Test public void testPropertyToMap() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); PropertyToMap ptm = newInstance(PropertyToMap.class); ptm.setStringProperty("stringPropertyValue"); ptm.addStringProperty2("stringProperty2Value"); @@ -359,7 +359,7 @@ public void testPropertyToMap() throws Exception { @Test public void testPropertyToCustomMap() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); PropertyToMap ptm = newInstance(PropertyToMap.class); ptm.setStringProperty3("stringProperty3Value"); ptm.setStringProperty4("stringProperty4Value"); @@ -379,7 +379,7 @@ public void testPropertyToCustomMap() throws Exception { @Test public void testPropertyToClassLevelMap() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); MapTestObject mto = newInstance(MapTestObject.class); PropertyToMap ptm = newInstance(PropertyToMap.class); Map<String, String> map = newInstance(HashMap.class); @@ -428,7 +428,7 @@ public void testPropertyToClassLevelMap() throws Exception { @Test public void testPropertyToCustomClassLevelMap() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); MapTestObject mto = newInstance(MapTestObject.class); PropertyToMap ptm = newInstance(PropertyToMap.class); ptm.setStringProperty("stringPropertyValue"); diff --git a/core/src/test/java/org/dozer/functional_tests/MapWithCustomGetAndPutMethodTest.java b/core/src/test/java/org/dozer/functional_tests/MapWithCustomGetAndPutMethodTest.java index df1a0128c..8917c88e7 100644 --- a/core/src/test/java/org/dozer/functional_tests/MapWithCustomGetAndPutMethodTest.java +++ b/core/src/test/java/org/dozer/functional_tests/MapWithCustomGetAndPutMethodTest.java @@ -18,6 +18,7 @@ import java.util.HashMap; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.MappingException; import org.dozer.loader.api.BeanMappingBuilder; import org.dozer.loader.api.TypeDefinition; @@ -33,7 +34,7 @@ public class MapWithCustomGetAndPutMethodTest extends AbstractFunctionalTest { @Test public void testDefaultMapBehaviour_UseDefaultGetAndPutMethod() { - DozerBeanMapper defaultMapper = new DozerBeanMapper(); + DozerBeanMapper defaultMapper = DozerBeanMapperBuilder.buildDefault(); // Map to Object, should use "get" MapWithCustomGetAndPut input1 = MapWithCustomGetAndPut.createInput(); @@ -57,7 +58,7 @@ public void testDefaultMapBehaviour_UseDefaultGetAndPutMethod() { @Test public void testMapWithCustomMethods_UseSpecifiedMethods() { - DozerBeanMapper customMapper = new DozerBeanMapper(); + DozerBeanMapper customMapper = DozerBeanMapperBuilder.buildDefault(); customMapper.addMapping(new BeanMappingBuilder() { @Override protected void configure() { @@ -89,7 +90,7 @@ protected void configure() { @Test public void testMapWithNullGetAndPutMethods_FallbackToDefaultMethods() { - DozerBeanMapper nullMapper = new DozerBeanMapper(); + DozerBeanMapper nullMapper = DozerBeanMapperBuilder.buildDefault(); nullMapper.addMapping(new BeanMappingBuilder() { @Override protected void configure() { @@ -121,7 +122,7 @@ protected void configure() { @Test public void testMapWithEmptyGetAndPutMethods_FallbackToDefaultMethods() { - DozerBeanMapper emptyMapper = new DozerBeanMapper(); + DozerBeanMapper emptyMapper = DozerBeanMapperBuilder.buildDefault(); emptyMapper.addMapping(new BeanMappingBuilder() { @Override protected void configure() { @@ -157,7 +158,7 @@ protected void configure() { */ @Test(expected=MappingException.class) public void testMapWithInvalidGetMethod_ThrowsMappingException() { - DozerBeanMapper invalidMapper = new DozerBeanMapper(); + DozerBeanMapper invalidMapper = DozerBeanMapperBuilder.buildDefault(); invalidMapper.addMapping(new BeanMappingBuilder() { @Override protected void configure() { @@ -181,7 +182,7 @@ protected void configure() { */ @Test(expected=MappingException.class) public void testMapWithInvalidPutMethod_ThrowsMappingException() { - DozerBeanMapper invalidMapper = new DozerBeanMapper(); + DozerBeanMapper invalidMapper = DozerBeanMapperBuilder.buildDefault(); invalidMapper.addMapping(new BeanMappingBuilder() { @Override protected void configure() { diff --git a/core/src/test/java/org/dozer/functional_tests/MapperTest.java b/core/src/test/java/org/dozer/functional_tests/MapperTest.java index 7ed6313f2..5ae4ebab0 100755 --- a/core/src/test/java/org/dozer/functional_tests/MapperTest.java +++ b/core/src/test/java/org/dozer/functional_tests/MapperTest.java @@ -23,7 +23,7 @@ import java.util.Set; import org.apache.commons.lang3.SerializationUtils; -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.vo.Apple; import org.dozer.vo.Car; @@ -76,7 +76,7 @@ public class MapperTest extends AbstractFunctionalTest { @Override @Before public void setUp() throws Exception { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); } @Test @@ -111,7 +111,7 @@ public void testCustomGetterSetterMap() throws Exception { @Test public void testNoClassMappings() throws Exception { - Mapper mapper = new DozerBeanMapper(); + Mapper mapper = DozerBeanMapperBuilder.buildDefault(); // Should attempt mapping even though it is not in the beanmapping.xml file NoCustomMappingsObjectPrime dest1 = mapper.map(testDataFactory.getInputTestNoClassMappingsNoCustomMappingsObject(), NoCustomMappingsObjectPrime.class); diff --git a/core/src/test/java/org/dozer/functional_tests/MultiThreadedTest.java b/core/src/test/java/org/dozer/functional_tests/MultiThreadedTest.java index fea93c5f0..3f331807d 100644 --- a/core/src/test/java/org/dozer/functional_tests/MultiThreadedTest.java +++ b/core/src/test/java/org/dozer/functional_tests/MultiThreadedTest.java @@ -32,7 +32,7 @@ public class MultiThreadedTest extends AbstractFunctionalTest { @Override @Before public void setUp() throws Exception { - mapper = getMapper(new String[] {"dozerBeanMapping.xml"}); + mapper = getMapper(new String[] {"testDozerBeanMapping.xml"}); } /* diff --git a/core/src/test/java/org/dozer/functional_tests/PerformanceTest.java b/core/src/test/java/org/dozer/functional_tests/PerformanceTest.java index 42dfb2d1b..96b48c8bc 100755 --- a/core/src/test/java/org/dozer/functional_tests/PerformanceTest.java +++ b/core/src/test/java/org/dozer/functional_tests/PerformanceTest.java @@ -52,7 +52,7 @@ public class PerformanceTest extends AbstractFunctionalTest { @Before public void setUp() throws Exception { if (mapper == null) { - mapper = getMapper("dozerBeanMapping.xml"); + mapper = getMapper("testDozerBeanMapping.xml"); } } diff --git a/core/src/test/java/org/dozer/functional_tests/RecursiveInterfaceMappingTest.java b/core/src/test/java/org/dozer/functional_tests/RecursiveInterfaceMappingTest.java index 327ffbff4..6ffc2805a 100644 --- a/core/src/test/java/org/dozer/functional_tests/RecursiveInterfaceMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/RecursiveInterfaceMappingTest.java @@ -15,11 +15,9 @@ */ package org.dozer.functional_tests; -import java.util.ArrayList; import java.util.Iterator; -import java.util.List; -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.vo.interfacerecursion.User; import org.dozer.vo.interfacerecursion.UserGroup; @@ -67,9 +65,9 @@ public void testRecursiveInterfaceMapping() throws Exception { } // get mapper - List<String> mappingFiles = new ArrayList<String>(); - mappingFiles.add("mappings/interface-recursion-mappings.xml"); - Mapper mapper = new DozerBeanMapper(mappingFiles); + Mapper mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("mappings/interface-recursion-mappings.xml") + .build(); // do mapping UserGroupPrime userGroupPrime = null; diff --git a/core/src/test/java/org/dozer/functional_tests/SubclassReferenceTest.java b/core/src/test/java/org/dozer/functional_tests/SubclassReferenceTest.java index 8039bc60e..b21869e4c 100755 --- a/core/src/test/java/org/dozer/functional_tests/SubclassReferenceTest.java +++ b/core/src/test/java/org/dozer/functional_tests/SubclassReferenceTest.java @@ -15,9 +15,7 @@ */ package org.dozer.functional_tests; -import java.util.Arrays; - -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.vo.copybyreference.Reference; import org.dozer.vo.copybyreference.TestA; @@ -34,7 +32,9 @@ public class SubclassReferenceTest extends AbstractFunctionalTest { @Before public void setUp() { - mapper = new DozerBeanMapper(Arrays.asList(new String[] { getMappingFile() })); + mapper = DozerBeanMapperBuilder.create() + .withMappingFiles(getMappingFile()) + .build(); testA = newInstance(TestA.class); testA.setOne("one"); testA.setOneA("oneA"); diff --git a/core/src/test/java/org/dozer/functional_tests/VariablesTest.java b/core/src/test/java/org/dozer/functional_tests/VariablesTest.java index 01b976831..78799a659 100644 --- a/core/src/test/java/org/dozer/functional_tests/VariablesTest.java +++ b/core/src/test/java/org/dozer/functional_tests/VariablesTest.java @@ -18,15 +18,11 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.Set; - import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertTrue; - -import org.dozer.config.GlobalSettings; import org.dozer.functional_tests.runner.ProxyDataObjectInstantiator; + import org.junit.Before; import org.junit.Test; - import static org.junit.Assert.assertEquals; /** @@ -42,8 +38,6 @@ public void setUp() throws Exception { @Test public void testTest() { - assertTrue(GlobalSettings.getInstance().isElEnabled()); - Container<Child> source = new Container<Child>(); Container<ChildClone> destination = new Container<ChildClone>(); diff --git a/core/src/test/java/org/dozer/functional_tests/builder/CollectionWithNullTest.java b/core/src/test/java/org/dozer/functional_tests/builder/CollectionWithNullTest.java index f1e19e669..baeb329a6 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/CollectionWithNullTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/CollectionWithNullTest.java @@ -16,12 +16,12 @@ package org.dozer.functional_tests.builder; import java.util.ArrayList; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.DozerConverter; import org.dozer.loader.api.BeanMappingBuilder; import org.dozer.loader.api.TypeMappingOptions; @@ -44,7 +44,9 @@ public class CollectionWithNullTest extends Assert { @Before public void setUp() { - mapper = new DozerBeanMapper(Collections.singletonList("mappings/collectionsWithNull.xml")); + mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("mappings/collectionsWithNull.xml") + .build(); foo = new Foo(); bar = new Bar(); diff --git a/core/src/test/java/org/dozer/functional_tests/builder/DeepMappingWithMapIdTest.java b/core/src/test/java/org/dozer/functional_tests/builder/DeepMappingWithMapIdTest.java index 7922fbc85..26825d752 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/DeepMappingWithMapIdTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/DeepMappingWithMapIdTest.java @@ -23,6 +23,7 @@ import java.util.TreeSet; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.MappingProcessor; import org.dozer.classmap.RelationshipType; import org.dozer.loader.api.BeanMappingBuilder; @@ -60,7 +61,7 @@ public void testMappingListOfObjectsWithMapId() { Assert.assertNull(srcChild1.getLastName()); Assert.assertEquals(new Integer(1), srcChild1.getId()); - DozerBeanMapper mapper = new DozerBeanMapper(); + DozerBeanMapper mapper = DozerBeanMapperBuilder.buildDefault(); mapper.addMapping(getParentMapping(ParentWithChildList.class)); mapper.addMapping(getChildMapping()); mapper.map(src, dest, MAP_ID_PATENT); @@ -83,7 +84,7 @@ public void testMappingSetOfObjectsWithMapId() { Assert.assertEquals(new Integer(1), srcChild1.getId()); //Perform the mapping - DozerBeanMapper mapper = new DozerBeanMapper(); + DozerBeanMapper mapper = DozerBeanMapperBuilder.buildDefault(); mapper.addMapping(getParentMapping(ParentWithChildSet.class)); mapper.addMapping(getChildMapping()); mapper.map(src, dest, MAP_ID_PATENT); diff --git a/core/src/test/java/org/dozer/functional_tests/builder/DozerBuilderTest.java b/core/src/test/java/org/dozer/functional_tests/builder/DozerBuilderTest.java index 2de0ccafe..ab4a54138 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/DozerBuilderTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/DozerBuilderTest.java @@ -20,6 +20,7 @@ import org.dozer.CustomConverter; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.classmap.RelationshipType; import org.dozer.loader.api.BeanMappingBuilder; import org.dozer.loader.api.FieldsMappingOptions; @@ -50,7 +51,7 @@ public class DozerBuilderTest { @Before public void setUp() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); } @Test diff --git a/core/src/test/java/org/dozer/functional_tests/builder/GenericsTest.java b/core/src/test/java/org/dozer/functional_tests/builder/GenericsTest.java index 0bada2661..6522d9628 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/GenericsTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/GenericsTest.java @@ -19,11 +19,11 @@ import java.util.List; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.loader.api.BeanMappingBuilder; import org.junit.Assert; import org.junit.Before; import org.junit.Test; - import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @@ -36,7 +36,7 @@ public class GenericsTest extends Assert { @Before public void setUp() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); } diff --git a/core/src/test/java/org/dozer/functional_tests/builder/InheritanceTest.java b/core/src/test/java/org/dozer/functional_tests/builder/InheritanceTest.java index 8d98aed37..5396034bb 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/InheritanceTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/InheritanceTest.java @@ -16,6 +16,7 @@ package org.dozer.functional_tests.builder; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -32,7 +33,7 @@ public class InheritanceTest extends Assert { @Before public void setUp() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); source = new A(); source.property1 = "1"; diff --git a/core/src/test/java/org/dozer/functional_tests/builder/MapMappingTest.java b/core/src/test/java/org/dozer/functional_tests/builder/MapMappingTest.java index a1e6b92df..9defceeed 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/MapMappingTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/MapMappingTest.java @@ -26,6 +26,7 @@ import static junit.framework.Assert.assertNotSame; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.classmap.RelationshipType; import org.dozer.functional_tests.AbstractFunctionalTest; import org.dozer.loader.api.BeanMappingBuilder; @@ -47,7 +48,7 @@ public class MapMappingTest extends AbstractFunctionalTest { @Before public void setUp() { - beanMapper = new DozerBeanMapper(); + beanMapper = DozerBeanMapperBuilder.buildDefault(); source = new MapContainer(); target = new MapContainer(); } @@ -141,7 +142,7 @@ public void shouldMapTopLevel() { @Test public void testDozerMultiTypeMapContainingCollections() throws Exception { - DozerBeanMapper dozerBeanMapper = new DozerBeanMapper(); + DozerBeanMapper dozerBeanMapper = DozerBeanMapperBuilder.buildDefault(); // Setting up test data, multiple types in a single Map DozerExampleEntry entry = new DozerExampleEntry(); diff --git a/core/src/test/java/org/dozer/functional_tests/builder/MapNullTest.java b/core/src/test/java/org/dozer/functional_tests/builder/MapNullTest.java index e924d6952..e8739de6e 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/MapNullTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/MapNullTest.java @@ -16,6 +16,7 @@ package org.dozer.functional_tests.builder; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.functional_tests.AbstractFunctionalTest; import org.dozer.loader.api.BeanMappingBuilder; import org.dozer.loader.api.TypeMappingOptions; @@ -37,7 +38,7 @@ public class MapNullTest extends AbstractFunctionalTest { @Before public void setUp() { - beanMapper = new DozerBeanMapper(); + beanMapper = DozerBeanMapperBuilder.buildDefault(); source = new Source(); destination = new Destination(); } diff --git a/core/src/test/java/org/dozer/functional_tests/builder/PrimitiveTest.java b/core/src/test/java/org/dozer/functional_tests/builder/PrimitiveTest.java index 3d4ce342f..1f4a0523e 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/PrimitiveTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/PrimitiveTest.java @@ -20,6 +20,7 @@ import java.net.URL; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.loader.api.BeanMappingBuilder; import org.dozer.loader.api.TypeMappingOptions; import org.junit.Assert; @@ -35,7 +36,7 @@ public class PrimitiveTest extends Assert { @Before public void setUp() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); } @Test diff --git a/core/src/test/java/org/dozer/functional_tests/builder/SimpleTest.java b/core/src/test/java/org/dozer/functional_tests/builder/SimpleTest.java index 3b971549c..34eb1f8af 100644 --- a/core/src/test/java/org/dozer/functional_tests/builder/SimpleTest.java +++ b/core/src/test/java/org/dozer/functional_tests/builder/SimpleTest.java @@ -19,6 +19,7 @@ import java.util.Map; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.loader.api.BeanMappingBuilder; import org.junit.Assert; import org.junit.Before; @@ -33,8 +34,7 @@ public class SimpleTest extends Assert { @Before public void setUp() { - beanMapper = new DozerBeanMapper(); - + beanMapper = DozerBeanMapperBuilder.buildDefault(); } @Test diff --git a/core/src/test/java/org/dozer/functional_tests/mapperaware/CachingCustomConverterTest.java b/core/src/test/java/org/dozer/functional_tests/mapperaware/CachingCustomConverterTest.java index a702e25ce..6753c7e5d 100644 --- a/core/src/test/java/org/dozer/functional_tests/mapperaware/CachingCustomConverterTest.java +++ b/core/src/test/java/org/dozer/functional_tests/mapperaware/CachingCustomConverterTest.java @@ -24,6 +24,7 @@ import org.dozer.CustomConverter; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.DozerConverter; import org.dozer.Mapper; import org.dozer.MapperAware; @@ -40,7 +41,7 @@ public class CachingCustomConverterTest extends Assert { @Before public void setup() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); List<String> mappingFileUrls = new ArrayList<String>(); mappingFileUrls.add("mappings/mapper-aware.xml"); diff --git a/core/src/test/java/org/dozer/functional_tests/mapperaware/SecondUsingMapInternalTest.java b/core/src/test/java/org/dozer/functional_tests/mapperaware/SecondUsingMapInternalTest.java index 9a5bcff1d..3398915f4 100644 --- a/core/src/test/java/org/dozer/functional_tests/mapperaware/SecondUsingMapInternalTest.java +++ b/core/src/test/java/org/dozer/functional_tests/mapperaware/SecondUsingMapInternalTest.java @@ -22,6 +22,7 @@ import org.dozer.CustomConverter; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.MapperAware; import org.dozer.vo.mapperaware.MapperAwareSimpleDest; @@ -42,7 +43,7 @@ public class SecondUsingMapInternalTest { @Before public void setup() { - mapper = new DozerBeanMapper(); + mapper = DozerBeanMapperBuilder.buildDefault(); List<String> mappingFileUrls = new ArrayList<String>(); mappingFileUrls.add("mappings/mapper-aware.xml"); diff --git a/core/src/test/java/org/dozer/functional_tests/runner/JavassistDataObjectInstantiator.java b/core/src/test/java/org/dozer/functional_tests/runner/JavassistDataObjectInstantiator.java index bfee6ae58..a63e38d24 100644 --- a/core/src/test/java/org/dozer/functional_tests/runner/JavassistDataObjectInstantiator.java +++ b/core/src/test/java/org/dozer/functional_tests/runner/JavassistDataObjectInstantiator.java @@ -22,6 +22,7 @@ import javassist.util.proxy.ProxyFactory; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.functional_tests.DataObjectInstantiator; import org.dozer.util.MappingUtils; @@ -56,7 +57,7 @@ public <T> T newInstance(Class<T> classToInstantiate, Object[] args) { try { Class[] argTypes = new Class[args.length]; for (int i = 0; i < args.length; i++) { - argTypes[i] = MappingUtils.getRealClass(args[i].getClass()); + argTypes[i] = MappingUtils.getRealClass(args[i].getClass(), new BeanContainer()); } Constructor constructor = newClass.getDeclaredConstructor(argTypes); instance = constructor.newInstance(args); diff --git a/core/src/test/java/org/dozer/functional_tests/runner/ProxyDataObjectInstantiator.java b/core/src/test/java/org/dozer/functional_tests/runner/ProxyDataObjectInstantiator.java index 63a37ba10..e6aed7083 100644 --- a/core/src/test/java/org/dozer/functional_tests/runner/ProxyDataObjectInstantiator.java +++ b/core/src/test/java/org/dozer/functional_tests/runner/ProxyDataObjectInstantiator.java @@ -25,6 +25,7 @@ import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; +import org.dozer.config.BeanContainer; import org.dozer.functional_tests.DataObjectInstantiator; import org.dozer.util.MappingUtils; @@ -58,7 +59,7 @@ public <T> T newInstance(Class<T> classToInstantiate) { public <T> T newInstance(Class<T> classToInstantiate, Object[] args) { List<Class<?>> argTypes = new ArrayList<Class<?>>(); for (Object arg : args) { - argTypes.add(MappingUtils.getRealClass(arg.getClass())); + argTypes.add(MappingUtils.getRealClass(arg.getClass(), new BeanContainer())); } Enhancer enhancer = new Enhancer(); diff --git a/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory.java b/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory.java index db6e5a0cd..918219e1e 100644 --- a/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory.java +++ b/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory.java @@ -15,13 +15,15 @@ */ package org.dozer.functional_tests.support; +import org.dozer.config.BeanContainer; + /** * @author tierney.matt */ public class SampleCustomBeanFactory extends BaseSampleBeanFactory { - public Object createBean(Object srcObj, Class<?> srcObjClass, String id) { + public Object createBean(Object srcObj, Class<?> srcObjClass, String id, BeanContainer beanContainer) { try { Object rvalue = Class.forName(id).newInstance(); // just for unit testing. need something to indicate that it was created by the factory method diff --git a/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory2.java b/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory2.java index edb3f010a..ae675127b 100644 --- a/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory2.java +++ b/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory2.java @@ -15,6 +15,7 @@ */ package org.dozer.functional_tests.support; +import org.dozer.config.BeanContainer; import org.dozer.vo.InsideTestObject; import org.dozer.vo.InsideTestObjectPrime; @@ -23,7 +24,7 @@ */ public class SampleCustomBeanFactory2 extends BaseSampleBeanFactory { - public Object createBean(Object srcObj, Class<?> srcObjClass, String id) { + public Object createBean(Object srcObj, Class<?> srcObjClass, String id, BeanContainer beanContainer) { // example of using all input objects. These params are passed in from the // dozer mapping processor. diff --git a/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory3.java b/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory3.java index 2cb170db5..609f785c5 100644 --- a/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory3.java +++ b/core/src/test/java/org/dozer/functional_tests/support/SampleCustomBeanFactory3.java @@ -16,6 +16,7 @@ package org.dozer.functional_tests.support; import org.dozer.BeanFactory; +import org.dozer.config.BeanContainer; import org.dozer.vo.Car; @@ -27,7 +28,7 @@ */ public class SampleCustomBeanFactory3 implements BeanFactory { - public Object createBean(Object srcObj, Class<?> srcObjClass, String id) { + public Object createBean(Object srcObj, Class<?> srcObjClass, String id, BeanContainer beanContainer) { try { Object rvalue = Car.class.newInstance(); // return the interface diff --git a/core/src/test/java/org/dozer/functional_tests/support/SampleDefaultBeanFactory.java b/core/src/test/java/org/dozer/functional_tests/support/SampleDefaultBeanFactory.java index 1320a604a..4b52cd1f0 100644 --- a/core/src/test/java/org/dozer/functional_tests/support/SampleDefaultBeanFactory.java +++ b/core/src/test/java/org/dozer/functional_tests/support/SampleDefaultBeanFactory.java @@ -15,12 +15,14 @@ */ package org.dozer.functional_tests.support; +import org.dozer.config.BeanContainer; + /** * @author tierney.matt */ public class SampleDefaultBeanFactory extends BaseSampleBeanFactory { - public Object createBean(Object srcObj, Class<?> srcObjClass, String id) { + public Object createBean(Object srcObj, Class<?> srcObjClass, String id, BeanContainer beanContainer) { try { Class<?> destClass = Class.forName(id); Object rvalue = destClass.newInstance(); diff --git a/core/src/test/java/org/dozer/functional_tests/support/UserBeanFactory.java b/core/src/test/java/org/dozer/functional_tests/support/UserBeanFactory.java index 5f694d5a1..b38e51345 100644 --- a/core/src/test/java/org/dozer/functional_tests/support/UserBeanFactory.java +++ b/core/src/test/java/org/dozer/functional_tests/support/UserBeanFactory.java @@ -17,6 +17,7 @@ import org.dozer.BeanFactory; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.vo.interfacerecursion.User; import org.dozer.vo.interfacerecursion.UserGroup; import org.dozer.vo.interfacerecursion.UserGroupImpl; @@ -31,7 +32,7 @@ */ public class UserBeanFactory implements BeanFactory { - public Object createBean(Object aSrcObj, Class<?> aSrcObjClass, String aTargetBeanId) { + public Object createBean(Object aSrcObj, Class<?> aSrcObjClass, String aTargetBeanId, BeanContainer beanContainer) { // check null arguments if (aSrcObj == null || aSrcObjClass == null || aTargetBeanId == null) { return null; diff --git a/core/src/test/java/org/dozer/jmx/DozerAdminControllerTest.java b/core/src/test/java/org/dozer/jmx/DozerAdminControllerTest.java index 441cec209..04715cd6f 100644 --- a/core/src/test/java/org/dozer/jmx/DozerAdminControllerTest.java +++ b/core/src/test/java/org/dozer/jmx/DozerAdminControllerTest.java @@ -16,28 +16,36 @@ package org.dozer.jmx; import org.dozer.AbstractDozerTest; +import org.dozer.config.GlobalSettings; import org.dozer.util.DozerConstants; -import org.junit.Before; + +import org.junit.Rule; import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import static org.mockito.Mockito.verify; /** * @author tierney.matt */ public class DozerAdminControllerTest extends AbstractDozerTest { - private DozerAdminController controller; + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Override - @Before - public void setUp() throws Exception { - controller = new DozerAdminController(); - } + @Mock + private GlobalSettings globalSettingsMock; + + @InjectMocks + private DozerAdminController controller; @Test public void testSetStatisticsEnabled() throws Exception { boolean isStatisticsEnabled = controller.isStatisticsEnabled(); controller.setStatisticsEnabled(!isStatisticsEnabled); - assertEquals("statistics enabled value was not updated", !isStatisticsEnabled, controller.isStatisticsEnabled()); + verify(globalSettingsMock).setStatisticsEnabled(!isStatisticsEnabled); } @Test diff --git a/core/src/test/java/org/dozer/jmx/DozerStatisticsControllerTest.java b/core/src/test/java/org/dozer/jmx/DozerStatisticsControllerTest.java index 8dc35a084..cfa8df1e2 100644 --- a/core/src/test/java/org/dozer/jmx/DozerStatisticsControllerTest.java +++ b/core/src/test/java/org/dozer/jmx/DozerStatisticsControllerTest.java @@ -16,30 +16,41 @@ package org.dozer.jmx; import java.util.Set; - import org.dozer.AbstractDozerTest; +import org.dozer.config.GlobalSettings; import org.dozer.stats.StatisticType; -import org.junit.Before; +import org.dozer.stats.StatisticsManager; + +import org.junit.Rule; import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import static org.mockito.Mockito.verify; /** * @author tierney.matt */ public class DozerStatisticsControllerTest extends AbstractDozerTest { - private DozerStatisticsController controller; + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Override - @Before - public void setUp() throws Exception { - controller = new DozerStatisticsController(); - } + @Mock + private GlobalSettings globalSettingsMock; + + @Mock + private StatisticsManager statisticsManager; + + @InjectMocks + private DozerStatisticsController controller; @Test public void testIsStatisticsEnabled() throws Exception { boolean isStatisticsEnabled = controller.isStatisticsEnabled(); controller.setStatisticsEnabled(!isStatisticsEnabled); - assertEquals("statistics enabled value was not updated", !isStatisticsEnabled, controller.isStatisticsEnabled()); + verify(globalSettingsMock).setStatisticsEnabled(!isStatisticsEnabled); } @Test diff --git a/core/src/test/java/org/dozer/jmx/JMXPlatformImplTest.java b/core/src/test/java/org/dozer/jmx/JMXPlatformImplTest.java index 6bc71b78f..85cce846d 100644 --- a/core/src/test/java/org/dozer/jmx/JMXPlatformImplTest.java +++ b/core/src/test/java/org/dozer/jmx/JMXPlatformImplTest.java @@ -16,15 +16,20 @@ package org.dozer.jmx; import java.lang.management.ManagementFactory; - import javax.management.MBeanServer; import javax.management.ObjectName; - import org.dozer.AbstractDozerTest; +import org.dozer.config.GlobalSettings; + import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + /** * @author dmitry.buzdin */ @@ -32,6 +37,12 @@ public class JMXPlatformImplTest extends AbstractDozerTest { private static final String DOZER_ADMIN_CONTROLLER = "org.dozer.jmx:type=DozerAdminController"; + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Mock + private GlobalSettings globalSettingsMock; + private MBeanServer mbs; private JMXPlatformImpl platform; @@ -50,7 +61,7 @@ public void testAvailable() { public void testRegister() throws Exception { assertFalse(mbs.isRegistered(new ObjectName(DOZER_ADMIN_CONTROLLER))); - platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController()); + platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController(globalSettingsMock)); assertTrue(mbs.isRegistered(new ObjectName(DOZER_ADMIN_CONTROLLER))); platform.unregisterMBean(DOZER_ADMIN_CONTROLLER); @@ -59,8 +70,8 @@ public void testRegister() throws Exception { @Test public void testDoubleRegister() throws Exception { - platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController()); - platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController()); + platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController(globalSettingsMock)); + platform.registerMBean(DOZER_ADMIN_CONTROLLER, new DozerAdminController(globalSettingsMock)); } @Test diff --git a/core/src/test/java/org/dozer/jmxtest/JMXTestEngine.java b/core/src/test/java/org/dozer/jmxtest/JMXTestEngine.java index 0196c4fc6..4465e4037 100644 --- a/core/src/test/java/org/dozer/jmxtest/JMXTestEngine.java +++ b/core/src/test/java/org/dozer/jmxtest/JMXTestEngine.java @@ -15,10 +15,7 @@ */ package org.dozer.jmxtest; -import java.util.ArrayList; -import java.util.List; - -import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.Mapper; import org.dozer.functional_tests.runner.NoProxyDataObjectInstantiator; import org.dozer.functional_tests.support.TestDataFactory; @@ -46,9 +43,9 @@ public static void main(String[] args) throws Exception { } private static void performSomeMappings() { - List<String> mappingFiles = new ArrayList<String>(); - mappingFiles.add("dozerBeanMapping.xml"); - Mapper mapper = new DozerBeanMapper(mappingFiles); + Mapper mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("testDozerBeanMapping.xml") + .build(); try { mapper.map(new String("yo"), new String("y")); @@ -76,9 +73,9 @@ private static void performSomeMappings() { mapper.map(src, SimpleObjPrime2.class); } - mappingFiles = new ArrayList<String>(); - mappingFiles.add("mappings/arrayToStringCustomConverter.xml"); - mapper = new DozerBeanMapper(mappingFiles); + mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("mappings/arrayToStringCustomConverter.xml") + .build(); for (int i = 0; i < 6000; i++) { SimpleObj simple = new SimpleObj(); diff --git a/core/src/test/java/org/dozer/loader/CustomMappingsLoaderTest.java b/core/src/test/java/org/dozer/loader/CustomMappingsLoaderTest.java index 5e55abded..3e4e35169 100644 --- a/core/src/test/java/org/dozer/loader/CustomMappingsLoaderTest.java +++ b/core/src/test/java/org/dozer/loader/CustomMappingsLoaderTest.java @@ -23,9 +23,15 @@ import org.dozer.CustomConverter; import org.dozer.MappingException; import org.dozer.classmap.ClassMap; +import org.dozer.classmap.ClassMapBuilder; import org.dozer.classmap.Configuration; import org.dozer.classmap.MappingFileData; +import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.config.BeanContainer; import org.dozer.converters.CustomConverterDescription; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Before; import org.junit.Test; @@ -38,7 +44,11 @@ public class CustomMappingsLoaderTest extends AbstractDozerTest{ @Before public void setUp() { - loader = new CustomMappingsLoader(); + BeanContainer beanContainer = new BeanContainer(); + DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + PropertyDescriptorFactory propertyDescriptorFactory = new PropertyDescriptorFactory(); + loader = new CustomMappingsLoader(new MappingsParser(beanContainer, destBeanCreator, propertyDescriptorFactory), + new ClassMapBuilder(beanContainer, destBeanCreator, new BeanMappingGenerator(beanContainer, destBeanCreator, propertyDescriptorFactory), propertyDescriptorFactory), beanContainer); data = new ArrayList<MappingFileData>(); } diff --git a/core/src/test/java/org/dozer/loader/MappingsBuilderTest.java b/core/src/test/java/org/dozer/loader/MappingsBuilderTest.java index c8ab910c7..15c8b7bc1 100644 --- a/core/src/test/java/org/dozer/loader/MappingsBuilderTest.java +++ b/core/src/test/java/org/dozer/loader/MappingsBuilderTest.java @@ -17,6 +17,10 @@ import org.dozer.AbstractDozerTest; import org.dozer.classmap.MappingFileData; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Test; /** @@ -24,9 +28,12 @@ */ public class MappingsBuilderTest extends AbstractDozerTest{ + private BeanContainer beanContainer = new BeanContainer(); + private DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + @Test public void testBuild() { - DozerBuilder builder = new DozerBuilder(); + DozerBuilder builder = new DozerBuilder(beanContainer, destBeanCreator, new PropertyDescriptorFactory()); MappingFileData result = builder.build(); assertNotNull(result); } diff --git a/core/src/test/java/org/dozer/loader/MappingsParserTest.java b/core/src/test/java/org/dozer/loader/MappingsParserTest.java index 1ed9a79a0..9f300155a 100644 --- a/core/src/test/java/org/dozer/loader/MappingsParserTest.java +++ b/core/src/test/java/org/dozer/loader/MappingsParserTest.java @@ -19,8 +19,13 @@ import org.dozer.classmap.ClassMappings; import org.dozer.classmap.Configuration; import org.dozer.classmap.MappingFileData; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.loader.xml.MappingFileReader; +import org.dozer.loader.xml.XMLParser; import org.dozer.loader.xml.XMLParserFactory; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Before; import org.junit.Test; @@ -30,16 +35,22 @@ public class MappingsParserTest extends AbstractDozerTest { private MappingsParser parser; + private BeanContainer beanContainer; + private DestBeanCreator destBeanCreator; + private PropertyDescriptorFactory propertyDescriptorFactory; @Override @Before public void setUp() throws Exception { - parser = MappingsParser.getInstance(); + beanContainer = new BeanContainer(); + destBeanCreator = new DestBeanCreator(beanContainer); + propertyDescriptorFactory = new PropertyDescriptorFactory(); + parser = new MappingsParser(beanContainer, destBeanCreator, propertyDescriptorFactory); } @Test(expected=IllegalArgumentException.class) public void testDuplicateMapIds() throws Exception { - MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); + MappingFileReader fileReader = new MappingFileReader(new XMLParserFactory(beanContainer), new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory), beanContainer); MappingFileData mappingFileData = fileReader.read("mappings/duplicateMapIdsMapping.xml"); parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); @@ -48,7 +59,7 @@ public void testDuplicateMapIds() throws Exception { @Test(expected=IllegalArgumentException.class) public void testDetectDuplicateMapping() throws Exception { - MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); + MappingFileReader fileReader = new MappingFileReader(new XMLParserFactory(beanContainer), new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory), beanContainer); MappingFileData mappingFileData = fileReader.read("mappings/duplicateMapping.xml"); parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); fail("should have thrown exception"); diff --git a/core/src/test/java/org/dozer/loader/xml/DozerResolverTest.java b/core/src/test/java/org/dozer/loader/xml/DozerResolverTest.java index 716bad028..7d80e323b 100644 --- a/core/src/test/java/org/dozer/loader/xml/DozerResolverTest.java +++ b/core/src/test/java/org/dozer/loader/xml/DozerResolverTest.java @@ -18,6 +18,8 @@ import org.xml.sax.InputSource; import org.dozer.AbstractDozerTest; +import org.dozer.config.BeanContainer; + import org.junit.Before; import org.junit.Test; @@ -30,7 +32,7 @@ public class DozerResolverTest extends AbstractDozerTest { @Before public void setUp() throws Exception { - dozerResolver = new DozerResolver(); + dozerResolver = new DozerResolver(new BeanContainer()); } @Test diff --git a/core/src/test/java/org/dozer/loader/xml/MappingStreamReaderTest.java b/core/src/test/java/org/dozer/loader/xml/MappingStreamReaderTest.java index cf0ae0f8d..7d54ed5e6 100644 --- a/core/src/test/java/org/dozer/loader/xml/MappingStreamReaderTest.java +++ b/core/src/test/java/org/dozer/loader/xml/MappingStreamReaderTest.java @@ -19,6 +19,10 @@ import java.io.InputStream; import org.dozer.classmap.MappingFileData; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Before; import org.junit.Test; @@ -34,12 +38,15 @@ public class MappingStreamReaderTest { @Before public void setUp() throws Exception { - streamReader = new MappingStreamReader(XMLParserFactory.getInstance()); + BeanContainer beanContainer = new BeanContainer(); + DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + PropertyDescriptorFactory propertyDescriptorFactory = new PropertyDescriptorFactory(); + streamReader = new MappingStreamReader(new XMLParserFactory(beanContainer), new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory)); } @Test public void loadFromStreamTest() throws IOException { - InputStream xmlStream = getClass().getClassLoader().getResourceAsStream("dozerBeanMapping.xml"); + InputStream xmlStream = getClass().getClassLoader().getResourceAsStream("testDozerBeanMapping.xml"); MappingFileData data = streamReader.read(xmlStream); xmlStream.close(); diff --git a/core/src/test/java/org/dozer/loader/xml/MappingStreamReader_WithExceptionsLoggedTest.java b/core/src/test/java/org/dozer/loader/xml/MappingStreamReader_WithExceptionsLoggedTest.java index 64b4d65e0..4d84402c4 100644 --- a/core/src/test/java/org/dozer/loader/xml/MappingStreamReader_WithExceptionsLoggedTest.java +++ b/core/src/test/java/org/dozer/loader/xml/MappingStreamReader_WithExceptionsLoggedTest.java @@ -17,6 +17,10 @@ import java.io.IOException; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; + import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -34,7 +38,9 @@ public class MappingStreamReader_WithExceptionsLoggedTest { @Before public void setUp() throws Exception { - streamReader = new MappingStreamReader(XMLParserFactory.getInstance()); + BeanContainer beanContainer = new BeanContainer(); + DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + streamReader = new MappingStreamReader(new XMLParserFactory(beanContainer), new XMLParser(beanContainer, destBeanCreator, new PropertyDescriptorFactory())); } @Test diff --git a/core/src/test/java/org/dozer/loader/xml/XMLParserTest.java b/core/src/test/java/org/dozer/loader/xml/XMLParserTest.java index efacbee71..bdddb00ef 100644 --- a/core/src/test/java/org/dozer/loader/xml/XMLParserTest.java +++ b/core/src/test/java/org/dozer/loader/xml/XMLParserTest.java @@ -23,8 +23,11 @@ import org.dozer.AbstractDozerTest; import org.dozer.classmap.ClassMap; import org.dozer.classmap.MappingFileData; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; import org.dozer.loader.MappingsSource; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.util.ResourceLoader; import org.junit.Before; import org.junit.Test; @@ -37,18 +40,24 @@ public class XMLParserTest extends AbstractDozerTest { MappingsSource<Document> parser; ResourceLoader loader; + BeanContainer beanContainer; + DestBeanCreator destBeanCreator; + PropertyDescriptorFactory propertyDescriptorFactory; @Before public void setUp() { loader = new ResourceLoader(getClass().getClassLoader()); + beanContainer = new BeanContainer(); + destBeanCreator = new DestBeanCreator(beanContainer); + propertyDescriptorFactory = new PropertyDescriptorFactory(); } @Test public void testParse() throws Exception { - URL url = loader.getResource("dozerBeanMapping.xml"); + URL url = loader.getResource("testDozerBeanMapping.xml"); - Document document = XMLParserFactory.getInstance().createParser().parse(url.openStream()); - parser = new XMLParser(); + Document document = new XMLParserFactory(beanContainer).createParser().parse(url.openStream()); + parser = new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory); MappingFileData mappings = parser.read(document); assertNotNull(mappings); @@ -62,8 +71,8 @@ public void testParse() throws Exception { public void testParseCustomConverterParam() throws Exception { URL url = loader.getResource("mappings/fieldCustomConverterParam.xml"); - Document document = XMLParserFactory.getInstance().createParser().parse(url.openStream()); - parser = new XMLParser(); + Document document = new XMLParserFactory(beanContainer).createParser().parse(url.openStream()); + parser = new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory); MappingFileData mappings = parser.read(document); diff --git a/core/src/test/java/org/dozer/propertydescriptor/FieldPropertyDescriptorTest.java b/core/src/test/java/org/dozer/propertydescriptor/FieldPropertyDescriptorTest.java index 009591863..73b0c1436 100644 --- a/core/src/test/java/org/dozer/propertydescriptor/FieldPropertyDescriptorTest.java +++ b/core/src/test/java/org/dozer/propertydescriptor/FieldPropertyDescriptorTest.java @@ -20,6 +20,8 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; import org.junit.Test; @@ -30,15 +32,17 @@ */ public class FieldPropertyDescriptorTest extends AbstractDozerTest { + private DestBeanCreator destBeanCreator = new DestBeanCreator(new BeanContainer()); + @Test(expected = MappingException.class) public void testNoSuchField() { - new FieldPropertyDescriptor(String.class, "nosuchfield", false, 0, null, null); + new FieldPropertyDescriptor(String.class, "nosuchfield", false, 0, null, null, destBeanCreator); fail(); } @Test public void testConstructor() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "hidden", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "hidden", false, 0, null, null, destBeanCreator); assertNotNull(descriptor); assertEquals(Integer.TYPE, descriptor.getPropertyType()); assertNotNull(descriptor.getPropertyValue(new Container())); @@ -46,33 +50,33 @@ public void testConstructor() { @Test public void getPropertyType() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "hidden", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "hidden", false, 0, null, null, destBeanCreator); assertEquals(Integer.TYPE, descriptor.getPropertyType()); } @Test public void getPropertyTypeChained() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null, destBeanCreator); assertEquals(String.class, descriptor.getPropertyType()); } @Test public void getPropertyValue() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "hidden", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "hidden", false, 0, null, null, destBeanCreator); Object result = descriptor.getPropertyValue(new Container()); assertEquals(42, result); } @Test public void getPropertyValueChained() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.hidden", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.hidden", false, 0, null, null, destBeanCreator); Object result = descriptor.getPropertyValue(new Container("A")); assertEquals(42, result); } @Test public void setPropertyValue() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "value", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "value", false, 0, null, null, destBeanCreator); Container bean = new Container("A"); descriptor.setPropertyValue(bean, "B", mock(FieldMap.class)); assertEquals("B", bean.value); @@ -80,7 +84,7 @@ public void setPropertyValue() { @Test public void setPropertyValueChained() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null, destBeanCreator); Container bean = new Container(""); bean.container = new Container(""); @@ -91,7 +95,7 @@ public void setPropertyValueChained() { @Test public void setPropertyValueChained_ThirdLevel() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.container.value", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.container.value", false, 0, null, null, destBeanCreator); Container bean = new Container("X"); bean.container = new Container("X"); bean.container.container = new Container("X"); @@ -103,7 +107,7 @@ public void setPropertyValueChained_ThirdLevel() { @Test public void setPropertyValueChained_IntermediateNull() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null, destBeanCreator); Container bean = new Container(""); descriptor.setPropertyValue(bean, "A", mock(FieldMap.class)); @@ -113,7 +117,7 @@ public void setPropertyValueChained_IntermediateNull() { @Test public void getPropertyValueChained_IntermediateNull() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "container.value", false, 0, null, null, destBeanCreator); Container bean = new Container(""); Object value = descriptor.getPropertyValue(bean); assertEquals("", value); @@ -121,7 +125,7 @@ public void getPropertyValueChained_IntermediateNull() { @Test public void getPropertyValueIndexed() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "values", true, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "values", true, 0, null, null, destBeanCreator); Container container = new Container(""); container.values.add("A"); Object value = descriptor.getPropertyValue(container); @@ -130,7 +134,7 @@ public void getPropertyValueIndexed() { @Test public void setPropertyValueIndexed() { - FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "values", true, 0, null, null); + FieldPropertyDescriptor descriptor = new FieldPropertyDescriptor(Container.class, "values", true, 0, null, null, destBeanCreator); Container container = new Container(""); descriptor.setPropertyValue(container, "A", mock(FieldMap.class)); assertEquals(1, container.values.size()); diff --git a/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorTest.java b/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorTest.java index 5ab77c623..4938a77fd 100644 --- a/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorTest.java +++ b/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorTest.java @@ -19,6 +19,8 @@ import java.lang.reflect.Method; import org.dozer.AbstractDozerTest; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.DozerField; import org.dozer.vo.deep2.Dest; import org.junit.Before; @@ -35,8 +37,10 @@ public class GetterSetterPropertyDescriptorTest extends AbstractDozerTest { public void setup() { DozerField dozerField = new DozerField("destField", "generic"); + BeanContainer beanContainer = new BeanContainer(); + DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); this.javaBeanPropertyDescriptor = new JavaBeanPropertyDescriptor( - Dest.class, dozerField.getName(), dozerField.isIndexed(), dozerField.getIndex(), null, null); + Dest.class, dozerField.getName(), dozerField.isIndexed(), dozerField.getIndex(), null, null, beanContainer, destBeanCreator); } @Test diff --git a/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorWithGenericSuperClassTest.java b/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorWithGenericSuperClassTest.java index eef06c686..7daef5c04 100644 --- a/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorWithGenericSuperClassTest.java +++ b/core/src/test/java/org/dozer/propertydescriptor/GetterSetterPropertyDescriptorWithGenericSuperClassTest.java @@ -16,6 +16,8 @@ package org.dozer.propertydescriptor; import org.dozer.AbstractDozerTest; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.DozerField; import org.dozer.vo.deep3.Dest; import org.dozer.vo.deep3.NestedDest; @@ -32,8 +34,9 @@ public class GetterSetterPropertyDescriptorWithGenericSuperClassTest extends Abs public void testGetReadMethod() throws Exception { DozerField dozerField = new DozerField("nestedList", "generic"); - JavaBeanPropertyDescriptor pd = new JavaBeanPropertyDescriptor(Dest.class, dozerField.getName(), dozerField.isIndexed(), - dozerField.getIndex(), null, null); + BeanContainer beanContainer = new BeanContainer(); + JavaBeanPropertyDescriptor pd = new JavaBeanPropertyDescriptor(Dest.class, dozerField.getName(), dozerField.isIndexed(), + dozerField.getIndex(), null, null, beanContainer, new DestBeanCreator(beanContainer)); Class<?> clazz = pd.genericType(); assertNotNull("clazz should not be null", clazz); diff --git a/core/src/test/java/org/dozer/propertydescriptor/MapPropertyDescriptorTest.java b/core/src/test/java/org/dozer/propertydescriptor/MapPropertyDescriptorTest.java index 0eb882175..d614cc064 100644 --- a/core/src/test/java/org/dozer/propertydescriptor/MapPropertyDescriptorTest.java +++ b/core/src/test/java/org/dozer/propertydescriptor/MapPropertyDescriptorTest.java @@ -20,6 +20,9 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; + import org.junit.Before; import org.junit.Test; @@ -30,10 +33,14 @@ public class MapPropertyDescriptorTest extends AbstractDozerTest { private MapPropertyDescriptor descriptor; + private BeanContainer beanContainer; + private DestBeanCreator destBeanCreator; @Before public void setUp() throws Exception { - descriptor = new MapPropertyDescriptor(MapStructure.class, "", false, 0, "set", "get", "key", null, null); + beanContainer = new BeanContainer(); + destBeanCreator = new DestBeanCreator(beanContainer); + descriptor = new MapPropertyDescriptor(MapStructure.class, "", false, 0, "set", "get", "key", null, null, beanContainer, destBeanCreator); } @Test @@ -45,7 +52,7 @@ public void testGetWriteMethod() throws NoSuchMethodException { @Test(expected=MappingException.class) public void testGetWriteMethod_NotFound() throws NoSuchMethodException { - descriptor = new MapPropertyDescriptor(MapStructure.class, "", false, 0, "missing_set", "get", "key", null, null); + descriptor = new MapPropertyDescriptor(MapStructure.class, "", false, 0, "missing_set", "get", "key", null, null, beanContainer, destBeanCreator); descriptor.getWriteMethod(); fail(); } diff --git a/core/src/test/java/org/dozer/stats/StatisticManagerTest.java b/core/src/test/java/org/dozer/stats/StatisticManagerTest.java index 2937aec60..0dea6d141 100644 --- a/core/src/test/java/org/dozer/stats/StatisticManagerTest.java +++ b/core/src/test/java/org/dozer/stats/StatisticManagerTest.java @@ -17,10 +17,12 @@ import java.util.HashSet; import java.util.Set; - import org.dozer.AbstractDozerTest; +import org.dozer.config.GlobalSettings; + import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; /** * @author tierney.matt @@ -31,7 +33,7 @@ public class StatisticManagerTest extends AbstractDozerTest { @Override @Before public void setUp() throws Exception { - statMgr = new StatisticsManagerImpl(); + statMgr = new StatisticsManagerImpl(Mockito.mock(GlobalSettings.class)); statMgr.setStatisticsEnabled(true); } diff --git a/core/src/test/java/org/dozer/util/MappingUtilsTest.java b/core/src/test/java/org/dozer/util/MappingUtilsTest.java index de3ef19b1..1d610c515 100755 --- a/core/src/test/java/org/dozer/util/MappingUtilsTest.java +++ b/core/src/test/java/org/dozer/util/MappingUtilsTest.java @@ -27,10 +27,14 @@ import org.dozer.MappingException; import org.dozer.classmap.ClassMap; import org.dozer.classmap.MappingFileData; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.functional_tests.runner.ProxyDataObjectInstantiator; import org.dozer.loader.MappingsParser; import org.dozer.loader.xml.MappingFileReader; +import org.dozer.loader.xml.XMLParser; import org.dozer.loader.xml.XMLParserFactory; +import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.vo.enumtest.DestType; import org.dozer.vo.enumtest.DestTypeWithOverride; import org.dozer.vo.enumtest.SrcType; @@ -53,6 +57,10 @@ */ public class MappingUtilsTest extends AbstractDozerTest { + private BeanContainer beanContainer = new BeanContainer(); + private DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + private PropertyDescriptorFactory propertyDescriptorFactory = new PropertyDescriptorFactory(); + @Test public void testIsBlankOrNull() throws Exception { assertTrue(MappingUtils.isBlankOrNull(null)); @@ -62,9 +70,9 @@ public void testIsBlankOrNull() throws Exception { @Test public void testOverridenFields() throws Exception { - MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); + MappingFileReader fileReader = new MappingFileReader(new XMLParserFactory(beanContainer), new XMLParser(beanContainer, destBeanCreator, propertyDescriptorFactory), beanContainer); MappingFileData mappingFileData = fileReader.read("mappings/overridemapping.xml"); - MappingsParser mappingsParser = MappingsParser.getInstance(); + MappingsParser mappingsParser = new MappingsParser(beanContainer, destBeanCreator, propertyDescriptorFactory); mappingsParser.processMappings(mappingFileData.getClassMaps(), mappingFileData.getConfiguration()); // validate class mappings for (ClassMap classMap : mappingFileData.getClassMaps()) { @@ -113,14 +121,14 @@ public void testThrowMappingException_CheckedException() { @Test public void testGetRealClass() { Object proxyObj = ProxyDataObjectInstantiator.INSTANCE.newInstance(ArrayList.class); - assertEquals(ArrayList.class, MappingUtils.getRealClass(proxyObj.getClass())); - assertEquals(ArrayList.class, MappingUtils.getRealClass(ArrayList.class)); + assertEquals(ArrayList.class, MappingUtils.getRealClass(proxyObj.getClass(), beanContainer)); + assertEquals(ArrayList.class, MappingUtils.getRealClass(ArrayList.class, beanContainer)); } @Test public void testGetRealClass_CGLIBTarget() { Object proxyObj = ProxyDataObjectInstantiator.INSTANCE.newInstance(new Class[] {List.class}, new ArrayList()); - assertSame(proxyObj.getClass(), MappingUtils.getRealClass(proxyObj.getClass())); + assertSame(proxyObj.getClass(), MappingUtils.getRealClass(proxyObj.getClass(), beanContainer)); } @Test @@ -205,9 +213,9 @@ public void testIsEnum() { @Test public void testLoadClass() { - assertNotNull(MappingUtils.loadClass("java.lang.String")); - assertNotNull(MappingUtils.loadClass("java.lang.String[]")); - assertNotNull(MappingUtils.loadClass("[Ljava.lang.String;")); + assertNotNull(MappingUtils.loadClass("java.lang.String", beanContainer)); + assertNotNull(MappingUtils.loadClass("java.lang.String[]", beanContainer)); + assertNotNull(MappingUtils.loadClass("[Ljava.lang.String;", beanContainer)); } @Test @@ -225,7 +233,7 @@ public void testGetDeepInterfaces() { } public void testGetDeepInterfaces(Class<?> classToTest, Class<?>... expectedInterfaces) { - List<Class<?>> result = MappingUtils.getInterfaceHierarchy(classToTest); + List<Class<?>> result = MappingUtils.getInterfaceHierarchy(classToTest, beanContainer); List<Class<?>> expected = Arrays.asList(expectedInterfaces); assertEquals(expected, result); @@ -242,7 +250,7 @@ public void testGetSuperClasses() { } public void testGetSuperClasses(Class<?> classToTest, Class<?>... expectedClasses) { - List<Class<?>> result = MappingUtils.getSuperClassesAndInterfaces(classToTest); + List<Class<?>> result = MappingUtils.getSuperClassesAndInterfaces(classToTest, beanContainer); List<Class<?>> expected = Arrays.asList(expectedClasses); assertEquals(expected, result); diff --git a/core/src/test/java/org/dozer/util/MappingValidatorTest.java b/core/src/test/java/org/dozer/util/MappingValidatorTest.java index 1262a12d2..325f155eb 100644 --- a/core/src/test/java/org/dozer/util/MappingValidatorTest.java +++ b/core/src/test/java/org/dozer/util/MappingValidatorTest.java @@ -17,6 +17,8 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; + import org.junit.Test; /** @@ -24,6 +26,8 @@ */ public class MappingValidatorTest extends AbstractDozerTest { + private BeanContainer beanContainer = new BeanContainer(); + @Test(expected = MappingException.class) public void testValidateMappingRequest_NullSrcObj() throws Exception { MappingValidator.validateMappingRequest(null); @@ -51,12 +55,12 @@ public void testValidateMappingRequest_OK() throws Exception { @Test(expected = MappingException.class) public void testValidtateMappingURL_InvalidFileName() throws Exception{ - MappingValidator.validateURL("hello"); + MappingValidator.validateURL("hello", beanContainer); } @Test(expected = MappingException.class) public void testValidtateMappingURL_NullFileName() throws Exception{ - MappingValidator.validateURL(null); + MappingValidator.validateURL(null, beanContainer); } } diff --git a/core/src/test/java/org/dozer/util/ReflectionUtilsTest.java b/core/src/test/java/org/dozer/util/ReflectionUtilsTest.java index 46a87bfc6..fef8fa78e 100644 --- a/core/src/test/java/org/dozer/util/ReflectionUtilsTest.java +++ b/core/src/test/java/org/dozer/util/ReflectionUtilsTest.java @@ -25,6 +25,7 @@ import org.dozer.AbstractDozerTest; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.vo.A; import org.dozer.vo.B; import org.dozer.vo.NoReadMethod; @@ -42,6 +43,8 @@ */ public class ReflectionUtilsTest extends AbstractDozerTest { + private BeanContainer beanContainer = new BeanContainer(); + @Test(expected = MappingException.class) public void testGetMethod_NotFound() throws Exception { SimpleObj src = new SimpleObj(); @@ -151,25 +154,25 @@ public void shouldFailWhenFieldMissing() { @Test public void shouldThrowNoSuchMethodFound() throws NoSuchMethodException { - Method result = ReflectionUtils.findAMethod(TestClass.class, "getC()"); + Method result = ReflectionUtils.findAMethod(TestClass.class, "getC()", beanContainer); assertThat(result, notNullValue()); } @Test public void shouldThrowNoSuchMethodFound_NoBrackets() throws NoSuchMethodException { - Method result = ReflectionUtils.findAMethod(TestClass.class, "getC"); + Method result = ReflectionUtils.findAMethod(TestClass.class, "getC", beanContainer); assertThat(result, notNullValue()); } @Test(expected = NoSuchMethodException.class) public void shouldThrowNoSuchMethodFound_Missing() throws Exception { - ReflectionUtils.findAMethod(TestClass.class, "noSuchMethod()"); + ReflectionUtils.findAMethod(TestClass.class, "noSuchMethod()", beanContainer); fail(); } @Test(expected = NoSuchMethodException.class) public void shouldThrowNoSuchMethodFound_MissingNoBrackets() throws Exception { - ReflectionUtils.findAMethod(TestClass.class, "noSuchMethod"); + ReflectionUtils.findAMethod(TestClass.class, "noSuchMethod", beanContainer); fail(); } diff --git a/core/src/test/resources/dozerBeanMapping.xml b/core/src/test/resources/testDozerBeanMapping.xml similarity index 97% rename from core/src/test/resources/dozerBeanMapping.xml rename to core/src/test/resources/testDozerBeanMapping.xml index 520d30e59..9c1e58ed8 100755 --- a/core/src/test/resources/dozerBeanMapping.xml +++ b/core/src/test/resources/testDozerBeanMapping.xml @@ -1,770 +1,770 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - - Copyright 2005-2017 Dozer Project - - 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. - ---> -<mappings xmlns="http://dozermapper.github.io/schema/bean-mapping" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping http://dozermapper.github.io/schema/bean-mapping.xsd"> - - <configuration> - <stop-on-errors>true</stop-on-errors> - <date-format>MM/dd/yyyy HH:mm</date-format><!-- default dateformat will apply to all class maps unless the class mapping explicitly overrides it --> - <wildcard>true</wildcard><!-- default wildcard policy that will apply to all class maps unless the class mapping explicitly overrides it --> - <custom-converters><!-- these are always considered bi-directional --> - <converter type="org.dozer.functional_tests.support.TestCustomConverter"> - <class-a>org.dozer.vo.CustomDoubleObjectIF</class-a> - <class-b>java.lang.Double</class-b> - </converter> - <!-- this is a top level custom mapping. You are responsible for mapping everything between class-a and class-b --> - <converter type="org.dozer.functional_tests.support.TestCustomHashMapConverter"> - <!-- keep the carriage returns...this tests parsing the xml --> - <class-a>org.dozer.vo.TestCustomConverterHashMapObject</class-a> - <class-b>org.dozer.vo.TestCustomConverterHashMapPrimeObject</class-b> - </converter> - <!-- testing converters with hints --> - <converter type="org.dozer.functional_tests.support.HintedOnlyConverter"> - <class-a>org.dozer.vo.HintedOnly</class-a> - <class-b>java.lang.String</class-b> - </converter> - </custom-converters> - <copy-by-references> - <copy-by-reference>org.dozer.vo.NoExtendBaseObjectGlobalCopyByReference</copy-by-reference> - </copy-by-references> - </configuration> - - <mapping wildcard="true" date-format="MM-dd-yyyy HH:mm:ss"><!-- Override top level date format default. Defaults to wildcard = true. this means that any properties the same name between classes it will implicitly copy --> - <class-a>org.dozer.vo.TestObject</class-a> - <class-b>org.dozer.vo.TestObjectPrime</class-b> - <field-exclude> - <a>excludeMe</a> - <b>excludeMe</b> - </field-exclude> - <field-exclude type="one-way"> - <a>excludeMeOneWay</a> - <b>excludeMeOneWay</b> - </field-exclude> - <field> - <a>carMetalThingy</a> - <b>vanMetalThingy</b> - <a-hint>org.dozer.vo.Car</a-hint> - <b-hint>org.dozer.vo.Van</b-hint> - </field> - <field> - <a>anotherLongValue</a> - <b>theLongValue</b> - </field> - <field> - <a>primArray</a> - <b>primitiveArray</b> - </field> - <field> - <a>one</a><!-- converting String to String by name only --> - <b>onePrime</b> - </field> - <field> - <a>two</a><!-- converting Integer to Integer by name only --> - <b>twoPrime</b> - </field> - <field> - <a>three</a><!-- converting by name and type InsideTestObject to InsideTestObjectPrime (actually this object is in the second <mapping> below --> - <b>threePrime</b> - </field> - <field> - <a date-format="MM/dd/yyyy HH:mm:ss:SS">dateStr</a><!-- converting from String to Date using date-format. Override class mapping date format--> - <b>dateFromStr</b> - </field> - <field> - <a>theMappedPrimitive</a><!-- converting int to int by name only --> - <b>anotherPrimitive</b> - </field> - <field> - <a>anArray</a><!-- converting int[] to int [] by name only --> - <b>theMappedArray</b> - </field> - <field relationship-type="non-cumulative"> - <a>unequalNamedList</a><!-- converting String List to String List by name only --> - <b>theMappedUnequallyNamedList</b> - </field> - <field> - <a>arrayForLists</a><!-- changing an Integer [] to List and back again --> - <b>listForArray</b> - <b-hint>java.lang.Integer</b-hint> - </field> - <field relationship-type="cumulative"> - <a>hintList</a><!-- converting TheFirstSubClass List to TheFirstSubClassPrime List --> - <b>hintList</b> - <a-hint>org.dozer.vo.TheFirstSubClass</a-hint> - <b-hint>org.dozer.vo.TheFirstSubClassPrime</b-hint> - </field> - <field copy-by-reference="true"> - <a>copyByReference</a> - <b>copyByReferencePrime</b> - </field> - <field copy-by-reference="true"> - <a>copyByReferenceDeep</a> - <b>insideTestObject.copyByReference</b> - </field> - <field> - <a>globalCopyByReference</a> - <b>globalCopyByReferencePrime</b> - </field> - <field> - <a>setToArray</a> - <b>arrayToSet</b> - </field> - <field> - <a>setToObjectArray</a> - <b>objectArrayToSet</b> - <b-hint>org.dozer.vo.Apple</b-hint> - </field> - <field> - <a>setToList</a> - <b>listToSet</b> - </field> - <field> - <a>collectionToList</a> - <b>listToCollection</b> - </field> - <field relationship-type="non-cumulative"> - <a>setToListWithValues</a> - <b>setToListWithValues</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.SuperSuperSuperClass</class-a> - <class-b>org.dozer.vo.SuperSuperSuperClassPrime</class-b> - <field> - <a>hydrate</a> - <b>dehydrate</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.SuperSuperClass</class-a> - <class-b>org.dozer.vo.SuperSuperClassPrime</class-b> - <field> - <a>superSuperAttribute</a> - <b>superSuperAttr</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.SuperClass</class-a> - <class-b>org.dozer.vo.SuperClassPrime</class-b> - <field> - <a>superAttribute</a> - <b>superAttr</b> - </field> - <field> - <a>superList</a> - <b>superArray</b> - </field> - <field type="one-way"> - <a>superFieldToExclude</a> - <b>superFieldToExcludePrime</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.SubClass</class-a> - <class-b>org.dozer.vo.SubClassPrime</class-b> - <field> - <a>attribute</a> - <b>attributePrime</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.InsideTestObject</class-a> - <class-b>org.dozer.vo.InsideTestObjectPrime</class-b> - <field> - <a>label</a><!-- converting String to String by name only --> - <b>labelPrime</b> - </field> - <field> - <a>toWrapper</a><!-- converting a primitive (int) to a custom primitive wrapper --> - <b>anotherWrapper</b> - </field> - </mapping> - - <mapping wildcard="false"> - <class-a>org.dozer.vo.FurtherTestObject</class-a> - <class-b>org.dozer.vo.FurtherTestObjectPrime</class-b> - <field> - <a>one</a><!-- normally, you don't have to map equally name attributes, but wildcards="false" --> - <b>one</b> - </field> - <field-exclude> - <a>address</a> - <b>address</b> - </field-exclude> - </mapping> - - <mapping wildcard="false"> - <class-a>org.dozer.vo.WeirdGetter</class-a> - <class-b>org.dozer.vo.WeirdGetterPrime</class-b> - <field> - <a set-method="placeValue" get-method="buildValue">value</a> - <b>value</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.WeirdGetter2</class-a> - <class-b>org.dozer.vo.WeirdGetterPrime2</class-b> - <field> - <a>value</a> - <b set-method="placeValue" get-method="buildValue">value</b> - </field> - </mapping> - - <mapping wildcard="false"> - <class-a>org.dozer.vo.DehydrateTestObject</class-a> - <class-b>org.dozer.vo.HydrateTestObject</class-b> - <!-- Iterate Method Mapping --> - <field> - <a>appleComputers</a> - <b set-method="addComputer" type="iterate">computers</b> - <b-hint>org.dozer.vo.AppleComputer</b-hint> - </field> - <!-- Iterate Method Mapping --> - <field> - <a set-method="addCar" get-method="myIterateCars" type="iterate">iterateCars</a> - <b set-method="addIterateCar" type="iterate">iterateCars</b> - <a-hint>org.dozer.vo.Car</a-hint> - <b-hint>org.dozer.vo.Car</b-hint> - </field> - <!-- Iterate Method Mapping --> - <field> - <a set-method="addMoreCar" type="iterate">iterateMoreCars</a> - <b>carArray</b> - <a-hint>org.dozer.vo.Car</a-hint> - <b-hint>org.dozer.vo.Car</b-hint> - </field> - </mapping> - - <mapping wildcard="false"> - <class-a>org.dozer.vo.Vehicle</class-a><!-- incompatible mapping test --> - <class-b>org.dozer.vo.TestObject</class-b> - <field> - <a>name</a><!-- obviously can not map a string to a complex type unless complex type has a String constructor --> - <b>noMappingsObj</b> - </field> - </mapping> - - <mapping stop-on-errors="true"> - <class-a>org.dozer.vo.MethodFieldTestObject</class-a> - <class-b>org.dozer.vo.MethodFieldTestObject2</class-b> - <field type="one-way"><!-- we can not map a ArrayList to a String, hence the one-way mapping --> - <a>integerStr</a> - <b set-method="addIntegerToList">integerList</b> - </field> - <field type="one-way"> - <a>priceItemStr</a> - <b set-method="addToTotalPrice">totalPrice</b> - </field> - <field type="one-way"> - <a>fieldOne</a> - <b>fieldOne</b> - </field> - </mapping> - - <mapping stop-on-errors="true"> - <class-a>org.dozer.vo.deep.House</class-a> - <class-b>org.dozer.vo.deep.HomeDescription</class-b> - <field> - <a>owner.name</a> - <b>description.ownerName</b> - </field> - <field> - <a>owner.prim</a> - <b>prim</b> - </field> - <field> - <a>address.street</a> - <b>description.street</b> - </field> - <field> - <a>address.city.name</a> - <b>description.city</b> - </field> - <field> - <a>rooms</a> - <b>description.rooms</b> - </field> - <field type="one-way"> - <a>owner.yourName</a> - <b>description.myName</b> - </field> - <field relationship-type="non-cumulative"> - <a>rooms</a> - <b>description.someOwners</b> - <a-hint>org.dozer.vo.deep.Room</a-hint> - <b-hint>org.dozer.vo.deep.Person</b-hint> - </field> - <field> - <a>customSetGetMethod</a> - <b set-method="setCustom" type="iterate">description.customSetGetMethod</b> - <b-hint>org.dozer.vo.Van</b-hint> - </field> - </mapping> - - <mapping stop-on-errors="true" type="bi-directional"> - <class-a>org.dozer.vo.deep.SrcDeepObj</class-a> - <class-b>org.dozer.vo.deep.DestDeepObj</class-b> - <field> - <a>srcNestedObj.src1</a> - <b>dest1</b> - </field> - <field> - <a>srcNestedObj.src2</a> - <b>dest2</b> - </field> - <field> - <a>srcNestedObj.src3</a> - <b>dest3</b> - </field> - <field> - <a>srcNestedObj.src4</a> - <b>dest4</b> - </field> - <field> - <a>srcNestedObj.hintList</a> - <b>hintList</b> - <a-hint>java.lang.String</a-hint> - <b-hint>java.lang.Integer</b-hint> - </field> - <field> - <a>srcNestedObj.hintList2</a> - <b>hintList2</b> - <a-hint>org.dozer.vo.TheFirstSubClass</a-hint> - <b-hint>org.dozer.vo.TheFirstSubClassPrime</b-hint> - </field> - <field> - <a>srcNestedObj.srcNestedObj2.src5</a> - <b>dest5</b> - </field> - <field> - <a>srcNestedObj.src6</a> - <b>dest6</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.TestCustomConverterObject</class-a> - <class-b>org.dozer.vo.TestCustomConverterObjectPrime</class-b> - <field> - <a>names</a> - <b>names</b> - <a-hint>org.dozer.vo.CustomDoubleObject</a-hint> - <b-hint>java.lang.Double</b-hint> - </field> - <field> - <a>attribute</a> - <b>doubleAttribute</b> - </field> - </mapping> - - <!-- one way test case --> - <mapping type="one-way" stop-on-errors="true"> - <class-a>org.dozer.vo.OneWayObject</class-a> - <class-b>org.dozer.vo.OneWayObjectPrime</class-b> - <field> - <a>oneWayField</a> - <b>oneWayPrimeField</b> - </field> - <field> - <a>setOnly</a> - <b>setOnlyField</b> - </field> - <!-- we don't support nested fields with type="one-way". The reason is that I do not make a bi-directional map - since this is a one-way mapping. They will have to create a one way mapping the other way if they want to exclude fields - in the other direction - <field type="one-way"> - <a>oneWay</a> - <b>oneWay</b> - </field> - --> - <!-- testing method mapping on a generic map. can only be one-way --> - <field> - <a>stringToList</a> - <b set-method="addValue">stringList</b> - </field> - <!-- testing method mapping on a deep map. can only be one-way --> - <field> - <a>nested.src1</a> - <b set-method="addValue">stringList</b> - </field> - </mapping> - - <!-- testing map by reference --> - <mapping> - <class-a>org.dozer.vo.TestReferenceObject</class-a> - <class-b>org.dozer.vo.TestReferencePrimeObject</class-b> - <field relationship-type="non-cumulative"> - <a>listA</a> - <b>listAPrime</b> - <a-hint>org.dozer.vo.TestReferenceFoo</a-hint> - <b-hint>org.dozer.vo.TestReferenceFooPrime</b-hint> - </field> - <field relationship-type="cumulative"> - <a>arrayToArrayCumulative</a> - <b>arrayToArrayCumulative</b> - <a-hint>org.dozer.vo.TestReferenceFoo</a-hint> - <b-hint>org.dozer.vo.TestReferenceFooPrime</b-hint> - </field> - <field relationship-type="non-cumulative"> - <a>arrayToArrayNoncumulative</a> - <b>arrayToArrayNoncumulative</b> - <a-hint>org.dozer.vo.TestReferenceFoo</a-hint> - <b-hint>org.dozer.vo.TestReferenceFooPrime</b-hint> - </field> - <!-- example of NOT using hints for Array to Array --> - <field> - <a>cars</a> - <b>vans</b> - </field> - <!-- example of NOT using hints for List to Array --> - <field> - <a>vehicles</a> - <b>moreVans</b> - </field> - </mapping> - - <!-- inheritance test 1--> - <mapping> - <class-a>org.dozer.vo.inheritance.BaseClass</class-a> - <class-b>org.dozer.vo.inheritance.BaseSubClassCombined</class-b> - <field> - <a>baseAttribute</a> - <b>baseAttribute2</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.inheritance.SubClass</class-a> - <class-b>org.dozer.vo.inheritance.BaseSubClassCombined</class-b> - <field> - <a>subAttribute</a> - <b>subAttribute2</b> - </field> - </mapping> - - <!-- inheritance test 2--> - <mapping> - <class-a>org.dozer.vo.inheritance.AnotherSubClass</class-a> - <class-b>org.dozer.vo.inheritance.AnotherSubClassPrime</class-b> - <field> - <a>subAttribute</a> - <b>subAttribute2</b> - </field> - <field> - <a>subList</a> - <b>theListOfSubClassPrime</b> - <a-hint>org.dozer.vo.inheritance.SClass, - org.dozer.vo.inheritance.S2Class - </a-hint> - <b-hint>org.dozer.vo.inheritance.SClassPrime, - org.dozer.vo.inheritance.S2ClassPrime - </b-hint> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.inheritance.AnotherBaseClass</class-a> - <class-b>org.dozer.vo.inheritance.AnotherBaseClassPrime</class-b> - <field> - <a>baseAttribute</a> - <b>baseAttribute2</b> - </field> - <field> - <a>listToArray</a> - <b>arrayToList</b> - <a-hint>org.dozer.vo.inheritance.SClass, - org.dozer.vo.inheritance.S2Class - </a-hint> - <b-hint>org.dozer.vo.inheritance.SClassPrime, - org.dozer.vo.inheritance.S2ClassPrime - </b-hint> - </field> - - </mapping> - - - <mapping> - <class-a>org.dozer.vo.inheritance.BaseSubClass</class-a> - <class-b>org.dozer.vo.inheritance.BaseSubClassPrime</class-b> - <field> - <a>baseSubAttribute</a> - <b>baseSubAttribute2</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.inheritance.SClass</class-a> - <class-b>org.dozer.vo.inheritance.SClassPrime</class-b> - <field> - <a>subAttribute</a> - <b>subAttribute2</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.inheritance.S2Class</class-a> - <class-b>org.dozer.vo.inheritance.S2ClassPrime</class-b> - <field> - <a>sub2Attribute</a> - <b>sub2Attribute2</b> - </field> - </mapping> - - <!-- inheritance test abstract class--> - <mapping> - <class-a>org.dozer.vo.inheritance.SuperSpecificObject</class-a> - <class-b>org.dozer.vo.inheritance.Specific1</class-b> - <field> - <a>superAttr1</a> - <b>superAttr2</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.inheritance.SuperSpecificObject</class-a> - <class-b>org.dozer.vo.inheritance.Specific3</class-b> - <field> - <a>superAttr1</a> - <b>superAttr3</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.inheritance.WrapperSpecific</class-a> - <class-b>org.dozer.vo.inheritance.WrapperSpecificPrime</class-b> - <field> - <a>specificObject</a> - <b>specificObjectPrime</b> - <b-hint>org.dozer.vo.inheritance.Specific3</b-hint> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.CustomConverterWrapper</class-a> - <class-b>org.dozer.vo.CustomConverterWrapperPrime</class-b> - <field> - <a set-method="addHint" type="iterate">needsHint</a> - <b>needsHint</b> - <a-hint>org.dozer.vo.HintedOnly</a-hint> - <b-hint>java.lang.String</b-hint> - </field> - </mapping> - - <!-- Testing NULL data --> - <mapping> - <class-a>org.dozer.vo.AnotherTestObject</class-a> - <class-b>org.dozer.vo.AnotherTestObjectPrime</class-b> - <field> - <a>field1</a> - <b>to.thePrimitive</b> - </field> - </mapping> - - <!-- test 'self' mapping --> - <mapping> - <class-a>org.dozer.vo.self.SimpleAccount</class-a> - <class-b>org.dozer.vo.self.Account</class-b> - <field> - <a>this</a> - <b>address</b> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.self.SimpleAccount</class-a> - <class-b>org.dozer.vo.self.Address</class-b> - <field> - <a>streetName</a> - <b>street</b> - </field> - </mapping> - - <!-- testing mapping properties to a Map --> - <mapping> - <class-a>org.dozer.vo.map.PropertyToMap</class-a> - <class-b>org.dozer.vo.map.MapToProperty</class-b> - <field> - <a>stringProperty</a> - <b>hashMap</b> - </field> - <field> - <a set-method="addStringProperty2">stringProperty2</a> - <b key="myStringProperty">hashMap</b> - </field> - <field> - <a>nullStringProperty</a> - <b>hashMap</b> - </field> - <field> - <a>stringProperty3</a> - <b map-get-method="getValue" map-set-method="putValue" key="myCustomProperty">customMap</b> - </field> - <field> - <a>stringProperty4</a> - <b map-get-method="getValue" map-set-method="putValue" key="myCustomNullProperty">nullCustomMap</b> - <b-hint>org.dozer.vo.map.CustomMap</b-hint> - </field> - <field> - <a>stringProperty5</a> - <b map-get-method="getValue" map-set-method="putValue">customMap</b> - </field> - <field> - <a>stringProperty6</a> - <b>nullHashMap</b> - <b-hint>java.util.HashMap</b-hint> - </field> - <field> - <a>stringProperty5</a> - <b map-get-method="getValue" map-set-method="putValue">customMapWithDiffSetMethod</b> - </field> - <field> - <a>reverseMap</a> - <b>reverseMapString</b> - </field> - <field> - <a>reverseMap</a> - <b>reverseMapInteger</b> - </field> - </mapping> - - <!-- testing mapping properties to a Class Level Map --> - <mapping map-id="myTestMapping"> - <class-a>org.dozer.vo.map.PropertyToMap</class-a> - <class-b>java.util.HashMap</class-b> - <field> - <a>stringProperty2</a> - <b key="myStringProperty">this</b> - </field> - <!-- Add deep property functionality - <field> - <a>testObject.one</a> - <B key="testDeepProperty">this</b> - </field> - --> - <field-exclude> - <a>excludeMe</a> - <b>this</b> - </field-exclude> - </mapping> - - <mapping map-id="myCustomTestMapping"> - <class-a>org.dozer.vo.map.PropertyToMap</class-a> - <class-b map-set-method="putValue" map-get-method="getValue">org.dozer.vo.map.CustomMap</class-b> - <field> - <a set-method="addStringProperty2">stringProperty2</a> - <b key="myStringProperty">this</b> - </field> - <field-exclude> - <a>excludeMe</a> - <b>this</b> - </field-exclude> - </mapping> - - <!-- testing mapping properties to a Custom Class Level Map --> - <mapping map-id="myCustomTestMappingUsingInterface"> - <class-a map-set-method="putValue" map-get-method="getValue">org.dozer.vo.map.CustomMapIF</class-a> - <class-b>org.dozer.vo.map.PropertyToMap</class-b> - <field> - <a key="myStringProperty">this</a> - <b set-method="addStringProperty2">stringProperty2</b> - </field> - <field-exclude> - <a>this</a> - <b>excludeMe</b> - </field-exclude> - </mapping> - - <!-- testing mapping properties to a Class Level Map --> - <mapping map-id="myReverseTestMapping"> - <class-a>java.util.Map</class-a> - <class-b>org.dozer.vo.map.PropertyToMap</class-b> - <field> - <a key="myStringProperty">this</a> - <b set-method="addStringProperty2">stringProperty2</b> - </field> - <field-exclude> - <a>this</a> - <b>excludeMe</b> - </field-exclude> - </mapping> - - <mapping> - <class-a>org.dozer.vo.map.MapTestObject</class-a> - <class-b>org.dozer.vo.map.MapTestObjectPrime</class-b> - <field map-id="myTestMapping"> - <a>propertyToMap</a> - <b>propertyToMapMap</b> - </field> - <field map-id="myReverseTestMapping"> - <a>propertyToMapMapReverse</a> - <b>propertyToMapReverse</b> - </field> - <field map-id="myTestMapping"> - <a>propertyToMapToNullMap</a> - <b>nullPropertyToMapMap</b> - <b-hint>java.util.HashMap</b-hint> - </field> - <field map-id="myCustomTestMapping"> - <a>propertyToCustomMap</a> - <b>propertyToCustomMapMap</b> - </field> - <field map-id="myCustomTestMappingUsingInterface"> - <a>propertyToCustomMapMapWithInterface</a> - <b>propertyToCustomMapWithInterface</b> - <a-hint>org.dozer.vo.map.CustomMap</a-hint> - </field> - </mapping> - - <mapping> - <class-a>org.dozer.vo.SimpleObj</class-a> - <class-b>org.dozer.vo.SimpleObjPrime2</class-b> - <field> - <a>field1</a> - <b>field1Prime</b> - </field> - <field> - <a>field2</a> - <b>field2Prime</b> - </field> - <field> - <a>field3</a> - <b>field3Prime</b> - </field> - <field> - <a>field4</a> - <b>field4Prime</b> - </field> - <field> - <a>field5</a> - <b>field5Prime</b> - </field> - <field> - <a>field6</a> - <b>field6Prime</b> - </field> - </mapping> - -</mappings> +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + Copyright 2005-2017 Dozer Project + + 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. + +--> +<mappings xmlns="http://dozermapper.github.io/schema/bean-mapping" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping http://dozermapper.github.io/schema/bean-mapping.xsd"> + + <configuration> + <stop-on-errors>true</stop-on-errors> + <date-format>MM/dd/yyyy HH:mm</date-format><!-- default dateformat will apply to all class maps unless the class mapping explicitly overrides it --> + <wildcard>true</wildcard><!-- default wildcard policy that will apply to all class maps unless the class mapping explicitly overrides it --> + <custom-converters><!-- these are always considered bi-directional --> + <converter type="org.dozer.functional_tests.support.TestCustomConverter"> + <class-a>org.dozer.vo.CustomDoubleObjectIF</class-a> + <class-b>java.lang.Double</class-b> + </converter> + <!-- this is a top level custom mapping. You are responsible for mapping everything between class-a and class-b --> + <converter type="org.dozer.functional_tests.support.TestCustomHashMapConverter"> + <!-- keep the carriage returns...this tests parsing the xml --> + <class-a>org.dozer.vo.TestCustomConverterHashMapObject</class-a> + <class-b>org.dozer.vo.TestCustomConverterHashMapPrimeObject</class-b> + </converter> + <!-- testing converters with hints --> + <converter type="org.dozer.functional_tests.support.HintedOnlyConverter"> + <class-a>org.dozer.vo.HintedOnly</class-a> + <class-b>java.lang.String</class-b> + </converter> + </custom-converters> + <copy-by-references> + <copy-by-reference>org.dozer.vo.NoExtendBaseObjectGlobalCopyByReference</copy-by-reference> + </copy-by-references> + </configuration> + + <mapping wildcard="true" date-format="MM-dd-yyyy HH:mm:ss"><!-- Override top level date format default. Defaults to wildcard = true. this means that any properties the same name between classes it will implicitly copy --> + <class-a>org.dozer.vo.TestObject</class-a> + <class-b>org.dozer.vo.TestObjectPrime</class-b> + <field-exclude> + <a>excludeMe</a> + <b>excludeMe</b> + </field-exclude> + <field-exclude type="one-way"> + <a>excludeMeOneWay</a> + <b>excludeMeOneWay</b> + </field-exclude> + <field> + <a>carMetalThingy</a> + <b>vanMetalThingy</b> + <a-hint>org.dozer.vo.Car</a-hint> + <b-hint>org.dozer.vo.Van</b-hint> + </field> + <field> + <a>anotherLongValue</a> + <b>theLongValue</b> + </field> + <field> + <a>primArray</a> + <b>primitiveArray</b> + </field> + <field> + <a>one</a><!-- converting String to String by name only --> + <b>onePrime</b> + </field> + <field> + <a>two</a><!-- converting Integer to Integer by name only --> + <b>twoPrime</b> + </field> + <field> + <a>three</a><!-- converting by name and type InsideTestObject to InsideTestObjectPrime (actually this object is in the second <mapping> below --> + <b>threePrime</b> + </field> + <field> + <a date-format="MM/dd/yyyy HH:mm:ss:SS">dateStr</a><!-- converting from String to Date using date-format. Override class mapping date format--> + <b>dateFromStr</b> + </field> + <field> + <a>theMappedPrimitive</a><!-- converting int to int by name only --> + <b>anotherPrimitive</b> + </field> + <field> + <a>anArray</a><!-- converting int[] to int [] by name only --> + <b>theMappedArray</b> + </field> + <field relationship-type="non-cumulative"> + <a>unequalNamedList</a><!-- converting String List to String List by name only --> + <b>theMappedUnequallyNamedList</b> + </field> + <field> + <a>arrayForLists</a><!-- changing an Integer [] to List and back again --> + <b>listForArray</b> + <b-hint>java.lang.Integer</b-hint> + </field> + <field relationship-type="cumulative"> + <a>hintList</a><!-- converting TheFirstSubClass List to TheFirstSubClassPrime List --> + <b>hintList</b> + <a-hint>org.dozer.vo.TheFirstSubClass</a-hint> + <b-hint>org.dozer.vo.TheFirstSubClassPrime</b-hint> + </field> + <field copy-by-reference="true"> + <a>copyByReference</a> + <b>copyByReferencePrime</b> + </field> + <field copy-by-reference="true"> + <a>copyByReferenceDeep</a> + <b>insideTestObject.copyByReference</b> + </field> + <field> + <a>globalCopyByReference</a> + <b>globalCopyByReferencePrime</b> + </field> + <field> + <a>setToArray</a> + <b>arrayToSet</b> + </field> + <field> + <a>setToObjectArray</a> + <b>objectArrayToSet</b> + <b-hint>org.dozer.vo.Apple</b-hint> + </field> + <field> + <a>setToList</a> + <b>listToSet</b> + </field> + <field> + <a>collectionToList</a> + <b>listToCollection</b> + </field> + <field relationship-type="non-cumulative"> + <a>setToListWithValues</a> + <b>setToListWithValues</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.SuperSuperSuperClass</class-a> + <class-b>org.dozer.vo.SuperSuperSuperClassPrime</class-b> + <field> + <a>hydrate</a> + <b>dehydrate</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.SuperSuperClass</class-a> + <class-b>org.dozer.vo.SuperSuperClassPrime</class-b> + <field> + <a>superSuperAttribute</a> + <b>superSuperAttr</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.SuperClass</class-a> + <class-b>org.dozer.vo.SuperClassPrime</class-b> + <field> + <a>superAttribute</a> + <b>superAttr</b> + </field> + <field> + <a>superList</a> + <b>superArray</b> + </field> + <field type="one-way"> + <a>superFieldToExclude</a> + <b>superFieldToExcludePrime</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.SubClass</class-a> + <class-b>org.dozer.vo.SubClassPrime</class-b> + <field> + <a>attribute</a> + <b>attributePrime</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.InsideTestObject</class-a> + <class-b>org.dozer.vo.InsideTestObjectPrime</class-b> + <field> + <a>label</a><!-- converting String to String by name only --> + <b>labelPrime</b> + </field> + <field> + <a>toWrapper</a><!-- converting a primitive (int) to a custom primitive wrapper --> + <b>anotherWrapper</b> + </field> + </mapping> + + <mapping wildcard="false"> + <class-a>org.dozer.vo.FurtherTestObject</class-a> + <class-b>org.dozer.vo.FurtherTestObjectPrime</class-b> + <field> + <a>one</a><!-- normally, you don't have to map equally name attributes, but wildcards="false" --> + <b>one</b> + </field> + <field-exclude> + <a>address</a> + <b>address</b> + </field-exclude> + </mapping> + + <mapping wildcard="false"> + <class-a>org.dozer.vo.WeirdGetter</class-a> + <class-b>org.dozer.vo.WeirdGetterPrime</class-b> + <field> + <a set-method="placeValue" get-method="buildValue">value</a> + <b>value</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.WeirdGetter2</class-a> + <class-b>org.dozer.vo.WeirdGetterPrime2</class-b> + <field> + <a>value</a> + <b set-method="placeValue" get-method="buildValue">value</b> + </field> + </mapping> + + <mapping wildcard="false"> + <class-a>org.dozer.vo.DehydrateTestObject</class-a> + <class-b>org.dozer.vo.HydrateTestObject</class-b> + <!-- Iterate Method Mapping --> + <field> + <a>appleComputers</a> + <b set-method="addComputer" type="iterate">computers</b> + <b-hint>org.dozer.vo.AppleComputer</b-hint> + </field> + <!-- Iterate Method Mapping --> + <field> + <a set-method="addCar" get-method="myIterateCars" type="iterate">iterateCars</a> + <b set-method="addIterateCar" type="iterate">iterateCars</b> + <a-hint>org.dozer.vo.Car</a-hint> + <b-hint>org.dozer.vo.Car</b-hint> + </field> + <!-- Iterate Method Mapping --> + <field> + <a set-method="addMoreCar" type="iterate">iterateMoreCars</a> + <b>carArray</b> + <a-hint>org.dozer.vo.Car</a-hint> + <b-hint>org.dozer.vo.Car</b-hint> + </field> + </mapping> + + <mapping wildcard="false"> + <class-a>org.dozer.vo.Vehicle</class-a><!-- incompatible mapping test --> + <class-b>org.dozer.vo.TestObject</class-b> + <field> + <a>name</a><!-- obviously can not map a string to a complex type unless complex type has a String constructor --> + <b>noMappingsObj</b> + </field> + </mapping> + + <mapping stop-on-errors="true"> + <class-a>org.dozer.vo.MethodFieldTestObject</class-a> + <class-b>org.dozer.vo.MethodFieldTestObject2</class-b> + <field type="one-way"><!-- we can not map a ArrayList to a String, hence the one-way mapping --> + <a>integerStr</a> + <b set-method="addIntegerToList">integerList</b> + </field> + <field type="one-way"> + <a>priceItemStr</a> + <b set-method="addToTotalPrice">totalPrice</b> + </field> + <field type="one-way"> + <a>fieldOne</a> + <b>fieldOne</b> + </field> + </mapping> + + <mapping stop-on-errors="true"> + <class-a>org.dozer.vo.deep.House</class-a> + <class-b>org.dozer.vo.deep.HomeDescription</class-b> + <field> + <a>owner.name</a> + <b>description.ownerName</b> + </field> + <field> + <a>owner.prim</a> + <b>prim</b> + </field> + <field> + <a>address.street</a> + <b>description.street</b> + </field> + <field> + <a>address.city.name</a> + <b>description.city</b> + </field> + <field> + <a>rooms</a> + <b>description.rooms</b> + </field> + <field type="one-way"> + <a>owner.yourName</a> + <b>description.myName</b> + </field> + <field relationship-type="non-cumulative"> + <a>rooms</a> + <b>description.someOwners</b> + <a-hint>org.dozer.vo.deep.Room</a-hint> + <b-hint>org.dozer.vo.deep.Person</b-hint> + </field> + <field> + <a>customSetGetMethod</a> + <b set-method="setCustom" type="iterate">description.customSetGetMethod</b> + <b-hint>org.dozer.vo.Van</b-hint> + </field> + </mapping> + + <mapping stop-on-errors="true" type="bi-directional"> + <class-a>org.dozer.vo.deep.SrcDeepObj</class-a> + <class-b>org.dozer.vo.deep.DestDeepObj</class-b> + <field> + <a>srcNestedObj.src1</a> + <b>dest1</b> + </field> + <field> + <a>srcNestedObj.src2</a> + <b>dest2</b> + </field> + <field> + <a>srcNestedObj.src3</a> + <b>dest3</b> + </field> + <field> + <a>srcNestedObj.src4</a> + <b>dest4</b> + </field> + <field> + <a>srcNestedObj.hintList</a> + <b>hintList</b> + <a-hint>java.lang.String</a-hint> + <b-hint>java.lang.Integer</b-hint> + </field> + <field> + <a>srcNestedObj.hintList2</a> + <b>hintList2</b> + <a-hint>org.dozer.vo.TheFirstSubClass</a-hint> + <b-hint>org.dozer.vo.TheFirstSubClassPrime</b-hint> + </field> + <field> + <a>srcNestedObj.srcNestedObj2.src5</a> + <b>dest5</b> + </field> + <field> + <a>srcNestedObj.src6</a> + <b>dest6</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.TestCustomConverterObject</class-a> + <class-b>org.dozer.vo.TestCustomConverterObjectPrime</class-b> + <field> + <a>names</a> + <b>names</b> + <a-hint>org.dozer.vo.CustomDoubleObject</a-hint> + <b-hint>java.lang.Double</b-hint> + </field> + <field> + <a>attribute</a> + <b>doubleAttribute</b> + </field> + </mapping> + + <!-- one way test case --> + <mapping type="one-way" stop-on-errors="true"> + <class-a>org.dozer.vo.OneWayObject</class-a> + <class-b>org.dozer.vo.OneWayObjectPrime</class-b> + <field> + <a>oneWayField</a> + <b>oneWayPrimeField</b> + </field> + <field> + <a>setOnly</a> + <b>setOnlyField</b> + </field> + <!-- we don't support nested fields with type="one-way". The reason is that I do not make a bi-directional map + since this is a one-way mapping. They will have to create a one way mapping the other way if they want to exclude fields + in the other direction + <field type="one-way"> + <a>oneWay</a> + <b>oneWay</b> + </field> + --> + <!-- testing method mapping on a generic map. can only be one-way --> + <field> + <a>stringToList</a> + <b set-method="addValue">stringList</b> + </field> + <!-- testing method mapping on a deep map. can only be one-way --> + <field> + <a>nested.src1</a> + <b set-method="addValue">stringList</b> + </field> + </mapping> + + <!-- testing map by reference --> + <mapping> + <class-a>org.dozer.vo.TestReferenceObject</class-a> + <class-b>org.dozer.vo.TestReferencePrimeObject</class-b> + <field relationship-type="non-cumulative"> + <a>listA</a> + <b>listAPrime</b> + <a-hint>org.dozer.vo.TestReferenceFoo</a-hint> + <b-hint>org.dozer.vo.TestReferenceFooPrime</b-hint> + </field> + <field relationship-type="cumulative"> + <a>arrayToArrayCumulative</a> + <b>arrayToArrayCumulative</b> + <a-hint>org.dozer.vo.TestReferenceFoo</a-hint> + <b-hint>org.dozer.vo.TestReferenceFooPrime</b-hint> + </field> + <field relationship-type="non-cumulative"> + <a>arrayToArrayNoncumulative</a> + <b>arrayToArrayNoncumulative</b> + <a-hint>org.dozer.vo.TestReferenceFoo</a-hint> + <b-hint>org.dozer.vo.TestReferenceFooPrime</b-hint> + </field> + <!-- example of NOT using hints for Array to Array --> + <field> + <a>cars</a> + <b>vans</b> + </field> + <!-- example of NOT using hints for List to Array --> + <field> + <a>vehicles</a> + <b>moreVans</b> + </field> + </mapping> + + <!-- inheritance test 1--> + <mapping> + <class-a>org.dozer.vo.inheritance.BaseClass</class-a> + <class-b>org.dozer.vo.inheritance.BaseSubClassCombined</class-b> + <field> + <a>baseAttribute</a> + <b>baseAttribute2</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.inheritance.SubClass</class-a> + <class-b>org.dozer.vo.inheritance.BaseSubClassCombined</class-b> + <field> + <a>subAttribute</a> + <b>subAttribute2</b> + </field> + </mapping> + + <!-- inheritance test 2--> + <mapping> + <class-a>org.dozer.vo.inheritance.AnotherSubClass</class-a> + <class-b>org.dozer.vo.inheritance.AnotherSubClassPrime</class-b> + <field> + <a>subAttribute</a> + <b>subAttribute2</b> + </field> + <field> + <a>subList</a> + <b>theListOfSubClassPrime</b> + <a-hint>org.dozer.vo.inheritance.SClass, + org.dozer.vo.inheritance.S2Class + </a-hint> + <b-hint>org.dozer.vo.inheritance.SClassPrime, + org.dozer.vo.inheritance.S2ClassPrime + </b-hint> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.inheritance.AnotherBaseClass</class-a> + <class-b>org.dozer.vo.inheritance.AnotherBaseClassPrime</class-b> + <field> + <a>baseAttribute</a> + <b>baseAttribute2</b> + </field> + <field> + <a>listToArray</a> + <b>arrayToList</b> + <a-hint>org.dozer.vo.inheritance.SClass, + org.dozer.vo.inheritance.S2Class + </a-hint> + <b-hint>org.dozer.vo.inheritance.SClassPrime, + org.dozer.vo.inheritance.S2ClassPrime + </b-hint> + </field> + + </mapping> + + + <mapping> + <class-a>org.dozer.vo.inheritance.BaseSubClass</class-a> + <class-b>org.dozer.vo.inheritance.BaseSubClassPrime</class-b> + <field> + <a>baseSubAttribute</a> + <b>baseSubAttribute2</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.inheritance.SClass</class-a> + <class-b>org.dozer.vo.inheritance.SClassPrime</class-b> + <field> + <a>subAttribute</a> + <b>subAttribute2</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.inheritance.S2Class</class-a> + <class-b>org.dozer.vo.inheritance.S2ClassPrime</class-b> + <field> + <a>sub2Attribute</a> + <b>sub2Attribute2</b> + </field> + </mapping> + + <!-- inheritance test abstract class--> + <mapping> + <class-a>org.dozer.vo.inheritance.SuperSpecificObject</class-a> + <class-b>org.dozer.vo.inheritance.Specific1</class-b> + <field> + <a>superAttr1</a> + <b>superAttr2</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.inheritance.SuperSpecificObject</class-a> + <class-b>org.dozer.vo.inheritance.Specific3</class-b> + <field> + <a>superAttr1</a> + <b>superAttr3</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.inheritance.WrapperSpecific</class-a> + <class-b>org.dozer.vo.inheritance.WrapperSpecificPrime</class-b> + <field> + <a>specificObject</a> + <b>specificObjectPrime</b> + <b-hint>org.dozer.vo.inheritance.Specific3</b-hint> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.CustomConverterWrapper</class-a> + <class-b>org.dozer.vo.CustomConverterWrapperPrime</class-b> + <field> + <a set-method="addHint" type="iterate">needsHint</a> + <b>needsHint</b> + <a-hint>org.dozer.vo.HintedOnly</a-hint> + <b-hint>java.lang.String</b-hint> + </field> + </mapping> + + <!-- Testing NULL data --> + <mapping> + <class-a>org.dozer.vo.AnotherTestObject</class-a> + <class-b>org.dozer.vo.AnotherTestObjectPrime</class-b> + <field> + <a>field1</a> + <b>to.thePrimitive</b> + </field> + </mapping> + + <!-- test 'self' mapping --> + <mapping> + <class-a>org.dozer.vo.self.SimpleAccount</class-a> + <class-b>org.dozer.vo.self.Account</class-b> + <field> + <a>this</a> + <b>address</b> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.self.SimpleAccount</class-a> + <class-b>org.dozer.vo.self.Address</class-b> + <field> + <a>streetName</a> + <b>street</b> + </field> + </mapping> + + <!-- testing mapping properties to a Map --> + <mapping> + <class-a>org.dozer.vo.map.PropertyToMap</class-a> + <class-b>org.dozer.vo.map.MapToProperty</class-b> + <field> + <a>stringProperty</a> + <b>hashMap</b> + </field> + <field> + <a set-method="addStringProperty2">stringProperty2</a> + <b key="myStringProperty">hashMap</b> + </field> + <field> + <a>nullStringProperty</a> + <b>hashMap</b> + </field> + <field> + <a>stringProperty3</a> + <b map-get-method="getValue" map-set-method="putValue" key="myCustomProperty">customMap</b> + </field> + <field> + <a>stringProperty4</a> + <b map-get-method="getValue" map-set-method="putValue" key="myCustomNullProperty">nullCustomMap</b> + <b-hint>org.dozer.vo.map.CustomMap</b-hint> + </field> + <field> + <a>stringProperty5</a> + <b map-get-method="getValue" map-set-method="putValue">customMap</b> + </field> + <field> + <a>stringProperty6</a> + <b>nullHashMap</b> + <b-hint>java.util.HashMap</b-hint> + </field> + <field> + <a>stringProperty5</a> + <b map-get-method="getValue" map-set-method="putValue">customMapWithDiffSetMethod</b> + </field> + <field> + <a>reverseMap</a> + <b>reverseMapString</b> + </field> + <field> + <a>reverseMap</a> + <b>reverseMapInteger</b> + </field> + </mapping> + + <!-- testing mapping properties to a Class Level Map --> + <mapping map-id="myTestMapping"> + <class-a>org.dozer.vo.map.PropertyToMap</class-a> + <class-b>java.util.HashMap</class-b> + <field> + <a>stringProperty2</a> + <b key="myStringProperty">this</b> + </field> + <!-- Add deep property functionality + <field> + <a>testObject.one</a> + <B key="testDeepProperty">this</b> + </field> + --> + <field-exclude> + <a>excludeMe</a> + <b>this</b> + </field-exclude> + </mapping> + + <mapping map-id="myCustomTestMapping"> + <class-a>org.dozer.vo.map.PropertyToMap</class-a> + <class-b map-set-method="putValue" map-get-method="getValue">org.dozer.vo.map.CustomMap</class-b> + <field> + <a set-method="addStringProperty2">stringProperty2</a> + <b key="myStringProperty">this</b> + </field> + <field-exclude> + <a>excludeMe</a> + <b>this</b> + </field-exclude> + </mapping> + + <!-- testing mapping properties to a Custom Class Level Map --> + <mapping map-id="myCustomTestMappingUsingInterface"> + <class-a map-set-method="putValue" map-get-method="getValue">org.dozer.vo.map.CustomMapIF</class-a> + <class-b>org.dozer.vo.map.PropertyToMap</class-b> + <field> + <a key="myStringProperty">this</a> + <b set-method="addStringProperty2">stringProperty2</b> + </field> + <field-exclude> + <a>this</a> + <b>excludeMe</b> + </field-exclude> + </mapping> + + <!-- testing mapping properties to a Class Level Map --> + <mapping map-id="myReverseTestMapping"> + <class-a>java.util.Map</class-a> + <class-b>org.dozer.vo.map.PropertyToMap</class-b> + <field> + <a key="myStringProperty">this</a> + <b set-method="addStringProperty2">stringProperty2</b> + </field> + <field-exclude> + <a>this</a> + <b>excludeMe</b> + </field-exclude> + </mapping> + + <mapping> + <class-a>org.dozer.vo.map.MapTestObject</class-a> + <class-b>org.dozer.vo.map.MapTestObjectPrime</class-b> + <field map-id="myTestMapping"> + <a>propertyToMap</a> + <b>propertyToMapMap</b> + </field> + <field map-id="myReverseTestMapping"> + <a>propertyToMapMapReverse</a> + <b>propertyToMapReverse</b> + </field> + <field map-id="myTestMapping"> + <a>propertyToMapToNullMap</a> + <b>nullPropertyToMapMap</b> + <b-hint>java.util.HashMap</b-hint> + </field> + <field map-id="myCustomTestMapping"> + <a>propertyToCustomMap</a> + <b>propertyToCustomMapMap</b> + </field> + <field map-id="myCustomTestMappingUsingInterface"> + <a>propertyToCustomMapMapWithInterface</a> + <b>propertyToCustomMapWithInterface</b> + <a-hint>org.dozer.vo.map.CustomMap</a-hint> + </field> + </mapping> + + <mapping> + <class-a>org.dozer.vo.SimpleObj</class-a> + <class-b>org.dozer.vo.SimpleObjPrime2</class-b> + <field> + <a>field1</a> + <b>field1Prime</b> + </field> + <field> + <a>field2</a> + <b>field2Prime</b> + </field> + <field> + <a>field3</a> + <b>field3Prime</b> + </field> + <field> + <a>field4</a> + <b>field4Prime</b> + </field> + <field> + <a>field5</a> + <b>field5Prime</b> + </field> + <field> + <a>field6</a> + <b>field6Prime</b> + </field> + </mapping> + +</mappings> diff --git a/docs/asciidoc/documentation/apimappings.adoc b/docs/asciidoc/documentation/apimappings.adoc index b480d9c73..7ac0c02ba 100644 --- a/docs/asciidoc/documentation/apimappings.adoc +++ b/docs/asciidoc/documentation/apimappings.adoc @@ -78,6 +78,6 @@ instance. It is possible to add multiple Builder classes. [source,java,prettyprint] ---- -DozerBeanMapper mapper = new DozerBeanMapper(); +DozerBeanMapper mapper = DozerBeanMapperBuilder.createDefault(); mapper.addMapping(builder); ---- diff --git a/docs/asciidoc/documentation/custombeanfactories.adoc b/docs/asciidoc/documentation/custombeanfactories.adoc index c28d9b735..876ee1a39 100644 --- a/docs/asciidoc/documentation/custombeanfactories.adoc +++ b/docs/asciidoc/documentation/custombeanfactories.adoc @@ -6,7 +6,7 @@ using a default constructor. This is sufficient for most use cases, but if you need more flexibility you can specify your own bean factories to instantiate the data objects. -Your custom bean factory must implement the org.dozer.BeanFactory +Your custom bean factory must implement the `org.dozer.BeanFactory` interface. By default the Dozer mapping engine will use the destination object class name for the bean id when calling the factory. @@ -14,16 +14,16 @@ object class name for the bean id when calling the factory. ---- public interface BeanFactory { public Object createBean(Object source, Class sourceClass, - String targetBeanId); + String targetBeanId, BeanContainer beanContainer); } ---- Next, in your Dozer mapping file(s) you just need to specify a -bean-factory xml attribute for any mappings that you want to use a +`bean-factory` xml attribute for any mappings that you want to use a custom factory. -In the following example, the SampleCustomBeanFactory will be used to -create any new instances of the InsideTestObjectPrime java bean data +In the following example, the `SampleCustomBeanFactory` will be used to +create any new instances of the `InsideTestObjectPrime` java bean data object. [source,xml,prettyprint] @@ -37,8 +37,8 @@ object. ---- If your factory looks up beans based on a different id than class name, -you can specifiy a factory-bean-id xml attribute. At runtime the -specified factory-bean-id will be passed to the factory instead of class +you can specify a `factory-bean-id` xml attribute. At runtime the +specified `factory-bean-id` will be passed to the factory instead of class name. [source,xml,prettyprint] @@ -67,7 +67,7 @@ would be used for any mappings in that file. ---- Bean factories can also be specified at the mapping level. The specified -factory would be used for class-a and class-b. +factory would be used for `class-a` and `class-b`. [source,xml,prettyprint] ---- @@ -107,4 +107,4 @@ control techniques. ---- By defining your factories as Spring beans you can then inject them into -the DozerBeanMapper class. +the `Mapper` instance. diff --git a/docs/asciidoc/documentation/gettingstarted.adoc b/docs/asciidoc/documentation/gettingstarted.adoc index 9786551cd..0350b9676 100644 --- a/docs/asciidoc/documentation/gettingstarted.adoc +++ b/docs/asciidoc/documentation/gettingstarted.adoc @@ -18,7 +18,7 @@ For your first mapping, lets assume that the two data objects share all common a [source,java,prettyprint] ---- -Mapper mapper = new DozerBeanMapper(); +Mapper mapper = DozerBeanMapperBuilder.createDefault(); DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class); ---- @@ -30,12 +30,7 @@ At this point you have completed your first Dozer mapping. Later sections will go over how to specify custom mappings via custom xml files. *IMPORTANT:* For real-world applications it is _NOT_ recommended to create a new instance of the Mapper -each time you map objects. -Typically, a system will only have one DozerBeanMapper instance per JVM. -If you are not using an link:https://en.wikipedia.org/wiki/Inversion_of_control[IoC] framework -where you can define the Mapper instance as _scope="singleton"_. -If needed, a link:https://github.com/DozerMapper/dozer/blob/master/core/src/main/java/org/dozer/DozerBeanMapperSingletonWrapper.java[DozerBeanMapperSingletonWrapper] -convenience class is provided. +each time you map objects but reuse created instance instead. === Specifying Custom Mappings via XML If the two different types of data objects that you are mapping contain any fields that don't share a common property name, diff --git a/docs/asciidoc/documentation/metadata.adoc b/docs/asciidoc/documentation/metadata.adoc index f2711ba76..97d1f76a5 100644 --- a/docs/asciidoc/documentation/metadata.adoc +++ b/docs/asciidoc/documentation/metadata.adoc @@ -33,8 +33,9 @@ To begin querying the mapping definitions the following code is needed: [source,java,prettyprint] ---- -DozerBeanMapper mapper = new DozerBeanMapper(); -mapper.setMappingFiles(listOfFiles); +DozerBeanMapper mapper = DozerBeanMapperBuilder.create() + .withMappingFiles(listOfFiles) + .build(); MappingMetadata mapMetadata = beanMapper.getMappingMetadata(); ---- diff --git a/docs/asciidoc/documentation/usage.adoc b/docs/asciidoc/documentation/usage.adoc index c5ef01313..2b9a2f57a 100644 --- a/docs/asciidoc/documentation/usage.adoc +++ b/docs/asciidoc/documentation/usage.adoc @@ -7,7 +7,7 @@ After mapping the two objects it then returns the destination object with all of [source,java,prettyprint] ---- -Mapper mapper = new DozerBeanMapper(); +Mapper mapper = DozerBeanMapperBuilder.createDefault(); DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class); ---- @@ -46,12 +46,9 @@ If you are using the mapper this way just wrap it using the singleton pattern. [source,java,prettyprint] ---- -List myMappingFiles = new ArrayList(); -myMappingFiles.add("dozerBeanMapping.xml"); -myMappingFiles.add("someOtherDozerBeanMappings.xml"); - -DozerBeanMapper mapper = new DozerBeanMapper(); -mapper.setMappingFiles(myMappingFiles); +DozerBeanMapper mapper = DozerBeanMapperBuilder.create() + .withMappingFiles("dozerBeanMapping.xml", "someOtherDozerBeanMappings.xml") + .build(); DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class); ---- @@ -71,36 +68,3 @@ The following is an example how the Mapper bean would be configured via Spring. </property> </bean> ---- - -=== Dozer Bean Mapper Singleton Wrapper -There is one way to configure the DozerBeanMapperSingletonWrapper to use -your custom mapping file. - -* *Using one mapping file:* A file called dozerBeanMapping.xml file will -be loaded if it is in your Classpath. You can find a sample of this file -in the \{dozer.home}/mappings directory. - -The mapping file defines all of the relationships between Java classes -and their attributes. The link:./mappings.adoc[Custom Mappings] section -details the custom XML mapping options that are available. - -The following example show how to use the -DozerBeanMapperSingletonWrapper. Dozer has a method called map which -takes a source object and either a destination object or destination -object class type. After mapping the two objects it then returns the -destination object with all of its mapped fields. - -[source,java,prettyprint] ----- -Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); -DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class); ----- - -or - -[source,java,prettyprint] ----- -Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); -DestinationObject destObject = new DestinationObject(); -mapper.map(sourceObject, destObject); ----- diff --git a/docs/asciidoc/migration/v6-to-v61.adoc b/docs/asciidoc/migration/v6-to-v61.adoc index c72f4d1b6..bc9efe702 100644 --- a/docs/asciidoc/migration/v6-to-v61.adoc +++ b/docs/asciidoc/migration/v6-to-v61.adoc @@ -41,3 +41,52 @@ See link:https://github.com/DozerMapper/dozer/releases/tag/v6.1.0[for release no http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://dozermapper.github.io/schema/dozer-spring http://dozermapper.github.io/schema/dozer-spring.xsd"> ---- + +=== 3. DozerBeanMapper instantiation is deprecated +Direct instantiation of `DozerBeanMapper` is deprecated and its constructors will be hidden in version 6.2. + +Please use `DozerBeanMapperBuilder` instead. + +**Deprecated:** +[source,java,prettyprint] +---- +Mapper mapper = new DozerBeanMapper(); +---- + +**Recommended:** +[source,java,prettyprint] +---- +Mapper mapper = DozerBeanMapperBuilder.createDefault(); +---- + +=== 4. Dozer Bean Mapper Singleton Wrapper is deprecated +`DozerBeanMapperSingletonWrapper` is deprecated and planned for removal in version 6.2. + +Dozer project does not advise to use JVM singletons. Please use your DI container to manage single instance + of the `Mapper` if required. The following code can be used to create a `Mapper` with default configuration: +[source,java,prettyprint] +---- +Mapper mapper = DozerBeanMapperBuilder.createDefault(); +---- + +=== 5. Internal API is changed +Dozer is moving away from having JVM-global state. This means that some internal API like `BeanContainer` is +not available anymore via singleton references, i.e. `BeanContainer.getInstance()` does not exist. If you were using +this or any other code that is reworked, please let us know. Most likely you developed `DozerModule`. We would like to know +more about real-world use cases to build convenient public API for modules developers. + +=== 6. org.dozer.BeanFactory interface changes +Old signature of `org.dozer.BeanFactory` is deprecated and will be removed in version 6.2. Please use new method of this interface when +creating custom bean factories. + +**Deprecated:** +[source,java,prettyprint] +---- + Object createBean(Object source, Class<?> sourceClass, String targetBeanId) +---- + +**Recommended:** +[source,java,prettyprint] +---- + Object createBean(Object source, Class<?> sourceClass, String targetBeanId, BeanContainer beanContainer) +---- \ No newline at end of file diff --git a/osgi-test/src/test/java/org/dozer/osgi/OsgiContainerTest.java b/osgi-test/src/test/java/org/dozer/osgi/OsgiContainerTest.java index d234d2c04..54e933e58 100644 --- a/osgi-test/src/test/java/org/dozer/osgi/OsgiContainerTest.java +++ b/osgi-test/src/test/java/org/dozer/osgi/OsgiContainerTest.java @@ -15,12 +15,10 @@ */ package org.dozer.osgi; -import java.util.Collections; -import java.util.List; - import javax.inject.Inject; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; @@ -64,21 +62,22 @@ public Option[] config() { @Test public void shouldInstantiate() { - DozerBeanMapper beanMapper = new DozerBeanMapper(); + DozerBeanMapper beanMapper = DozerBeanMapperBuilder.buildDefault(); assertThat(beanMapper, notNullValue()); } @Test public void shouldMap() { - DozerBeanMapper beanMapper = new DozerBeanMapper(); + DozerBeanMapper beanMapper = DozerBeanMapperBuilder.buildDefault(); Object result = beanMapper.map(new Object(), Object.class); assertThat(result, notNullValue()); } @Test public void shouldLoadMappingFile() { - List<String> mappingFiles = Collections.singletonList("mappings/mapping.xml"); - DozerBeanMapper beanMapper = new DozerBeanMapper(mappingFiles); + DozerBeanMapper beanMapper = DozerBeanMapperBuilder.create() + .withMappingFiles("mappings/mapping.xml") + .build(); Object result = beanMapper.map(new Object(), Object.class); assertThat(result, notNullValue()); } diff --git a/proto/src/main/java/org/dozer/ProtobufSupportModule.java b/proto/src/main/java/org/dozer/ProtobufSupportModule.java index b968000ad..8e8c59d25 100644 --- a/proto/src/main/java/org/dozer/ProtobufSupportModule.java +++ b/proto/src/main/java/org/dozer/ProtobufSupportModule.java @@ -15,10 +15,15 @@ */ package org.dozer; +import java.util.Collection; +import java.util.Collections; +import org.dozer.builder.BeanBuilderCreationStrategy; import org.dozer.builder.ByProtobufBuilder; -import org.dozer.builder.DestBeanBuilderCreator; -import org.dozer.classmap.generator.BeanMappingGenerator; +import org.dozer.classmap.generator.BeanFieldsDetector; import org.dozer.classmap.generator.ProtobufBeanFieldsDetector; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; +import org.dozer.propertydescriptor.PropertyDescriptorCreationStrategy; import org.dozer.propertydescriptor.PropertyDescriptorFactory; import org.dozer.propertydescriptor.ProtoFieldPropertyDescriptorCreationStrategy; @@ -26,9 +31,33 @@ * @author Dmitry Spikhalskiy */ public class ProtobufSupportModule implements DozerModule { + + private BeanContainer beanContainer; + private DestBeanCreator destBeanCreator; + private PropertyDescriptorFactory propertyDescriptorFactory; + + @Override + public void init(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + public void init() { - DestBeanBuilderCreator.addPluggedStrategy(new ByProtobufBuilder()); - PropertyDescriptorFactory.addPluggedPropertyDescriptorCreationStrategy(new ProtoFieldPropertyDescriptorCreationStrategy()); - BeanMappingGenerator.addPluggedFieldDetector(new ProtobufBeanFieldsDetector()); + } + + @Override + public Collection<BeanBuilderCreationStrategy> getBeanBuilderCreationStrategies() { + return Collections.singleton(new ByProtobufBuilder()); + } + + @Override + public Collection<BeanFieldsDetector> getBeanFieldsDetectors() { + return Collections.singleton(new ProtobufBeanFieldsDetector()); + } + + @Override + public Collection<PropertyDescriptorCreationStrategy> getPropertyDescriptorCreationStrategies() { + return Collections.singleton(new ProtoFieldPropertyDescriptorCreationStrategy(beanContainer, destBeanCreator, propertyDescriptorFactory)); } } diff --git a/proto/src/main/java/org/dozer/classmap/generator/ProtobufBeanFieldsDetector.java b/proto/src/main/java/org/dozer/classmap/generator/ProtobufBeanFieldsDetector.java index 443e0344b..d56fd35b3 100644 --- a/proto/src/main/java/org/dozer/classmap/generator/ProtobufBeanFieldsDetector.java +++ b/proto/src/main/java/org/dozer/classmap/generator/ProtobufBeanFieldsDetector.java @@ -27,7 +27,7 @@ /** * @author Dmitry Spikhalskiy */ -public class ProtobufBeanFieldsDetector implements BeanMappingGenerator.BeanFieldsDetector { +public class ProtobufBeanFieldsDetector implements BeanFieldsDetector { public boolean accepts(Class<?> clazz) { return Message.class.isAssignableFrom(clazz); } diff --git a/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptor.java b/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptor.java index b5ddf7287..a2e8ea084 100644 --- a/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptor.java +++ b/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptor.java @@ -24,6 +24,8 @@ import org.dozer.BeanBuilder; import org.dozer.MappingException; import org.dozer.builder.ProtoBeanBuilder; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.FieldMap; import org.dozer.fieldmap.HintContainer; import org.dozer.util.DeepHierarchyUtils; @@ -38,8 +40,16 @@ public class ProtoFieldPropertyDescriptor extends AbstractPropertyDescriptor { private final Logger logger = LoggerFactory.getLogger(ProtoFieldPropertyDescriptor.class); - public ProtoFieldPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public ProtoFieldPropertyDescriptor(Class<?> clazz, String fieldName, boolean isIndexed, int index, HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, + BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { super(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; } private Class<?> _propertyType; @@ -51,18 +61,18 @@ public Class<?> getPropertyType() { Class<?> result; if (MappingUtils.isDeepMapping(fieldName)) { try { - result = DeepHierarchyUtils.getDeepFieldType(clazz, fieldName, srcDeepIndexHintContainer); + result = DeepHierarchyUtils.getDeepFieldType(clazz, fieldName, srcDeepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); } catch (Exception ignore) { logger.info("Determine field type by srcDeepIndexHintContainer failed"); try { - result = DeepHierarchyUtils.getDeepFieldType(clazz, fieldName, destDeepIndexHintContainer); + result = DeepHierarchyUtils.getDeepFieldType(clazz, fieldName, destDeepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); } catch (Exception secondIgnore) { logger.info("Determine field type by destDeepIndexHintContainer failed"); result = null; } } } else { - result = ProtoUtils.getJavaClass(getFieldDescriptor()); + result = ProtoUtils.getJavaClass(getFieldDescriptor(), beanContainer); } this._propertyType = result; @@ -75,7 +85,7 @@ public Class<?> getPropertyType() { public Object getPropertyValue(Object bean) { Object result; if (MappingUtils.isDeepMapping(fieldName)) { - result = DeepHierarchyUtils.getDeepFieldValue(bean, fieldName, isIndexed, index, srcDeepIndexHintContainer); + result = DeepHierarchyUtils.getDeepFieldValue(bean, fieldName, isIndexed, index, srcDeepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); } else { result = getSimplePropertyValue(bean); if (isIndexed) { @@ -96,7 +106,7 @@ private Object getSimplePropertyValue(Object bean) { } Object value = ProtoUtils.getFieldValue(bean, fieldName); - return ProtoUtils.unwrapEnums(value); + return ProtoUtils.unwrapEnums(value, beanContainer); } @Override @@ -136,18 +146,18 @@ public Class<?> genericType() { Class<?> result; if (MappingUtils.isDeepMapping(fieldName)) { try { - result = DeepHierarchyUtils.getDeepGenericType(clazz, fieldName, srcDeepIndexHintContainer); + result = DeepHierarchyUtils.getDeepGenericType(clazz, fieldName, srcDeepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); } catch (Exception ignore) { logger.info("Determine field generic type by srcDeepIndexHintContainer failed"); try { - result = DeepHierarchyUtils.getDeepGenericType(clazz, fieldName, destDeepIndexHintContainer); + result = DeepHierarchyUtils.getDeepGenericType(clazz, fieldName, destDeepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); } catch (Exception secondIgnore) { logger.info("Determine field generic type by destDeepIndexHintContainer failed"); result = null; } } } else { - result = ProtoUtils.getJavaGenericClassForCollection(getFieldDescriptor()); + result = ProtoUtils.getJavaGenericClassForCollection(getFieldDescriptor(), beanContainer); } this._genericType = result; diff --git a/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategy.java b/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategy.java index 55ae3bb0e..cad230982 100644 --- a/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategy.java +++ b/proto/src/main/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategy.java @@ -18,6 +18,8 @@ import com.google.protobuf.Descriptors; import com.google.protobuf.Message; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.fieldmap.HintContainer; import org.dozer.util.MappingUtils; import org.dozer.util.ProtoUtils; @@ -26,9 +28,20 @@ * @author Dmitry Spikhalskiy */ public class ProtoFieldPropertyDescriptorCreationStrategy implements PropertyDescriptorCreationStrategy { + + private final BeanContainer beanContainer; + private final DestBeanCreator destBeanCreator; + private final PropertyDescriptorFactory propertyDescriptorFactory; + + public ProtoFieldPropertyDescriptorCreationStrategy(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { + this.beanContainer = beanContainer; + this.destBeanCreator = destBeanCreator; + this.propertyDescriptorFactory = propertyDescriptorFactory; + } + @Override public DozerPropertyDescriptor buildFor(Class<?> clazz, String fieldName, boolean isIndexed, int index, HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer) { - return new ProtoFieldPropertyDescriptor(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer); + return new ProtoFieldPropertyDescriptor(clazz, fieldName, isIndexed, index, srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator, propertyDescriptorFactory); } @Override diff --git a/proto/src/main/java/org/dozer/util/ProtoUtils.java b/proto/src/main/java/org/dozer/util/ProtoUtils.java index 3996475f5..a51d8ffdc 100644 --- a/proto/src/main/java/org/dozer/util/ProtoUtils.java +++ b/proto/src/main/java/org/dozer/util/ProtoUtils.java @@ -28,6 +28,7 @@ import com.google.protobuf.ProtocolMessageEnum; import org.apache.commons.lang3.StringUtils; +import org.dozer.config.BeanContainer; /** * @author Dmitry Spikhalskiy @@ -98,7 +99,7 @@ public static Object getFieldValue(Object message, String fieldName) { return null; } - public static Class<?> getJavaClass(final Descriptors.FieldDescriptor descriptor) { + public static Class<?> getJavaClass(final Descriptors.FieldDescriptor descriptor, BeanContainer beanContainer) { if (descriptor.isMapField()) { return Map.class; } @@ -107,18 +108,18 @@ public static Class<?> getJavaClass(final Descriptors.FieldDescriptor descriptor return List.class; } - return getJavaClassIgnoreRepeated(descriptor); + return getJavaClassIgnoreRepeated(descriptor, beanContainer); } - public static Class<?> getJavaGenericClassForCollection(final Descriptors.FieldDescriptor descriptor) { + public static Class<?> getJavaGenericClassForCollection(final Descriptors.FieldDescriptor descriptor, BeanContainer beanContainer) { if (!descriptor.isRepeated()) { return null; } - return getJavaClassIgnoreRepeated(descriptor); + return getJavaClassIgnoreRepeated(descriptor, beanContainer); } - private static Class<?> getJavaClassIgnoreRepeated(final Descriptors.FieldDescriptor descriptor) { + private static Class<?> getJavaClassIgnoreRepeated(final Descriptors.FieldDescriptor descriptor, BeanContainer beanContainer) { switch (descriptor.getJavaType()) { case INT: return Integer.class; @@ -136,10 +137,10 @@ private static Class<?> getJavaClassIgnoreRepeated(final Descriptors.FieldDescri return ByteString.class; //code duplicate, but GenericDescriptor interface is private in protobuf case ENUM: - return getEnumClassByEnumDescriptor(descriptor.getEnumType()); + return getEnumClassByEnumDescriptor(descriptor.getEnumType(), beanContainer); case MESSAGE: return MappingUtils.loadClass(StringUtils.join( - getFullyQualifiedClassName(descriptor.getMessageType().getFile().getOptions(), descriptor.getMessageType().getName()), '.')); + getFullyQualifiedClassName(descriptor.getMessageType().getFile().getOptions(), descriptor.getMessageType().getName()), '.'), beanContainer); default: throw new RuntimeException(); } @@ -152,9 +153,9 @@ private static String[] getFullyQualifiedClassName(DescriptorProtos.FileOptions name}; } - private static Class<? extends Enum> getEnumClassByEnumDescriptor(Descriptors.EnumDescriptor descriptor) { + private static Class<? extends Enum> getEnumClassByEnumDescriptor(Descriptors.EnumDescriptor descriptor, BeanContainer beanContainer) { return (Class<? extends Enum>)MappingUtils.loadClass(StringUtils.join( - getFullyQualifiedClassName(descriptor.getFile().getOptions(), descriptor.getName()), '.')); + getFullyQualifiedClassName(descriptor.getFile().getOptions(), descriptor.getName()), '.'), beanContainer); } public static Object wrapEnums(Object value) { @@ -174,10 +175,10 @@ public static Object wrapEnums(Object value) { return value; } - public static Object unwrapEnums(Object value) { + public static Object unwrapEnums(Object value, BeanContainer beanContainer) { if (value instanceof Descriptors.EnumValueDescriptor) { Descriptors.EnumValueDescriptor descriptor = (Descriptors.EnumValueDescriptor)value; - Class<? extends Enum> enumClass = getEnumClassByEnumDescriptor(descriptor.getType()); + Class<? extends Enum> enumClass = getEnumClassByEnumDescriptor(descriptor.getType(), beanContainer); Enum[] enumValues = enumClass.getEnumConstants(); for (Enum enumValue : enumValues) { if (((Descriptors.EnumValueDescriptor)value).getName().equals(enumValue.name())) { @@ -190,7 +191,7 @@ public static Object unwrapEnums(Object value) { if (value instanceof Collection) { List modifiedList = new ArrayList(((List)value).size()); for (Object element : (List)value) { - modifiedList.add(unwrapEnums(element)); + modifiedList.add(unwrapEnums(element, beanContainer)); } return modifiedList; } diff --git a/proto/src/test/java/org/dozer/functional_tests/ProtoAbstractTest.java b/proto/src/test/java/org/dozer/functional_tests/ProtoAbstractTest.java index fce54f52d..561e93d5b 100644 --- a/proto/src/test/java/org/dozer/functional_tests/ProtoAbstractTest.java +++ b/proto/src/test/java/org/dozer/functional_tests/ProtoAbstractTest.java @@ -19,6 +19,7 @@ import java.util.List; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.util.DozerConstants; import org.junit.Ignore; @@ -32,7 +33,7 @@ protected DozerBeanMapper getMapper(List<String> fileNames) { System.setProperty("log4j.debug", "true"); System.setProperty(DozerConstants.DEBUG_SYS_PROP, "true"); - DozerBeanMapper mapper = new DozerBeanMapper(); + DozerBeanMapper mapper = DozerBeanMapperBuilder.buildDefault(); mapper.setMappingFiles(fileNames); return mapper; diff --git a/proto/src/test/java/org/dozer/functional_tests/ProtoBeansMappingTest.java b/proto/src/test/java/org/dozer/functional_tests/ProtoBeansMappingTest.java index fe7cbd2fe..e28a352f4 100644 --- a/proto/src/test/java/org/dozer/functional_tests/ProtoBeansMappingTest.java +++ b/proto/src/test/java/org/dozer/functional_tests/ProtoBeansMappingTest.java @@ -19,6 +19,7 @@ import org.dozer.DozerBeanMapper; import org.dozer.MappingException; +import org.dozer.config.BeanContainer; import org.dozer.util.MappingUtils; import org.dozer.vo.proto.LiteTestObject; import org.dozer.vo.proto.MapExample; @@ -56,15 +57,17 @@ public class ProtoBeansMappingTest extends ProtoAbstractTest { public ExpectedException thrown = ExpectedException.none(); protected DozerBeanMapper mapper; + private BeanContainer beanContainer; @Before public void setUp() throws Exception { + beanContainer = new BeanContainer(); mapper = getMapper("mappings/protoBeansMapping.xml"); } @Test public void testTrivial() { - Class<?> type = MappingUtils.loadClass("org.dozer.vo.proto.ProtoTestObjects.SimpleProtoTestObject"); + Class<?> type = MappingUtils.loadClass("org.dozer.vo.proto.ProtoTestObjects.SimpleProtoTestObject", beanContainer); assertNotNull(type); } diff --git a/proto/src/test/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategyTest.java b/proto/src/test/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategyTest.java index 154aedf85..1ffb7293d 100644 --- a/proto/src/test/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategyTest.java +++ b/proto/src/test/java/org/dozer/propertydescriptor/ProtoFieldPropertyDescriptorCreationStrategyTest.java @@ -15,6 +15,8 @@ */ package org.dozer.propertydescriptor; +import org.dozer.config.BeanContainer; +import org.dozer.factory.DestBeanCreator; import org.dozer.vo.proto.ProtoTestObjects; import org.junit.Before; import org.junit.Test; @@ -31,7 +33,9 @@ public class ProtoFieldPropertyDescriptorCreationStrategyTest { @Before public void setUp() throws Exception { - strategy = new ProtoFieldPropertyDescriptorCreationStrategy(); + BeanContainer beanContainer = new BeanContainer(); + DestBeanCreator destBeanCreator = new DestBeanCreator(beanContainer); + strategy = new ProtoFieldPropertyDescriptorCreationStrategy(beanContainer, destBeanCreator, new PropertyDescriptorFactory()); } @Test diff --git a/spring/src/main/java/org/dozer/spring/DozerBeanMapperFactoryBean.java b/spring/src/main/java/org/dozer/spring/DozerBeanMapperFactoryBean.java index 0c4b48dae..a142e863b 100644 --- a/spring/src/main/java/org/dozer/spring/DozerBeanMapperFactoryBean.java +++ b/spring/src/main/java/org/dozer/spring/DozerBeanMapperFactoryBean.java @@ -26,6 +26,7 @@ import org.dozer.CustomConverter; import org.dozer.CustomFieldMapper; import org.dozer.DozerBeanMapper; +import org.dozer.DozerBeanMapperBuilder; import org.dozer.DozerEventListener; import org.dozer.Mapper; import org.dozer.loader.api.BeanMappingBuilder; @@ -116,7 +117,7 @@ public final boolean isSingleton() { // interface 'InitializingBean' // ================================================================================================================================== public final void afterPropertiesSet() throws Exception { - this.beanMapper = new DozerBeanMapper(); + this.beanMapper = DozerBeanMapperBuilder.buildDefault(); loadMappingFiles(); diff --git a/spring/src/test/java/org/dozer/spring/functional_tests/support/SampleCustomBeanFactory.java b/spring/src/test/java/org/dozer/spring/functional_tests/support/SampleCustomBeanFactory.java index 3ac3580b8..c7e160176 100644 --- a/spring/src/test/java/org/dozer/spring/functional_tests/support/SampleCustomBeanFactory.java +++ b/spring/src/test/java/org/dozer/spring/functional_tests/support/SampleCustomBeanFactory.java @@ -16,13 +16,14 @@ package org.dozer.spring.functional_tests.support; import org.dozer.BeanFactory; +import org.dozer.config.BeanContainer; /** * @author Dmitry Buzdin */ public class SampleCustomBeanFactory implements BeanFactory { - public Object createBean(Object srcObj, Class<?> srcObjClass, String id) { + public Object createBean(Object srcObj, Class<?> srcObjClass, String id, BeanContainer beanContainer) { try { return Class.forName(id).newInstance(); } catch (Exception e) { diff --git a/spring/src/test/resources/applicationContext.xml b/spring/src/test/resources/applicationContext.xml index 848282a43..a32d74a20 100644 --- a/spring/src/test/resources/applicationContext.xml +++ b/spring/src/test/resources/applicationContext.xml @@ -24,7 +24,9 @@ <import resource="classpath:spring-event-listener.xml"/> <import resource="classpath:spring-bean-mapping-builder.xml"/> - <bean id="implicitMapper" class="org.dozer.DozerBeanMapper" scope="singleton"/> + <bean id="implicitMapper" + class="org.dozer.DozerBeanMapperBuilder" + factory-method="buildDefault"/> <!-- Provided Spring Integration --> <bean id="byFactory" class="org.dozer.spring.DozerBeanMapperFactoryBean"> diff --git a/spring/src/test/resources/spring-bean-factory.xml b/spring/src/test/resources/spring-bean-factory.xml index 805d89eff..42b6f99ea 100755 --- a/spring/src/test/resources/spring-bean-factory.xml +++ b/spring/src/test/resources/spring-bean-factory.xml @@ -20,7 +20,9 @@ "http://www.springframework.org/dtd/spring-beans.dtd"> <beans default-lazy-init="false"> - <bean id="mapperWithBeanFactory" class="org.dozer.DozerBeanMapper" scope="singleton"> + <bean id="mapperWithBeanFactory" + class="org.dozer.DozerBeanMapperBuilder" + factory-method="buildDefault"> <property name="mappingFiles"> <list> <value>mappingSpring.xml</value> diff --git a/spring/src/test/resources/spring-custom-converter.xml b/spring/src/test/resources/spring-custom-converter.xml index 63ce34e89..1a619be0a 100644 --- a/spring/src/test/resources/spring-custom-converter.xml +++ b/spring/src/test/resources/spring-custom-converter.xml @@ -21,7 +21,9 @@ <beans> <!-- Semi-Manual Solution --> - <bean id="mapperWithConverter" class="org.dozer.DozerBeanMapper"> + <bean id="mapperWithConverter" + class="org.dozer.DozerBeanMapperBuilder" + factory-method="buildDefault"> <property name="customConverters"> <list> <ref bean="converter"/> diff --git a/spring/src/test/resources/spring-event-listener.xml b/spring/src/test/resources/spring-event-listener.xml index dd92ce9b7..2b01cc530 100644 --- a/spring/src/test/resources/spring-event-listener.xml +++ b/spring/src/test/resources/spring-event-listener.xml @@ -20,7 +20,9 @@ "http://www.springframework.org/dtd/spring-beans.dtd"> <beans default-lazy-init="false"> - <bean id="mapperWithEventListener" class="org.dozer.DozerBeanMapper" scope="singleton"> + <bean id="mapperWithEventListener" + class="org.dozer.DozerBeanMapperBuilder" + factory-method="buildDefault"> <property name="eventListeners"> <list> <ref bean="eventTestListener"/>
10c4f93ae28a5c0746783dd4cbec6bf20a11bad8
evllabs$jgaap
slight optimizations to distances
p
https://github.com/evllabs/jgaap
diff --git a/src/com/jgaap/distances/BrayCurtisDistance.java b/src/com/jgaap/distances/BrayCurtisDistance.java index 6021e5466..14de61bc5 100644 --- a/src/com/jgaap/distances/BrayCurtisDistance.java +++ b/src/com/jgaap/distances/BrayCurtisDistance.java @@ -3,7 +3,6 @@ import java.util.HashSet; import java.util.Set; -import com.jgaap.generics.DistanceCalculationException; import com.jgaap.generics.DistanceFunction; import com.jgaap.generics.Event; import com.jgaap.generics.EventMap; @@ -34,8 +33,7 @@ public boolean showInGUI() { } @Override - public double distance(EventMap unknownEventMap, EventMap knownEventMap) - throws DistanceCalculationException { + public double distance(EventMap unknownEventMap, EventMap knownEventMap) { Set<Event> events = new HashSet<Event>(unknownEventMap.uniqueEvents()); events.addAll(knownEventMap.uniqueEvents()); @@ -43,8 +41,10 @@ public double distance(EventMap unknownEventMap, EventMap knownEventMap) double distance = 0.0, sumNumer = 0.0, sumDenom = 0.0; for(Event event: events){ - sumNumer += Math.abs(unknownEventMap.relativeFrequency(event) - knownEventMap.relativeFrequency(event)); - sumDenom += unknownEventMap.relativeFrequency(event) + knownEventMap.relativeFrequency(event); + double known = knownEventMap.relativeFrequency(event); + double unknown = unknownEventMap.relativeFrequency(event); + sumNumer += Math.abs(unknown - known); + sumDenom += unknown + known; } distance = sumNumer / sumDenom; return distance; diff --git a/src/com/jgaap/distances/SoergleDistance.java b/src/com/jgaap/distances/SoergleDistance.java index 8cfef0782..432182454 100644 --- a/src/com/jgaap/distances/SoergleDistance.java +++ b/src/com/jgaap/distances/SoergleDistance.java @@ -43,8 +43,10 @@ public double distance(EventMap unknownEventMap, EventMap knownEventMap) double distance = 0.0, sumNumer = 0.0, sumDenom = 0.0; for(Event event : events){ - sumNumer += Math.abs(unknownEventMap.relativeFrequency(event) - knownEventMap.relativeFrequency(event)); - sumDenom += Math.max(unknownEventMap.relativeFrequency(event), knownEventMap.relativeFrequency(event)); + double known = knownEventMap.relativeFrequency(event); + double unknown = unknownEventMap.relativeFrequency(event); + sumNumer += Math.abs(unknown - known); + sumDenom += Math.max(unknown, known); } distance = sumNumer / sumDenom;
040fa2581a8a9b51fb154a5e5ae8aff6c8cd291d
elasticsearch
Added GeoDistance test which verifies the- difference in behaviour between ARC and PLANE
a
https://github.com/elastic/elasticsearch
diff --git a/src/test/java/org/elasticsearch/test/unit/index/search/geo/GeoDistanceTests.java b/src/test/java/org/elasticsearch/test/unit/index/search/geo/GeoDistanceTests.java index 3783357c3fe18..649769e26d5cf 100644 --- a/src/test/java/org/elasticsearch/test/unit/index/search/geo/GeoDistanceTests.java +++ b/src/test/java/org/elasticsearch/test/unit/index/search/geo/GeoDistanceTests.java @@ -21,10 +21,13 @@ import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.index.search.geo.GeoDistance; +import org.elasticsearch.index.search.geo.Point; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.lessThan; /** */ @@ -35,18 +38,33 @@ public class GeoDistanceTests { public void testDistanceCheck() { // Note, is within is an approximation, so, even though 0.52 is outside 50mi, we still get "true" GeoDistance.DistanceBoundingCheck check = GeoDistance.distanceBoundingCheck(0, 0, 50, DistanceUnit.MILES); - //System.out.println("Dist: " + GeoDistance.ARC.calculate(0, 0, 0.5, 0.5, DistanceUnit.MILES)); assertThat(check.isWithin(0.5, 0.5), equalTo(true)); - //System.out.println("Dist: " + GeoDistance.ARC.calculate(0, 0, 0.52, 0.52, DistanceUnit.MILES)); assertThat(check.isWithin(0.52, 0.52), equalTo(true)); - //System.out.println("Dist: " + GeoDistance.ARC.calculate(0, 0, 1, 1, DistanceUnit.MILES)); assertThat(check.isWithin(1, 1), equalTo(false)); - check = GeoDistance.distanceBoundingCheck(0, 179, 200, DistanceUnit.MILES); - //System.out.println("Dist: " + GeoDistance.ARC.calculate(0, 179, 0, -179, DistanceUnit.MILES)); assertThat(check.isWithin(0, -179), equalTo(true)); - //System.out.println("Dist: " + GeoDistance.ARC.calculate(0, 179, 0, -178, DistanceUnit.MILES)); assertThat(check.isWithin(0, -178), equalTo(false)); } + + @Test + public void testArcDistanceVsPlaneInEllipsis() { + Point centre = new Point(48.8534100, 2.3488000); + Point northernPoint = new Point(48.8801108681, 2.35152032666); + Point westernPoint = new Point(48.85265, 2.308896); + + // With GeoDistance.ARC both the northern and western points are within the 4km range + assertThat(GeoDistance.ARC.calculate(centre.lat, centre.lon, northernPoint.lat, + northernPoint.lon, DistanceUnit.KILOMETERS), lessThan(4D)); + assertThat(GeoDistance.ARC.calculate(centre.lat, centre.lon, westernPoint.lat, + westernPoint.lon, DistanceUnit.KILOMETERS), lessThan(4D)); + + // With GeoDistance.PLANE, only the northern point is within the 4km range, + // the western point is outside of the range due to the simple math it employs, + // meaning results will appear elliptical + assertThat(GeoDistance.PLANE.calculate(centre.lat, centre.lon, northernPoint.lat, + northernPoint.lon, DistanceUnit.KILOMETERS), lessThan(4D)); + assertThat(GeoDistance.PLANE.calculate(centre.lat, centre.lon, westernPoint.lat, + westernPoint.lon, DistanceUnit.KILOMETERS), greaterThan(4D)); + } }
935820dbb5b80a81e66f432ec5199516bc98e998
Valadoc
driver/0.11.0: Add support for attributes
a
https://github.com/GNOME/vala/
diff --git a/src/driver/0.11.0/treebuilder.vala b/src/driver/0.11.0/treebuilder.vala index be416330bc..93c5f3c4a0 100644 --- a/src/driver/0.11.0/treebuilder.vala +++ b/src/driver/0.11.0/treebuilder.vala @@ -184,6 +184,55 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { // Translation helpers: // + private void process_attributes (Api.Symbol parent, GLib.List<Vala.Attribute> lst) { + // attributes wihtout arguments: + string[] attributes = { + "ReturnsModifiedPointer", + "DestroysInstance", + "NoAccessorMethod", + "NoArrayLength", + "Experimental", + "Diagnostics", + "PrintfFormat", + "PointerType", + "ScanfFormat", + "ThreadLocal", + "SimpleType", + "HasEmitter", + "ModuleInit", + "NoWrapper", + "Immutable", + "ErrorBase", + "NoReturn", + "NoThrow", + "Assert", + "Flags" + }; + + string? tmp = ""; + + foreach (Vala.Attribute att in lst) { + if (att.name == "CCode" && (tmp = att.args.get ("has_target")) != null && tmp == "false") { + Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att); + new_attribute.add_boolean ("has_target", false, att); + parent.add_attribute (new_attribute); + } else if (att.name == "Deprecated") { + Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att); + parent.add_attribute (new_attribute); + if ((tmp = att.args.get ("since")) != null) { + new_attribute.add_string ("since", tmp, att); + } + + if ((tmp = att.args.get ("replacement")) != null) { + new_attribute.add_string ("replacement", tmp, att); + } + } else if (att.name in attributes) { + Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att); + parent.add_attribute (new_attribute); + } + } + } + private SourceComment? create_comment (Vala.Comment? comment) { if (comment != null) { Vala.SourceReference pos = comment.source_reference; @@ -737,6 +786,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { } } + process_attributes (node, element.attributes); process_children (node, element); // save GLib.Error @@ -767,6 +817,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { } } + process_attributes (node, element.attributes); process_children (node, element); } @@ -790,6 +841,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { node.base_type = create_type_reference (basetype, node, node); } + process_attributes (node, element.attributes); process_children (node, element); } @@ -806,6 +858,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -833,6 +886,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { node.setter = new PropertyAccessor (node, file, element.name, get_access_modifier(element), accessor.get_cname(), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor); } + process_attributes (node, element.attributes); process_children (node, element); } @@ -849,6 +903,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -865,6 +920,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -881,6 +937,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -897,6 +954,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -912,6 +970,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -927,6 +986,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -943,6 +1003,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -958,6 +1019,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -973,6 +1035,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); }
465445e456d3575941cbf8d9d1ba71be96d1f93c
Search_api
Issue #2010116 by drunken monkey: Enabled "Index items immediately" for the default node index.
a
https://github.com/lucidworks/drupal_search_api
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 0a21b9ea..a44637a4 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,7 @@ Search API 1.x, dev (xx/xx/xxxx): --------------------------------- +- #2010116 by drunken monkey: Enabled "Index items immediately" for the default + node index. - #2013581 by drunken monkey: Added multi-valued field to test module. - #1288724 by brunodbo, drunken monkey, fearlsgroove: Added option for using OR in Views fulltext search. diff --git a/search_api.install b/search_api.install index 8fbb0e4a..09e8bb58 100644 --- a/search_api.install +++ b/search_api.install @@ -214,6 +214,7 @@ function search_api_install() { 'server' => NULL, 'item_type' => 'node', 'options' => array( + 'index_directly' => 1, 'cron_limit' => '50', 'data_alter_callbacks' => array( 'search_api_alter_node_access' => array(
788d431d98df0087a4ea7be7b3c82c4c5d2a8209
ReactiveX-RxJava
Implemented periodic scheduling
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java b/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java index e7883c69a1..ffa731a85e 100644 --- a/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java +++ b/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java @@ -31,6 +31,7 @@ import rx.Scheduler; import rx.Subscription; +import rx.subscriptions.CompositeSubscription; import rx.subscriptions.Subscriptions; import rx.util.functions.Action0; import rx.util.functions.Func2; @@ -73,11 +74,7 @@ public void call() { public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action, long dueTime, TimeUnit unit) { final AtomicReference<Subscription> sub = new AtomicReference<Subscription>(); long delay = unit.toMillis(dueTime); - - if (delay > Integer.MAX_VALUE) { - throw new IllegalArgumentException(String.format( - "The swing timer only accepts delays up to %d milliseconds.", Integer.MAX_VALUE)); - } + assertThatTheDelayIsValidForTheSwingTimer(delay); class ExecuteOnceAction implements ActionListener { private Timer timer; @@ -110,6 +107,52 @@ public void call() { } }); } + + @Override + public <T> Subscription schedulePeriodically(T state, final Func2<Scheduler, T, Subscription> action, long initialDelay, long period, TimeUnit unit) { + // FIXME test this! + final AtomicReference<Timer> timer = new AtomicReference<Timer>(); + + final long delay = unit.toMillis(period); + assertThatTheDelayIsValidForTheSwingTimer(delay); + + final CompositeSubscription subscriptions = new CompositeSubscription(); + final Func2<Scheduler, T, Subscription> initialAction = new Func2<Scheduler, T, Subscription>() { + @Override + public Subscription call(final Scheduler scheduler, final T state) { + // call the action once initially + subscriptions.add(action.call(scheduler, state)); + + // start timer for periodic execution, collect subscriptions + timer.set(new Timer((int) delay, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + subscriptions.add(action.call(scheduler, state)); + } + })); + timer.get().start(); + + return action.call(scheduler, state); + } + }; + subscriptions.add(schedule(state, initialAction, initialDelay, unit)); + + subscriptions.add(Subscriptions.create(new Action0() { + @Override + public void call() { + // in addition to all the individual unsubscriptions, stop the timer on unsubscribing + timer.get().stop(); + } + })); + + return subscriptions; + } + + private static void assertThatTheDelayIsValidForTheSwingTimer(long delay) { + if (delay > Integer.MAX_VALUE) { + throw new IllegalArgumentException(String.format("The swing timer only accepts delays up to %d milliseconds.", Integer.MAX_VALUE)); + } + } public static class UnitTest { @Test
8bba1e439e933b716ce64a8f029c3e84ed5a2d18
Mylyn Reviews
ReviewScope is optional
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext index a6cdc67f..5aac21b0 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext +++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext @@ -21,10 +21,11 @@ LineComment: "Line " start=INT ("-" end=INT)? ":" comment=STRING; ReviewScope: - "Review scope:" +{ReviewScope}"Review scope:" ( scope+=ReviewScopeItem - )+; + )* + ; ChangedReviewScope: "Updated review scope:"
52bf7e145152f3b9c5d1ffe07247bab5f95bdde9
ReactiveX-RxJava
Set threads to daemons so they don't prevent system- from exiting--- This applies to any pools RxJava itself creates. It will be up to users to do this for Executors they inject.-
c
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/concurrency/ExecutorScheduler.java b/rxjava-core/src/main/java/rx/concurrency/ExecutorScheduler.java index bed7e5f6c8..133f772889 100644 --- a/rxjava-core/src/main/java/rx/concurrency/ExecutorScheduler.java +++ b/rxjava-core/src/main/java/rx/concurrency/ExecutorScheduler.java @@ -53,7 +53,9 @@ public class ExecutorScheduler extends AbstractScheduler { @Override public Thread newThread(Runnable r) { - return new Thread(r, "RxScheduledExecutorPool-" + counter.incrementAndGet()); + Thread t = new Thread(r, "RxScheduledExecutorPool-" + counter.incrementAndGet()); + t.setDaemon(true); + return t; } }); diff --git a/rxjava-core/src/main/java/rx/concurrency/Schedulers.java b/rxjava-core/src/main/java/rx/concurrency/Schedulers.java index bd35ab58ff..f805917b83 100644 --- a/rxjava-core/src/main/java/rx/concurrency/Schedulers.java +++ b/rxjava-core/src/main/java/rx/concurrency/Schedulers.java @@ -118,7 +118,9 @@ private static ScheduledExecutorService createComputationExecutor() { @Override public Thread newThread(Runnable r) { - return new Thread(r, "RxComputationThreadPool-" + counter.incrementAndGet()); + Thread t = new Thread(r, "RxComputationThreadPool-" + counter.incrementAndGet()); + t.setDaemon(true); + return t; } }); } @@ -129,7 +131,9 @@ private static Executor createIOExecutor() { @Override public Thread newThread(Runnable r) { - return new Thread(r, "RxIOThreadPool-" + counter.incrementAndGet()); + Thread t = new Thread(r, "RxIOThreadPool-" + counter.incrementAndGet()); + t.setDaemon(true); + return t; } });
ea413ab4a18b4fdeb7e1166ee2e6edbdacf2b49c
Delta Spike
DELTASPIKE-402 introduce a way to conditionally skip test based on cdi-container versions
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/partial-bean/impl/src/test/java/org/apache/deltaspike/test/core/api/partialbean/uc003/PartialBeanAsAbstractClassWithInterceptorTest.java b/deltaspike/modules/partial-bean/impl/src/test/java/org/apache/deltaspike/test/core/api/partialbean/uc003/PartialBeanAsAbstractClassWithInterceptorTest.java index 40fadde33..eca179948 100644 --- a/deltaspike/modules/partial-bean/impl/src/test/java/org/apache/deltaspike/test/core/api/partialbean/uc003/PartialBeanAsAbstractClassWithInterceptorTest.java +++ b/deltaspike/modules/partial-bean/impl/src/test/java/org/apache/deltaspike/test/core/api/partialbean/uc003/PartialBeanAsAbstractClassWithInterceptorTest.java @@ -22,6 +22,7 @@ import org.apache.deltaspike.test.core.api.partialbean.shared.CustomInterceptorImpl; import org.apache.deltaspike.test.core.api.partialbean.shared.TestPartialBeanBinding; import org.apache.deltaspike.test.core.api.partialbean.util.ArchiveUtils; +import org.apache.deltaspike.test.utils.CdiContainerUnderTest; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; @@ -31,22 +32,33 @@ import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; +import org.junit.Assume; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import javax.enterprise.inject.Instance; import javax.inject.Inject; @RunWith(Arquillian.class) @Category(SeCategory.class) //TODO use different category (only new versions of weld) public class PartialBeanAsAbstractClassWithInterceptorTest { + public static final String CONTAINER_WELD_2_0_0 = "weld-2\\.0\\.0\\..*"; + + // we only inject an Instance as the proxy creation for the Bean itself + // would trigger a nasty bug in Weld-2.0.0 @Inject - private PartialBean partialBean; + private Instance<PartialBean> partialBean; @Deployment public static WebArchive war() { + if (CdiContainerUnderTest.is(CONTAINER_WELD_2_0_0)) + { + return ShrinkWrap.create(WebArchive.class, "empty.war"); + } + Asset beansXml = new StringAsset( "<beans><interceptors><class>" + CustomInterceptorImpl.class.getName() + @@ -70,11 +82,14 @@ public static WebArchive war() @Test public void testPartialBeanAsAbstractClassWithInterceptor() throws Exception { - String result = this.partialBean.getResult(); + // this test is known to not work under weld-2.0.0.Final and weld-2.0.0.SP1 + Assume.assumeTrue(!CdiContainerUnderTest.is(CONTAINER_WELD_2_0_0)); + + String result = this.partialBean.get().getResult(); Assert.assertEquals("partial-test-true", result); - result = this.partialBean.getManualResult(); + result = this.partialBean.get().getManualResult(); //"manual-test-true" would be the goal, but it isn't supported (for now) Assert.assertEquals("manual-test-false", result); diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml index e6a324588..97ecb03df 100644 --- a/deltaspike/parent/code/pom.xml +++ b/deltaspike/parent/code/pom.xml @@ -71,6 +71,7 @@ <configuration> <systemProperties> <org.apache.deltaspike.ProjectStage>UnitTest</org.apache.deltaspike.ProjectStage> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> </systemProperties> </configuration> </plugin> @@ -140,12 +141,20 @@ <activeByDefault>true</activeByDefault> </activation> + <properties> + <cdicontainer.version>owb-${owb.version}</cdicontainer.version> + </properties> + <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> + <systemProperties> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> + </systemProperties> + <!-- Ignore these groups because they don't work with embedded OWB --> <excludedGroups> org.apache.deltaspike.test.category.WebProfileCategory, @@ -202,11 +211,19 @@ <!-- use this profile to compile and test DeltaSpike with JBoss Weld --> <id>Weld</id> + <properties> + <cdicontainer.version>weld-${weld.version}</cdicontainer.version> + </properties> + + <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> + <systemProperties> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> + </systemProperties> <!-- Ignore these groups because they don't work with embedded Weld --> <excludedGroups> org.apache.deltaspike.test.category.WebProfileCategory, @@ -312,6 +329,10 @@ --> <id>tomee-build-managed</id> + <properties> + <cdicontainer.version>owb-${owb.version}</cdicontainer.version> + </properties> + <dependencies> <dependency> <groupId>org.apache.openejb</groupId> @@ -345,6 +366,7 @@ <systemProperties> <arquillian.launch>tomee</arquillian.launch> <org.apache.deltaspike.ProjectStage>UnitTest</org.apache.deltaspike.ProjectStage> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> </systemProperties> <!-- we just use groups to mark that a test should be executed only @@ -372,6 +394,9 @@ * --> <id>jbossas-managed-7</id> + <properties> + <cdicontainer.version>weld-${weld.version}</cdicontainer.version> + </properties> <dependencies> <dependency> @@ -419,6 +444,7 @@ <systemProperties> <arquillian.launch>jbossas-managed-7</arquillian.launch> <org.apache.deltaspike.ProjectStage>UnitTest</org.apache.deltaspike.ProjectStage> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> </systemProperties> <!-- we just use groups to mark that a test should be executed only with specific environments. even though a java-ee6 application server has to be able to run @@ -446,6 +472,11 @@ * --> <id>jbossas-build-managed-7</id> + + <properties> + <cdicontainer.version>weld-${weld.version}</cdicontainer.version> + </properties> + <dependencies> <dependency> <groupId>javax.enterprise</groupId> @@ -485,6 +516,7 @@ ${project.build.directory}/jboss-as-${jboss.as.version} </arquillian.jboss_home> <org.apache.deltaspike.ProjectStage>UnitTest</org.apache.deltaspike.ProjectStage> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> </systemProperties> <!-- we just use groups to mark that a test should be executed only with specific environments. even though a java-ee6 application server has to be able to run @@ -531,6 +563,11 @@ <profile> <id>jbossas-remote-7</id> <!-- AS7 must be started manually for this work correctly - debug hints see arquillian.xml --> + + <properties> + <cdicontainer.version>weld-${weld.version}</cdicontainer.version> + </properties> + <dependencies> <dependency> @@ -568,6 +605,7 @@ <systemProperties> <arquillian.launch>jbossas-remote-7</arquillian.launch> <org.apache.deltaspike.ProjectStage>UnitTest</org.apache.deltaspike.ProjectStage> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> </systemProperties> <!-- we just use groups to mark that a test should be executed only with specific environments. even though a java-ee6 application server has to be able to run @@ -586,6 +624,11 @@ <profile> <id>glassfish-remote-3.1</id> + + <properties> + <cdicontainer.version>weld-${weld.version}</cdicontainer.version> + </properties> + <dependencies> <dependency> <groupId>javax.enterprise</groupId> @@ -628,6 +671,7 @@ <systemProperties> <arquillian.launch>glassfish-remote-3.1</arquillian.launch> <org.apache.deltaspike.ProjectStage>UnitTest</org.apache.deltaspike.ProjectStage> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> </systemProperties> <!-- we just use groups to mark that a test should be executed only with specific environments. even though a java-ee6 application server has to be able to run @@ -646,6 +690,11 @@ <profile> <id>wls-remote-12c</id> + + <properties> + <cdicontainer.version>weld-${weld.version}</cdicontainer.version> + </properties> + <dependencies> <dependency> @@ -673,6 +722,7 @@ <systemProperties> <arquillian.launch>wls-remote-12c</arquillian.launch> <org.apache.deltaspike.ProjectStage>UnitTest</org.apache.deltaspike.ProjectStage> + <cdicontainer.version>${cdicontainer.version}</cdicontainer.version> </systemProperties> <systemPropertyVariables> <WLS_HOME>${env.WLS_HOME}</WLS_HOME> diff --git a/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/CdiContainerUnderTest.java b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/CdiContainerUnderTest.java new file mode 100644 index 000000000..ddbf71107 --- /dev/null +++ b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/CdiContainerUnderTest.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.utils; + +/** + * A small helper class which checks if the container + * which is currently being tested matches the given version RegExp + */ +public class CdiContainerUnderTest +{ + private CdiContainerUnderTest() + { + // utility class ct + } + + /** + * Checks whether the current container matches the given version regexps. + * @param containerRegExps container versions to test against. + * e.g. 'owb-1\\.0\\..*' or 'weld-2\\.0\\.0\\..*' + */ + public static boolean is(String... containerRegExps) + { + String containerVersion = System.getProperty("cdicontainer.version"); + + if (containerVersion == null) + { + return false; + } + + for (String containerRe : containerRegExps) + { + if (containerVersion.matches(containerRe)) + { + return true; + } + } + + return false; + } +}
cb8a05ec055238c44e99117b60bbda1a394a5082
tapiji
Remove org.eclipse.babel.tapiji.translator.rbe plug-in.
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.translator.rbe/.classpath b/org.eclipse.babel.tapiji.translator.rbe/.classpath deleted file mode 100644 index 8a8f1668..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/.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.tapiji.translator.rbe/.project b/org.eclipse.babel.tapiji.translator.rbe/.project deleted file mode 100644 index 6a4f6577..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/.project +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.translator.rbe</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.jdt.core.javabuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.ManifestBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.SchemaBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/org.eclipse.babel.tapiji.translator.rbe/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.babel.tapiji.translator.rbe/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 7a56900c..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Tue Jan 25 08:12:08 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.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 b35fd66e..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/META-INF/MANIFEST.MF +++ /dev/null @@ -1,8 +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" diff --git a/org.eclipse.babel.tapiji.translator.rbe/build.properties b/org.eclipse.babel.tapiji.translator.rbe/build.properties deleted file mode 100644 index 90262f14..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - src/ -src.includes = bin/,\ - src/ diff --git a/org.eclipse.babel.tapiji.translator.rbe/epl-v10.html b/org.eclipse.babel.tapiji.translator.rbe/epl-v10.html deleted file mode 100644 index ed4b1966..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/epl-v10.html +++ /dev/null @@ -1,328 +0,0 @@ -<html xmlns:o="urn:schemas-microsoft-com:office:office" -xmlns:w="urn:schemas-microsoft-com:office:word" -xmlns="http://www.w3.org/TR/REC-html40"> - -<head> -<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> -<meta name=ProgId content=Word.Document> -<meta name=Generator content="Microsoft Word 9"> -<meta name=Originator content="Microsoft Word 9"> -<link rel=File-List -href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> -<title>Eclipse Public License - Version 1.0</title> -<!--[if gte mso 9]><xml> - <o:DocumentProperties> - <o:Revision>2</o:Revision> - <o:TotalTime>3</o:TotalTime> - <o:Created>2004-03-05T23:03:00Z</o:Created> - <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> - <o:Pages>4</o:Pages> - <o:Words>1626</o:Words> - <o:Characters>9270</o:Characters> - <o:Lines>77</o:Lines> - <o:Paragraphs>18</o:Paragraphs> - <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> - <o:Version>9.4402</o:Version> - </o:DocumentProperties> -</xml><![endif]--><!--[if gte mso 9]><xml> - <w:WordDocument> - <w:TrackRevisions/> - </w:WordDocument> -</xml><![endif]--> -<style> -<!-- - /* Font Definitions */ -@font-face - {font-family:Tahoma; - panose-1:2 11 6 4 3 5 4 4 2 4; - mso-font-charset:0; - mso-generic-font-family:swiss; - mso-font-pitch:variable; - mso-font-signature:553679495 -2147483648 8 0 66047 0;} - /* Style Definitions */ -p.MsoNormal, li.MsoNormal, div.MsoNormal - {mso-style-parent:""; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p - {margin-right:0in; - mso-margin-top-alt:auto; - mso-margin-bottom-alt:auto; - margin-left:0in; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p.BalloonText, li.BalloonText, div.BalloonText - {mso-style-name:"Balloon Text"; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:8.0pt; - font-family:Tahoma; - mso-fareast-font-family:"Times New Roman";} -@page Section1 - {size:8.5in 11.0in; - margin:1.0in 1.25in 1.0in 1.25in; - mso-header-margin:.5in; - mso-footer-margin:.5in; - mso-paper-source:0;} -div.Section1 - {page:Section1;} ---> -</style> -</head> - -<body lang=EN-US style='tab-interval:.5in'> - -<div class=Section1> - -<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> -</p> - -<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER -THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, -REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE -OF THIS AGREEMENT.</span> </p> - -<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> - -<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -in the case of the initial Contributor, the initial code and documentation -distributed under this Agreement, and<br clear=left> -b) in the case of each subsequent Contributor:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) -changes to the Program, and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -additions to the Program;</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where -such changes and/or additions to the Program originate from and are distributed -by that particular Contributor. A Contribution 'originates' from a Contributor -if it was added to the Program by such Contributor itself or anyone acting on -such Contributor's behalf. Contributions do not include additions to the -Program which: (i) are separate modules of software distributed in conjunction -with the Program under their own license agreement, and (ii) are not derivative -works of the Program. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or -entity that distributes the Program.</span> </p> - -<p><span style='font-size:10.0pt'>&quot;Licensed Patents &quot; mean patent -claims licensable by a Contributor which are necessarily infringed by the use -or sale of its Contribution alone or when combined with the Program. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions -distributed in accordance with this Agreement.</span> </p> - -<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who -receives the Program under this Agreement, including all Contributors.</span> </p> - -<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -Subject to the terms of this Agreement, each Contributor hereby grants Recipient -a non-exclusive, worldwide, royalty-free copyright license to<span -style='color:red'> </span>reproduce, prepare derivative works of, publicly -display, publicly perform, distribute and sublicense the Contribution of such -Contributor, if any, and such derivative works, in source code and object code -form.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -Subject to the terms of this Agreement, each Contributor hereby grants -Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free -patent license under Licensed Patents to make, use, sell, offer to sell, import -and otherwise transfer the Contribution of such Contributor, if any, in source -code and object code form. This patent license shall apply to the combination -of the Contribution and the Program if, at the time the Contribution is added -by the Contributor, such addition of the Contribution causes such combination -to be covered by the Licensed Patents. The patent license shall not apply to -any other combinations which include the Contribution. No hardware per se is -licensed hereunder. </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c) -Recipient understands that although each Contributor grants the licenses to its -Contributions set forth herein, no assurances are provided by any Contributor -that the Program does not infringe the patent or other intellectual property -rights of any other entity. Each Contributor disclaims any liability to Recipient -for claims brought by any other entity based on infringement of intellectual -property rights or otherwise. As a condition to exercising the rights and -licenses granted hereunder, each Recipient hereby assumes sole responsibility -to secure any other intellectual property rights needed, if any. For example, -if a third party patent license is required to allow Recipient to distribute -the Program, it is Recipient's responsibility to acquire that license before -distributing the Program.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d) -Each Contributor represents that to its knowledge it has sufficient copyright -rights in its Contribution, if any, to grant the copyright license set forth in -this Agreement. </span></p> - -<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> - -<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the -Program in object code form under its own license agreement, provided that:</span> -</p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it complies with the terms and conditions of this Agreement; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -its license agreement:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) -effectively disclaims on behalf of all Contributors all warranties and -conditions, express and implied, including warranties or conditions of title -and non-infringement, and implied warranties or conditions of merchantability -and fitness for a particular purpose; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -effectively excludes on behalf of all Contributors all liability for damages, -including direct, indirect, special, incidental and consequential damages, such -as lost profits; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) -states that any provisions which differ from this Agreement are offered by that -Contributor alone and not by any other party; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv) -states that source code for the Program is available from such Contributor, and -informs licensees how to obtain it in a reasonable manner on or through a -medium customarily used for software exchange.<span style='color:blue'> </span></span></p> - -<p><span style='font-size:10.0pt'>When the Program is made available in source -code form:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it must be made available under this Agreement; and </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a -copy of this Agreement must be included with each copy of the Program. </span></p> - -<p><span style='font-size:10.0pt'>Contributors may not remove or alter any -copyright notices contained within the Program. </span></p> - -<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the -originator of its Contribution, if any, in a manner that reasonably allows -subsequent Recipients to identify the originator of the Contribution. </span></p> - -<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> - -<p><span style='font-size:10.0pt'>Commercial distributors of software may -accept certain responsibilities with respect to end users, business partners -and the like. While this license is intended to facilitate the commercial use -of the Program, the Contributor who includes the Program in a commercial -product offering should do so in a manner which does not create potential -liability for other Contributors. Therefore, if a Contributor includes the -Program in a commercial product offering, such Contributor (&quot;Commercial -Contributor&quot;) hereby agrees to defend and indemnify every other -Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and -costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other -legal actions brought by a third party against the Indemnified Contributor to -the extent caused by the acts or omissions of such Commercial Contributor in -connection with its distribution of the Program in a commercial product -offering. The obligations in this section do not apply to any claims or Losses -relating to any actual or alleged intellectual property infringement. In order -to qualify, an Indemnified Contributor must: a) promptly notify the Commercial -Contributor in writing of such claim, and b) allow the Commercial Contributor -to control, and cooperate with the Commercial Contributor in, the defense and -any related settlement negotiations. The Indemnified Contributor may participate -in any such claim at its own expense.</span> </p> - -<p><span style='font-size:10.0pt'>For example, a Contributor might include the -Program in a commercial product offering, Product X. That Contributor is then a -Commercial Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance claims and -warranties are such Commercial Contributor's responsibility alone. Under this -section, the Commercial Contributor would have to defend claims against the -other Contributors related to those performance claims and warranties, and if a -court requires any other Contributor to pay any damages as a result, the -Commercial Contributor must pay those damages.</span> </p> - -<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> - -<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS -AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT -WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, -WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, -MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely -responsible for determining the appropriateness of using and distributing the -Program and assumes all risks associated with its exercise of rights under this -Agreement , including but not limited to the risks and costs of program errors, -compliance with applicable laws, damage to or loss of data, programs or -equipment, and unavailability or interruption of operations. </span></p> - -<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> - -<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS -AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY -OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF -THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGES.</span> </p> - -<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> - -<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid -or unenforceable under applicable law, it shall not affect the validity or -enforceability of the remainder of the terms of this Agreement, and without -further action by the parties hereto, such provision shall be reformed to the -minimum extent necessary to make such provision valid and enforceable.</span> </p> - -<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation -against any entity (including a cross-claim or counterclaim in a lawsuit) -alleging that the Program itself (excluding combinations of the Program with -other software or hardware) infringes such Recipient's patent(s), then such -Recipient's rights granted under Section 2(b) shall terminate as of the date -such litigation is filed. </span></p> - -<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement -shall terminate if it fails to comply with any of the material terms or -conditions of this Agreement and does not cure such failure in a reasonable -period of time after becoming aware of such noncompliance. If all Recipient's -rights under this Agreement terminate, Recipient agrees to cease use and -distribution of the Program as soon as reasonably practicable. However, -Recipient's obligations under this Agreement and any licenses granted by -Recipient relating to the Program shall continue and survive. </span></p> - -<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute -copies of this Agreement, but in order to avoid inconsistency the Agreement is -copyrighted and may only be modified in the following manner. The Agreement -Steward reserves the right to publish new versions (including revisions) of -this Agreement from time to time. No one other than the Agreement Steward has -the right to modify this Agreement. The Eclipse Foundation is the initial -Agreement Steward. The Eclipse Foundation may assign the responsibility to -serve as the Agreement Steward to a suitable separate entity. Each new version -of the Agreement will be given a distinguishing version number. The Program -(including Contributions) may always be distributed subject to the version of -the Agreement under which it was received. In addition, after a new version of -the Agreement is published, Contributor may elect to distribute the Program -(including its Contributions) under the new version. Except as expressly stated -in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to -the intellectual property of any Contributor under this Agreement, whether -expressly, by implication, estoppel or otherwise. All rights in the Program not -expressly granted under this Agreement are reserved.</span> </p> - -<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the -State of New York and the intellectual property laws of the United States of -America. No party to this Agreement will bring a legal action under this -Agreement more than one year after the cause of action arose. Each party waives -its rights to a jury trial in any resulting litigation.</span> </p> - -<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> - -</div> - -</body> - -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java deleted file mode 100644 index 0c549d11..00000000 --- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.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 - created interface to select a key in an editor (fixed issue 59) - ******************************************************************************/ -package org.eclipse.babel.tapiji.translator.rbe.babel.bundle; - -public interface IMessagesEditor { - String getSelectedKey(); - - void setSelectedKey(String key); -}
22b5df0be228a82f0ed3802c87860cfc3d3ce9ed
restlet-framework-java
- Fixed bug causing unit tests to fail--
c
https://github.com/restlet/restlet-framework-java
diff --git a/module/org.restlet/src/org/restlet/data/Form.java b/module/org.restlet/src/org/restlet/data/Form.java index 987143338c..06311102d0 100644 --- a/module/org.restlet/src/org/restlet/data/Form.java +++ b/module/org.restlet/src/org/restlet/data/Form.java @@ -111,7 +111,7 @@ public Form(String queryString) { @Override public Parameter createEntry(String name, String value) { - return new Parameter(); + return new Parameter(name, value); } @Override diff --git a/module/org.restlet/src/org/restlet/util/Series.java b/module/org.restlet/src/org/restlet/util/Series.java index a98ba1a45e..e9a3b23761 100644 --- a/module/org.restlet/src/org/restlet/util/Series.java +++ b/module/org.restlet/src/org/restlet/util/Series.java @@ -30,7 +30,7 @@ */ public interface Series<E extends Series.Entry> extends List<E> { /** - * A sequence entry. + * A named series entry. * * @author Jerome Louvel ([email protected]) */
75fd6d4985f9e1b74294d1c8a21b5a559f0c96fd
elasticsearch
Added KeywordRepeatFilter that allows emitting- stemmed and unstemmed versions of the same token if stemmers are used--Closes -2753-
a
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.java b/src/main/java/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.java new file mode 100644 index 0000000000000..ec8ad4d12f312 --- /dev/null +++ b/src/main/java/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.java @@ -0,0 +1,71 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.lucene.analysis.miscellaneous; + +import org.apache.lucene.analysis.TokenFilter; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.tokenattributes.KeywordAttribute; +import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; + +import java.io.IOException; + + +/** + * This TokenFilter emits each incoming token twice once as keyword and once non-keyword, in other words once with + * {@link KeywordAttribute#setKeyword(boolean)} set to <code>true</code> and once set to <code>false</code>. + * This is useful if used with a stem filter that respects the {@link KeywordAttribute} to index the stemmed and the + * un-stemmed version of a term into the same field. + */ +//LUCENE MONITOR - this will be included in Lucene 4.3. (it's a plain copy of the lucene version) + +public final class KeywordRepeatFilter extends TokenFilter { + private final KeywordAttribute keywordAttribute = addAttribute(KeywordAttribute.class); + private final PositionIncrementAttribute posIncAttr = addAttribute(PositionIncrementAttribute.class); + private State state; + + /** + * Construct a token stream filtering the given input. + */ + public KeywordRepeatFilter(TokenStream input) { + super(input); + } + + @Override + public boolean incrementToken() throws IOException { + if (state != null) { + restoreState(state); + posIncAttr.setPositionIncrement(0); + keywordAttribute.setKeyword(false); + state = null; + return true; + } + if (input.incrementToken()) { + state = captureState(); + keywordAttribute.setKeyword(true); + return true; + } + return false; + } + + @Override + public void reset() throws IOException { + super.reset(); + state = null; + } +} diff --git a/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java b/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java index 32f9c2f1b55cc..40ebfa9d16b58 100644 --- a/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java +++ b/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java @@ -642,6 +642,17 @@ public TokenStream create(TokenStream tokenStream) { return new SnowballFilter(tokenStream, "Russian"); } })); + tokenFilterFactories.put("keyword_repeat", new PreBuiltTokenFilterFactoryFactory(new TokenFilterFactory() { + @Override + public String name() { + return "keyword_repeat"; + } + + @Override + public TokenStream create(TokenStream tokenStream) { + return new KeywordRepeatFilter(tokenStream); + } + })); // Char Filter charFilterFactories.put("html_strip", new PreBuiltCharFilterFactoryFactory(new CharFilterFactory() { diff --git a/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java b/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java index 165d3748c7fbc..56820b36fedc2 100644 --- a/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java +++ b/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java @@ -20,7 +20,12 @@ package org.elasticsearch.test.unit.index.analysis; import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.Tokenizer; +import org.apache.lucene.analysis.core.WhitespaceTokenizer; +import org.apache.lucene.analysis.miscellaneous.KeywordRepeatFilter; import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.util.Version; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.inject.ModulesBuilder; import org.elasticsearch.common.lucene.Lucene; @@ -42,6 +47,7 @@ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; +import java.io.StringReader; import java.util.Set; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; @@ -65,6 +71,15 @@ public void testSimpleConfigurationYaml() { Settings settings = settingsBuilder().loadFromClasspath("org/elasticsearch/test/unit/index/analysis/test1.yml").build(); testSimpleConfiguration(settings); } + + @Test + public void testDefaultFactory() { + AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromSettings(ImmutableSettings.settingsBuilder().build()); + TokenFilterFactory tokenFilter = analysisService.tokenFilter("keyword_repeat"); + Tokenizer tokenizer = new WhitespaceTokenizer(Version.LUCENE_36, new StringReader("foo bar")); + TokenStream stream = tokenFilter.create(tokenizer); + assertThat(stream, instanceOf(KeywordRepeatFilter.class)); + } private void testSimpleConfiguration(Settings settings) { Index index = new Index("test");
05d93592ba53123c2483b146d9aab9cc6e112ae1
drools
[DROOLS-37] fix jitting of comparison contraints- (cherry picked from commit 5ea47c020451949cc52708494afdfa50799467a2)--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest2.java b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest2.java index f6970516ae7..bc98ca4be75 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest2.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest2.java @@ -1129,4 +1129,48 @@ public void setPrice(BigDecimal price) { this.price = price; } } + + @Test + public void testJitComparable() { + // DROOLS-37 + String str = + "import org.drools.integrationtests.MiscTest2.IntegerWrapperImpl;\n" + + "\n" + + "rule \"minCost\"\n" + + "when\n" + + " $a : IntegerWrapperImpl()\n" + + " IntegerWrapperImpl( this < $a )\n" + + "then\n" + + "end"; + + KnowledgeBase kbase = loadKnowledgeBaseFromString(str); + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + ksession.insert(new IntegerWrapperImpl(2)); + ksession.insert(new IntegerWrapperImpl(3)); + + assertEquals(1, ksession.fireAllRules()); + } + + interface IntegerWraper { + int getInt(); + } + + public static abstract class AbstractIntegerWrapper implements IntegerWraper, Comparable<IntegerWraper> { } + + public static class IntegerWrapperImpl extends AbstractIntegerWrapper { + + private final int i; + + public IntegerWrapperImpl(int i) { + this.i = i; + } + + public int compareTo(IntegerWraper o) { + return getInt() - o.getInt(); + } + + public int getInt() { + return i; + } + } } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/rule/constraint/ASMConditionEvaluatorJitter.java b/drools-core/src/main/java/org/drools/rule/constraint/ASMConditionEvaluatorJitter.java index dbc4f496661..5fd86b7e117 100644 --- a/drools-core/src/main/java/org/drools/rule/constraint/ASMConditionEvaluatorJitter.java +++ b/drools-core/src/main/java/org/drools/rule/constraint/ASMConditionEvaluatorJitter.java @@ -15,6 +15,8 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Iterator; @@ -351,9 +353,9 @@ private void jitObjectBinary(SingleCondition singleCondition, Expression left, E } } else { if (type.isInterface()) { - invokeInterface(type, "compareTo", int.class, type == Comparable.class ? Object.class : type); + invokeInterface(type, "compareTo", int.class, type == Comparable.class ? Object.class : findComparingClass(type)); } else { - invokeVirtual(type, "compareTo", int.class, type); + invokeVirtual(type, "compareTo", int.class, findComparingClass(type)); } mv.visitInsn(ICONST_0); jitPrimitiveOperation(operation == BooleanOperator.NE ? BooleanOperator.EQ : operation, int.class); @@ -366,6 +368,25 @@ private void jitObjectBinary(SingleCondition singleCondition, Expression left, E mv.visitLabel(shortcutEvaluation); } + private Class<?> findComparingClass(Class<?> type) { + return findComparingClass(type, type); + } + + private Class<?> findComparingClass(Class<?> type, Class<?> originalType) { + if (type == null) { + return originalType; + } + for (Type interfaze : type.getGenericInterfaces()) { + if (interfaze instanceof ParameterizedType) { + ParameterizedType pType = (ParameterizedType)interfaze; + if (pType.getRawType() == Comparable.class) { + return (Class<?>) pType.getActualTypeArguments()[0]; + } + } + } + return findComparingClass(type.getSuperclass(), originalType); + } + private void prepareLeftOperand(BooleanOperator operation, Class<?> type, Class<?> leftType, Class<?> rightType, Label shortcutEvaluation) { if (leftType.isPrimitive()) { if (type != null) {
f2a59c6ea1b336cf2b7563fccbeecf278777808a
ReactiveX-RxJava
Fix for back pressure on the alternate- subscription.--
c
https://github.com/ReactiveX/RxJava
diff --git a/src/main/java/rx/internal/operators/OperatorSwitchIfEmpty.java b/src/main/java/rx/internal/operators/OperatorSwitchIfEmpty.java index 67fafbd8d2..615594cc17 100644 --- a/src/main/java/rx/internal/operators/OperatorSwitchIfEmpty.java +++ b/src/main/java/rx/internal/operators/OperatorSwitchIfEmpty.java @@ -76,6 +76,17 @@ public void onCompleted() { private void subscribeToAlternate() { child.add(alternate.unsafeSubscribe(new Subscriber<T>() { + + @Override + public void setProducer(final Producer producer) { + child.setProducer(new Producer() { + @Override + public void request(long n) { + producer.request(n); + } + }); + } + @Override public void onStart() { final long capacity = consumerCapacity.get(); diff --git a/src/test/java/rx/internal/operators/OperatorSwitchIfEmptyTest.java b/src/test/java/rx/internal/operators/OperatorSwitchIfEmptyTest.java index 443953563d..3fc735ccab 100644 --- a/src/test/java/rx/internal/operators/OperatorSwitchIfEmptyTest.java +++ b/src/test/java/rx/internal/operators/OperatorSwitchIfEmptyTest.java @@ -23,7 +23,9 @@ import rx.functions.Action0; import rx.subscriptions.Subscriptions; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; @@ -56,13 +58,15 @@ public void testSwitchWhenEmpty() throws Exception { @Test public void testSwitchWithProducer() throws Exception { + final AtomicBoolean emitted = new AtomicBoolean(false); Observable<Long> withProducer = Observable.create(new Observable.OnSubscribe<Long>() { @Override public void call(final Subscriber<? super Long> subscriber) { subscriber.setProducer(new Producer() { @Override public void request(long n) { - if (n > 0) { + if (n > 0 && !emitted.get()) { + emitted.set(true); subscriber.onNext(42L); subscriber.onCompleted(); } @@ -127,4 +131,33 @@ public void call(final Subscriber<? super Long> subscriber) { }).switchIfEmpty(Observable.<Long>never()).subscribe(); assertTrue(s.isUnsubscribed()); } + + @Test + public void testSwitchRequestAlternativeObservableWithBackpressure() { + final List<Integer> items = new ArrayList<Integer>(); + + Observable.<Integer>empty().switchIfEmpty(Observable.just(1, 2, 3)).subscribe(new Subscriber<Integer>() { + + @Override + public void onStart() { + request(1); + } + + @Override + public void onCompleted() { + + } + + @Override + public void onError(Throwable e) { + + } + + @Override + public void onNext(Integer integer) { + items.add(integer); + } + }); + assertEquals(Arrays.asList(1), items); + } } \ No newline at end of file
992ff293a9dc7efbedaa8290316f0f4e9e030439
ReactiveX-RxJava
Better name for worker class running scheduled- actions--
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java b/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java index 2feba948fb..acd5be7740 100644 --- a/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java +++ b/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java @@ -36,12 +36,12 @@ private static final class CachedWorkerPool { private final long keepAliveTime; - private final ConcurrentLinkedQueue<PoolWorker> expiringQueue; + private final ConcurrentLinkedQueue<ThreadWorker> expiringWorkerQueue; private final ScheduledExecutorService evictExpiredWorkerExecutor; CachedWorkerPool(long keepAliveTime, TimeUnit unit) { this.keepAliveTime = unit.toNanos(keepAliveTime); - this.expiringQueue = new ConcurrentLinkedQueue<PoolWorker>(); + this.expiringWorkerQueue = new ConcurrentLinkedQueue<ThreadWorker>(); evictExpiredWorkerExecutor = Executors.newScheduledThreadPool(1, EVICTOR_THREAD_FACTORY); evictExpiredWorkerExecutor.scheduleWithFixedDelay( @@ -58,35 +58,35 @@ public void run() { 60L, TimeUnit.SECONDS ); - PoolWorker get() { - while (!expiringQueue.isEmpty()) { - PoolWorker poolWorker = expiringQueue.poll(); - if (poolWorker != null) { - return poolWorker; + ThreadWorker get() { + while (!expiringWorkerQueue.isEmpty()) { + ThreadWorker threadWorker = expiringWorkerQueue.poll(); + if (threadWorker != null) { + return threadWorker; } } // No cached worker found, so create a new one. - return new PoolWorker(WORKER_THREAD_FACTORY); + return new ThreadWorker(WORKER_THREAD_FACTORY); } - void release(PoolWorker poolWorker) { + void release(ThreadWorker threadWorker) { // Refresh expire time before putting worker back in pool - poolWorker.setExpirationTime(now() + keepAliveTime); + threadWorker.setExpirationTime(now() + keepAliveTime); - expiringQueue.add(poolWorker); + expiringWorkerQueue.offer(threadWorker); } void evictExpiredWorkers() { - if (!expiringQueue.isEmpty()) { + if (!expiringWorkerQueue.isEmpty()) { long currentTimestamp = now(); - Iterator<PoolWorker> poolWorkerIterator = expiringQueue.iterator(); - while (poolWorkerIterator.hasNext()) { - PoolWorker poolWorker = poolWorkerIterator.next(); - if (poolWorker.getExpirationTime() <= currentTimestamp) { - poolWorkerIterator.remove(); - poolWorker.unsubscribe(); + Iterator<ThreadWorker> threadWorkerIterator = expiringWorkerQueue.iterator(); + while (threadWorkerIterator.hasNext()) { + ThreadWorker threadWorker = threadWorkerIterator.next(); + if (threadWorker.getExpirationTime() <= currentTimestamp) { + threadWorkerIterator.remove(); + threadWorker.unsubscribe(); } else { // Queue is ordered with the worker that will expire first in the beginning, so when we // find a non-expired worker we can stop evicting. @@ -108,20 +108,20 @@ public Worker createWorker() { private static class EventLoopWorker extends Scheduler.Worker { private final CompositeSubscription innerSubscription = new CompositeSubscription(); - private final PoolWorker poolWorker; + private final ThreadWorker threadWorker; volatile int once; static final AtomicIntegerFieldUpdater<EventLoopWorker> ONCE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(EventLoopWorker.class, "once"); - EventLoopWorker(PoolWorker poolWorker) { - this.poolWorker = poolWorker; + EventLoopWorker(ThreadWorker threadWorker) { + this.threadWorker = threadWorker; } @Override public void unsubscribe() { if (ONCE_UPDATER.compareAndSet(this, 0, 1)) { // unsubscribe should be idempotent, so only do this once - CachedWorkerPool.INSTANCE.release(poolWorker); + CachedWorkerPool.INSTANCE.release(threadWorker); } innerSubscription.unsubscribe(); } @@ -143,17 +143,17 @@ public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) { return Subscriptions.empty(); } - NewThreadScheduler.NewThreadWorker.ScheduledAction s = poolWorker.scheduleActual(action, delayTime, unit); + NewThreadScheduler.NewThreadWorker.ScheduledAction s = threadWorker.scheduleActual(action, delayTime, unit); innerSubscription.add(s); s.addParent(innerSubscription); return s; } } - private static final class PoolWorker extends NewThreadScheduler.NewThreadWorker { + private static final class ThreadWorker extends NewThreadScheduler.NewThreadWorker { private long expirationTime; - PoolWorker(ThreadFactory threadFactory) { + ThreadWorker(ThreadFactory threadFactory) { super(threadFactory); this.expirationTime = 0L; }
469ae561947ace9a87d971875fbf454a499b542c
intellij-community
add suggestions for literal expressions- (IDEA-57593)--
c
https://github.com/JetBrains/intellij-community
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java index 58932d94d7dba..e228200bef877 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java @@ -644,6 +644,11 @@ else if (expr instanceof PsiLiteralExpression && variableKind == VariableKind.ST return suggestVariableNameByExpressionOnly(((PsiParenthesizedExpression)expr).getExpression(), variableKind); } else if (expr instanceof PsiTypeCastExpression) { return suggestVariableNameByExpressionOnly(((PsiTypeCastExpression)expr).getOperand(), variableKind); + } else if (expr instanceof PsiLiteralExpression) { + final String text = StringUtil.stripQuotesAroundValue(expr.getText()); + if (isIdentifier(text)) { + return new NamesByExprInfo(text, getSuggestionsByName(text, variableKind, false)); + } } return new NamesByExprInfo(null, ArrayUtil.EMPTY_STRING_ARRAY);
07f305ea6967427f8b11c1d0e87e47ca634db504
duracloud$duracloud
This update closes https://jira.duraspace.org/browse/DURACLOUD-486 . It adds two new pieces of functionality to the Duplicate-on-Change service: - logging to x-service-out the duplication events in a tab-delimited format - retrying failed duplications at a level above the existing retries within the ContentDuplicatorImpl and SpaceDuplicatorImpl. git-svn-id: https://svn.duraspace.org/duracloud/trunk@622 1005ed41-97cd-4a8f-848c-be5b5fe45bcb
p
https://github.com/duracloud/duracloud
diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/ContentDuplicator.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/ContentDuplicator.java index eb54de854..9b4ba36bd 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/ContentDuplicator.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/ContentDuplicator.java @@ -21,8 +21,9 @@ public interface ContentDuplicator { * * @param spaceId of content item * @param contentId of content item + * @return checksum of content */ - public void createContent(String spaceId, String contentId); + public String createContent(String spaceId, String contentId); /** * This method updates an existing content item in the arg spaceId with the diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/DuplicationService.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/DuplicationService.java index 58ec835a6..474a6a36c 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/DuplicationService.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/DuplicationService.java @@ -14,7 +14,9 @@ import org.duracloud.common.util.DateUtil; import org.duracloud.error.ContentStoreException; import org.duracloud.services.duplication.impl.ContentDuplicatorImpl; +import org.duracloud.services.duplication.impl.ContentDuplicatorReportingImpl; import org.duracloud.services.duplication.impl.SpaceDuplicatorImpl; +import org.duracloud.services.duplication.impl.SpaceDuplicatorReportingImpl; import org.duracloud.services.duplication.result.DuplicationResultListener; import org.duracloud.services.duplication.result.ResultListener; import org.duracloud.services.listener.BaseListenerService; @@ -28,11 +30,10 @@ import javax.jms.MapMessage; import java.util.Dictionary; -public class DuplicationService extends BaseListenerService - implements ComputeService, ManagedService { +public class DuplicationService extends BaseListenerService implements ComputeService, ManagedService { private static final Logger log = - LoggerFactory.getLogger(DuplicationService.class); + LoggerFactory.getLogger(DuplicationService.class); private String host; @@ -73,8 +74,9 @@ public void start() throws Exception { String messageSelector = STORE_ID + " = '" + fromStoreId + "'"; initializeMessaging(messageSelector); - ContentStoreManager storeManager = - new ContentStoreManagerImpl(host, port, context); + ContentStoreManager storeManager = new ContentStoreManagerImpl(host, + port, + context); storeManager.login(credential); @@ -86,9 +88,9 @@ public void start() throws Exception { toStore = storeManager.getContentStore(toStoreId); primaryStore = storeManager.getPrimaryContentStore(); - } catch(ContentStoreException cse) { + } catch (ContentStoreException cse) { String error = "Unable to create connections to content " + - "stores for duplication " + cse.getMessage(); + "stores for duplication " + cse.getMessage(); log.error(error); super.setError(error); return; @@ -111,7 +113,7 @@ public void start() throws Exception { log.info("Listener container started: " + jmsContainer.isRunning()); log.info("**********"); log.info("Duplication Service Listener Started"); - + setServiceStatus(ServiceStatus.STARTED); } @@ -132,6 +134,7 @@ public void stop() throws Exception { log.info("Stopping Duplication Service"); terminateMessaging(); contentDuplicator.stop(); + spaceDuplicator.stop(); setServiceStatus(ServiceStatus.STOPPED); } @@ -141,30 +144,30 @@ protected void handleMapMessage(MapMessage message, String topic) { String spaceId = message.getString(SPACE_ID); String contentId = message.getString(CONTENT_ID); - if(getSpaceCreateTopic().equals(topic)) { + if (getSpaceCreateTopic().equals(topic)) { spaceDuplicator.createSpace(spaceId); - } - else if(getSpaceUpdateTopic().equals(topic)) { + + } else if (getSpaceUpdateTopic().equals(topic)) { spaceDuplicator.updateSpace(spaceId); - } - else if(getSpaceDeleteTopic().equals(topic)) { + + } else if (getSpaceDeleteTopic().equals(topic)) { spaceDuplicator.deleteSpace(spaceId); - } - else if(getContentCreateTopic().equals(topic)) { + + } else if (getContentCreateTopic().equals(topic)) { contentDuplicator.createContent(spaceId, contentId); - } - else if(getContentCopyTopic().equals(topic)) { + + } else if (getContentCopyTopic().equals(topic)) { contentDuplicator.createContent(spaceId, contentId); - } - else if(getContentUpdateTopic().equals(topic)) { + + } else if (getContentUpdateTopic().equals(topic)) { contentDuplicator.updateContent(spaceId, contentId); - } - else if(getContentDeleteTopic().equals(topic)) { + + } else if (getContentDeleteTopic().equals(topic)) { contentDuplicator.deleteContent(spaceId, contentId); } } catch (JMSException je) { String error = - "Error occured processing map message: " + je.getMessage(); + "Error occured processing map message: " + je.getMessage(); log.error(error); super.setError(error); throw new RuntimeException(error, je); @@ -180,7 +183,8 @@ private SpaceDuplicator getSpaceDuplicator(ContentStore fromStore, ContentStore toStore, ResultListener listener) { if (null == spaceDuplicator) { - spaceDuplicator = new SpaceDuplicatorImpl(fromStore, toStore); + SpaceDuplicator sd = new SpaceDuplicatorImpl(fromStore, toStore); + spaceDuplicator = new SpaceDuplicatorReportingImpl(sd, listener); } return spaceDuplicator; } @@ -189,12 +193,14 @@ private ContentDuplicator getContentDuplicator(ContentStore fromStore, ContentStore toStore, ResultListener listener) { if (null == contentDuplicator) { - SpaceDuplicator spaceDuplicator = getSpaceDuplicator(fromStore, - toStore, - listener); - contentDuplicator = new ContentDuplicatorImpl(fromStore, - toStore, - spaceDuplicator); + SpaceDuplicator sd = getSpaceDuplicator(fromStore, + toStore, + listener); + ContentDuplicator cd = new ContentDuplicatorImpl(fromStore, + toStore, + sd); + contentDuplicator = new ContentDuplicatorReportingImpl(cd, + listener); } return contentDuplicator; } diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/SpaceDuplicator.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/SpaceDuplicator.java index b13476b15..ba6ceff67 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/SpaceDuplicator.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/SpaceDuplicator.java @@ -35,4 +35,9 @@ public interface SpaceDuplicator { * @param spaceId of space to delete */ public void deleteSpace(String spaceId); + + /** + * This method performs any necessary clean-up of the SpaceDuplicator. + */ + public void stop(); } diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/ContentDuplicatorImpl.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/ContentDuplicatorImpl.java index 7f54bc61f..a45799102 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/ContentDuplicatorImpl.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/ContentDuplicatorImpl.java @@ -68,13 +68,13 @@ public ContentDuplicatorImpl(ContentStore fromStore, } @Override - public void createContent(String spaceId, String contentId) { + public String createContent(String spaceId, String contentId) { logDebug("Creating", spaceId, contentId); if (null == spaceId || null == contentId) { String err = "Space or content to create is null: {}, {}."; log.warn(err, spaceId, contentId); - return; + return null; } Content content = getContent(spaceId, contentId); @@ -100,7 +100,7 @@ public void createContent(String spaceId, String contentId) { err.append(" from "); err.append(fromStore.getStorageProviderType()); log.error(err.toString()); - return; + return null; } String mimeType = null; @@ -140,32 +140,31 @@ public void createContent(String spaceId, String contentId) { fileReaper.track(tmpFile, contentStream); } - addContent(spaceId, - contentId, - contentStream, - contentSize, - mimeType, - checksum, - properties); + return addContent(spaceId, + contentId, + contentStream, + contentSize, + mimeType, + checksum, + properties); } - private void addContent(String spaceId, - String contentId, - InputStream contentStream, - long contentSize, - String mimeType, - String checksum, - Map<String, String> properties) { - boolean success = false; + private String addContent(String spaceId, + String contentId, + InputStream contentStream, + long contentSize, + String mimeType, + String checksum, + Map<String, String> properties) { + String md5 = null; try { - toStore.addContent(spaceId, - contentId, - contentStream, - contentSize, - mimeType, - checksum, - properties); - success = true; + md5 = toStore.addContent(spaceId, + contentId, + contentStream, + contentSize, + mimeType, + checksum, + properties); } catch (NotFoundException nfe) { log.info("Unable to create content {}/{} in {}, due to: {}", @@ -189,34 +188,34 @@ private void addContent(String spaceId, } // Try again if it did not succeed. - if (!success) { - doAddContent(spaceId, - contentId, - contentSize, - mimeType, - checksum, - properties); + if (null == md5) { + md5 = doAddContent(spaceId, + contentId, + contentSize, + mimeType, + checksum, + properties); } + return md5; } - private void doAddContent(final String spaceId, - final String contentId, - final long contentSize, - final String mimeType, - final String checksum, - final Map<String, String> properties) { + private String doAddContent(final String spaceId, + final String contentId, + final long contentSize, + final String mimeType, + final String checksum, + final Map<String, String> properties) { try { - new StoreCaller<Boolean>(waitMillis) { - protected Boolean doCall() throws Exception { + return new StoreCaller<String>(waitMillis) { + protected String doCall() throws Exception { Content content = getContent(spaceId, contentId); - toStore.addContent(spaceId, - contentId, - content.getStream(), - contentSize, - mimeType, - checksum, - properties); - return true; + return toStore.addContent(spaceId, + contentId, + content.getStream(), + contentSize, + mimeType, + checksum, + properties); } }.call(); @@ -257,8 +256,10 @@ public void updateContent(String spaceId, String contentId) { throw new DuplicationException(err.toString()); } + boolean success = false; try { toStore.setContentProperties(spaceId, contentId, props); + success = true; } catch (NotFoundException nfe) { String err = "Unable to update content props for {}/{}, due to: {}"; @@ -274,7 +275,18 @@ public void updateContent(String spaceId, String contentId) { // Try setting the properties again. log.info("Trying to readd content props {}/{}", spaceId, contentId); - setProperties(spaceId, contentId, props); + success = setProperties(spaceId, contentId, props); + } + + if (!success) { + StringBuilder err = new StringBuilder(); + err.append("Error updating content: "); + err.append(spaceId); + err.append("/"); + err.append(contentId); + err.append(", to "); + err.append(toStore.getStorageProviderType()); + throw new DuplicationException(err.toString()); } } diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/ContentDuplicatorReportingImpl.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/ContentDuplicatorReportingImpl.java new file mode 100644 index 000000000..c28e7b25b --- /dev/null +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/ContentDuplicatorReportingImpl.java @@ -0,0 +1,316 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.duplication.impl; + +import org.duracloud.common.error.DuraCloudRuntimeException; +import org.duracloud.services.duplication.ContentDuplicator; +import org.duracloud.services.duplication.error.DuplicationException; +import org.duracloud.services.duplication.result.DuplicationEvent; +import org.duracloud.services.duplication.result.ResultListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Queue; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.DelayQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.CONTENT_CREATE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.CONTENT_DELETE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.CONTENT_UPDATE; + +/** + * @author Andrew Woods + * Date: 9/18/11 + */ +public class ContentDuplicatorReportingImpl implements ContentDuplicator { + + private final Logger log = LoggerFactory.getLogger( + ContentDuplicatorReportingImpl.class); + + public static final int MAX_RETRIES = 3; + + private ContentDuplicator contentDuplicator; + + private ResultListener listener; + private boolean watchQ; + private Queue<DuplicationEvent> inboxQ; + private DelayQueue<DuplicationEvent> retryQ; + private Map<DuplicationEvent, Integer> retryTally; + + private ExecutorService executor; + private final long waitMillis; + + + public ContentDuplicatorReportingImpl(ContentDuplicator contentDuplicator, + ResultListener listener) { + this(contentDuplicator, + listener, + 60000); // default waiting factor = 1min + } + + public ContentDuplicatorReportingImpl(ContentDuplicator contentDuplicator, + ResultListener listener, + long waitMillis) { + this.contentDuplicator = contentDuplicator; + this.listener = listener; + this.waitMillis = waitMillis; + + this.watchQ = true; + this.inboxQ = new ConcurrentLinkedQueue<DuplicationEvent>(); + this.retryQ = new DelayQueue<DuplicationEvent>(); + this.retryTally = new HashMap<DuplicationEvent, Integer>(); + this.executor = Executors.newFixedThreadPool(2); + + executor.execute(new QWatcher(inboxQ)); + executor.execute(new QWatcher(retryQ)); + } + + /** + * This thread spins on the provided queue of DuplicationEvents, executing + * the appropriate method. + */ + private class QWatcher extends Thread { + + private Queue<DuplicationEvent> queue; + + public QWatcher(Queue<DuplicationEvent> queue) { + this.queue = queue; + } + + @Override + public void run() { + while (watchQ) { + DuplicationEvent event = queue.poll(); + if (null != event) { + + switch (event.getType()) { + case CONTENT_CREATE: + createContent(event); + break; + + case CONTENT_DELETE: + deleteContent(event); + break; + + case CONTENT_UPDATE: + updateContent(event); + break; + + default: + String msg = "Unexpected retry event: " + event; + log.error(msg); + throw new DuraCloudRuntimeException(msg); + } + + } else { + try { + sleep(waitMillis); + } catch (InterruptedException e) { + // do nothing + } + } + } + } + } + + @Override + public String createContent(String spaceId, String contentId) { + submitEvent(new DuplicationEvent(spaceId, contentId, CONTENT_CREATE)); + return "returned-string-not-used"; + } + + @Override + public void updateContent(String spaceId, String contentId) { + submitEvent(new DuplicationEvent(spaceId, contentId, CONTENT_UPDATE)); + } + + @Override + public void deleteContent(String spaceId, String contentId) { + submitEvent(new DuplicationEvent(spaceId, contentId, CONTENT_DELETE)); + } + + private void submitEvent(DuplicationEvent event) { + if (!inboxQ.contains(event)) { + inboxQ.add(event); + + } else { + log.info("omitting event submission: {}, q: {}", event, inboxQ); + } + } + + private String createContent(DuplicationEvent event) { + String spaceId = event.getSpaceId(); + String contentId = event.getContentId(); + + String md5 = null; + try { + md5 = contentDuplicator.createContent(spaceId, contentId); + createContentSuccess(spaceId, contentId, md5); + + } catch (DuplicationException e) { + createContentFailure(spaceId, contentId); + } + return md5; + } + + private void updateContent(DuplicationEvent event) { + String spaceId = event.getSpaceId(); + String contentId = event.getContentId(); + + try { + contentDuplicator.updateContent(spaceId, contentId); + updateContentSuccess(spaceId, contentId); + + } catch (DuplicationException e) { + updateContentFailure(spaceId, contentId); + } + } + + private void deleteContent(DuplicationEvent event) { + String spaceId = event.getSpaceId(); + String contentId = event.getContentId(); + + try { + contentDuplicator.deleteContent(spaceId, contentId); + deleteContentSuccess(spaceId, contentId); + + } catch (DuplicationException e) { + deleteContentFailure(spaceId, contentId); + } + } + + @Override + public void stop() { + log.info("Shutting down."); + + watchQ = false; + executor.shutdown(); + + Set<DuplicationEvent> events = new HashSet<DuplicationEvent>(); + events.addAll(retryTally.keySet()); + + for (Object event : retryQ.toArray()) { + events.add((DuplicationEvent) event); + } + retryQ.clear(); + + for (Object event : inboxQ.toArray()) { + events.add((DuplicationEvent) event); + } + inboxQ.clear(); + + for (DuplicationEvent event : events) { + processFailure(event, "service shutdown during retry"); + } + } + + private void createContentSuccess(String spaceId, + String contentId, + String md5) { + processSuccess(spaceId, contentId, md5, CONTENT_CREATE); + } + + private void updateContentSuccess(String spaceId, String contentId) { + processSuccess(spaceId, contentId, TYPE.CONTENT_UPDATE); + } + + private void deleteContentSuccess(String spaceId, String contentId) { + processSuccess(spaceId, contentId, TYPE.CONTENT_DELETE); + } + + private void processSuccess(String spaceId, + String contentId, + String md5, + TYPE type) { + processSuccess(new DuplicationEvent(spaceId, contentId, md5, type)); + } + + private void processSuccess(String spaceId, String contentId, TYPE type) { + processSuccess(new DuplicationEvent(spaceId, contentId, type)); + } + + private void processSuccess(DuplicationEvent event) { + log.debug("processing success: {}", event); + + // clear the tracking of this event. + retryTally.remove(event); + listener.processResult(event); + } + + private void createContentFailure(String spaceId, String contentId) { + log.debug("createContentFailure({}, {})", spaceId, contentId); + contentFailure(spaceId, contentId, CONTENT_CREATE); + } + + private void updateContentFailure(String spaceId, String contentId) { + log.debug("updateContentFailure({}, {})", spaceId, contentId); + contentFailure(spaceId, contentId, TYPE.CONTENT_UPDATE); + } + + private void deleteContentFailure(String spaceId, String contentId) { + log.debug("deleteContentFailure({}, {})", spaceId, contentId); + contentFailure(spaceId, contentId, TYPE.CONTENT_DELETE); + } + + private void contentFailure(String spaceId, String contentId, TYPE type) { + DuplicationEvent event = new DuplicationEvent(spaceId, contentId, type); + + Integer tally = retryTally.get(event); + if (null == tally) { + tally = 0; + } + + if (tally >= MAX_RETRIES) { + processFailure(event, "max retries exceeded: " + tally); + + } else { + processRetry(event, tally + 1); + } + } + + private void processFailure(DuplicationEvent event, String error) { + log.warn("processing failure: {} for: {}", error, event); + + event.fail(error); + + // clear tracking of this event. + retryTally.remove(event); + listener.processResult(event); + } + + private void processRetry(DuplicationEvent result, Integer tally) { + log.info("Schedule retry: {}, for {}", tally, result); + + Random r = new Random(); + long exponentialWait = r.nextInt((int) Math.pow(3, tally)); + + long delayMillis = exponentialWait * waitMillis; + result.setDelay(delayMillis); + + retryTally.put(result, tally); + retryQ.put(result); + } + + /** + * This method is intended as a helper for UNIT TESTS ONLY. + * + * @return true if retries are in-progress + */ + protected boolean eventsExist() { + return !retryTally.isEmpty() || !retryQ.isEmpty() || !inboxQ.isEmpty(); + } + +} diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorImpl.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorImpl.java index 22b98a62f..92ebc5793 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorImpl.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorImpl.java @@ -133,6 +133,11 @@ public void deleteSpace(String spaceId) { } } + @Override + public void stop() { + log.info("stop() not implemented!"); + } + private boolean doCreateSpace(final String spaceId, final Map<String, String> properties) { try { diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorReportingImpl.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorReportingImpl.java index 2aee6df3a..10ea477f5 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorReportingImpl.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/impl/SpaceDuplicatorReportingImpl.java @@ -7,8 +7,22 @@ */ package org.duracloud.services.duplication.impl; +import org.duracloud.common.error.DuraCloudRuntimeException; import org.duracloud.services.duplication.SpaceDuplicator; +import org.duracloud.services.duplication.error.DuplicationException; +import org.duracloud.services.duplication.result.DuplicationEvent; import org.duracloud.services.duplication.result.ResultListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.DelayQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; /** * This class implements the SpaceDuplicator contract with the responsibility @@ -20,25 +34,213 @@ */ public class SpaceDuplicatorReportingImpl implements SpaceDuplicator { + private final Logger log = LoggerFactory.getLogger( + SpaceDuplicatorReportingImpl.class); + + public static final int MAX_RETRIES = 3; + private SpaceDuplicator spaceDuplicator; + private ResultListener listener; + private boolean watchQ; + private DelayQueue<DuplicationEvent> retryQ; + private Map<DuplicationEvent, Integer> retryTally; + + private ExecutorService executor; + private final long waitMillis; + + public SpaceDuplicatorReportingImpl(SpaceDuplicator spaceDuplicator, ResultListener listener) { - // Default method body + this(spaceDuplicator, listener, 60000); // default waiting factor = 1min + } + + public SpaceDuplicatorReportingImpl(SpaceDuplicator spaceDuplicator, + ResultListener listener, + long waitMillis) { + this.spaceDuplicator = spaceDuplicator; + this.listener = listener; + this.watchQ = true; + this.waitMillis = waitMillis; + + this.retryQ = new DelayQueue<DuplicationEvent>(); + this.retryTally = new HashMap<DuplicationEvent, Integer>(); + this.executor = Executors.newSingleThreadExecutor(); + + executor.execute(new QWatcher()); + } + + private class QWatcher extends Thread { + @Override + public void run() { + while (watchQ) { + DuplicationEvent event = retryQ.poll(); + if (null != event) { + switch (event.getType()) { + case SPACE_CREATE: + createSpace(event.getSpaceId()); + break; + + case SPACE_DELETE: + deleteSpace(event.getSpaceId()); + break; + + case SPACE_UPDATE: + updateSpace(event.getSpaceId()); + break; + + default: + String msg = "Unexpected retry event: " + event; + log.error(msg); + throw new DuraCloudRuntimeException(msg); + } + + } else { + try { + sleep(waitMillis); + } catch (InterruptedException e) { + // do nothing + } + } + } + } } @Override public void createSpace(String spaceId) { - // Default method body + try { + spaceDuplicator.createSpace(spaceId); + createSpaceSuccess(spaceId); + + } catch (DuplicationException e) { + createSpaceFailure(spaceId); + } } @Override public void updateSpace(String spaceId) { - // Default method body + try { + spaceDuplicator.updateSpace(spaceId); + updateSpaceSuccess(spaceId); + + } catch (DuplicationException e) { + updateSpaceFailure(spaceId); + } } @Override public void deleteSpace(String spaceId) { - // Default method body + try { + spaceDuplicator.deleteSpace(spaceId); + deleteSpaceSuccess(spaceId); + + } catch (DuplicationException e) { + deleteSpaceFailure(spaceId); + } } + + @Override + public void stop() { + log.info("Shutting down."); + + watchQ = false; + executor.shutdown(); + + Set<DuplicationEvent> events = new HashSet<DuplicationEvent>(); + events.addAll(retryTally.keySet()); + + for (Object event : retryQ.toArray()) { + events.add((DuplicationEvent) event); + } + retryQ.clear(); + + for (DuplicationEvent event : events) { + processFailure(event, "service shutdown during retry"); + } + } + + private void createSpaceSuccess(String spaceId) { + processSuccess(spaceId, DuplicationEvent.TYPE.SPACE_CREATE); + } + + private void updateSpaceSuccess(String spaceId) { + processSuccess(spaceId, DuplicationEvent.TYPE.SPACE_UPDATE); + } + + private void deleteSpaceSuccess(String spaceId) { + processSuccess(spaceId, DuplicationEvent.TYPE.SPACE_DELETE); + } + + private void processSuccess(String spaceId, DuplicationEvent.TYPE type) { + DuplicationEvent event = new DuplicationEvent(spaceId, type); + log.debug("processing success: {}", event); + + // clear the tracking of this event. + retryTally.remove(event); + listener.processResult(event); + } + + private void createSpaceFailure(String spaceId) { + log.debug("createSpaceFailure({})", spaceId); + spaceFailure(spaceId, DuplicationEvent.TYPE.SPACE_CREATE); + } + + private void updateSpaceFailure(String spaceId) { + log.debug("updateSpaceFailure({})", spaceId); + spaceFailure(spaceId, DuplicationEvent.TYPE.SPACE_UPDATE); + } + + private void deleteSpaceFailure(String spaceId) { + log.debug("deleteSpaceFailure({})", spaceId); + spaceFailure(spaceId, DuplicationEvent.TYPE.SPACE_DELETE); + } + + private void spaceFailure(String spaceId, DuplicationEvent.TYPE type) { + DuplicationEvent event = new DuplicationEvent(spaceId, type); + + Integer tally = retryTally.get(event); + if (null == tally) { + tally = 0; + } + + if (tally >= MAX_RETRIES) { + processFailure(event, "max retries exceeded: " + tally); + + } else { + processRetry(event, tally + 1); + } + } + + private void processFailure(DuplicationEvent event, String error) { + log.warn("processing failure: {}", event); + + event.fail(error); + + // clear tracking of this event. + retryTally.remove(event); + listener.processResult(event); + } + + private void processRetry(DuplicationEvent result, Integer tally) { + log.info("Schedule retry: {}, for {}", tally, result); + + Random r = new Random(); + long exponentialWait = r.nextInt((int) Math.pow(3, tally)); + + long delayMillis = exponentialWait * waitMillis; + result.setDelay(delayMillis); + + retryTally.put(result, tally); + retryQ.put(result); + } + + /** + * This method is intended as a helper for UNIT TESTS ONLY. + * + * @return true if retries are in-progress + */ + protected boolean retriesExist() { + return !retryTally.isEmpty() || !retryQ.isEmpty(); + } + } diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationEvent.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationEvent.java new file mode 100644 index 000000000..ed839c96a --- /dev/null +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationEvent.java @@ -0,0 +1,181 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.duplication.result; + +import org.duracloud.common.util.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.Delayed; +import java.util.concurrent.TimeUnit; + +import static org.duracloud.services.ComputeService.DELIM; + +/** + * This class holds details of a duplication result. + * <p/> + * Note: this class has a natural ordering that is inconsistent with equals. + * + * @author Andrew Woods + * Date: 9/14/11 + */ +public class DuplicationEvent implements Delayed { + + private final Logger log = LoggerFactory.getLogger(DuplicationEvent.class); + + private static final String header = + "space-id" + DELIM + "content-id" + DELIM + "md5" + DELIM + "event" + + DELIM + "success" + DELIM + "date-time" + DELIM + "message"; + + private String spaceId; + private String contentId; + private String md5; + private String error; + private TYPE type; + private final long eventTime; + + private boolean success; + + private long delayDeadline; + + public static enum TYPE { + SPACE_CREATE, + SPACE_UPDATE, + SPACE_DELETE, + CONTENT_CREATE, + CONTENT_UPDATE, + CONTENT_DELETE; + } + + public DuplicationEvent(String spaceId, TYPE type) { + this(spaceId, null, type); + } + + public DuplicationEvent(String spaceId, String contentId, TYPE type) { + this(spaceId, contentId, null, type); + } + + public DuplicationEvent(String spaceId, + String contentId, + String md5, + TYPE type) { + this.spaceId = spaceId; + this.contentId = contentId; + this.md5 = md5; + this.type = type; + + this.eventTime = System.currentTimeMillis(); + this.success = true; + } + + public void setDelay(long delayMillis) { + log.debug("setDelay({})", delayMillis); + delayDeadline = System.currentTimeMillis() + delayMillis; + } + + @Override + public long getDelay(TimeUnit timeUnit) { + long delay = delayDeadline - System.currentTimeMillis(); + return timeUnit.convert(delay, TimeUnit.MILLISECONDS); + } + + @Override + public int compareTo(Delayed that) { + long thisDelay = this.getDelay(TimeUnit.NANOSECONDS); + long thatDelay = that.getDelay(TimeUnit.NANOSECONDS); + + return thisDelay == thatDelay ? 0 : (thisDelay > thatDelay ? 1 : -1); + } + + public String getSpaceId() { + return spaceId; + } + + public String getContentId() { + return contentId; + } + + public boolean isSuccess() { + return success; + } + + public void fail(String error) { + this.success = false; + this.error = error; + } + + public String getHeader() { + return header; + } + + public String getEntry() { + StringBuilder entry = new StringBuilder(); + entry.append(spaceId); + entry.append(DELIM); + entry.append(null == contentId ? "-" : contentId); + entry.append(DELIM); + entry.append(null == md5 ? "-" : md5); + entry.append(DELIM); + entry.append(getType()); + entry.append(DELIM); + entry.append(isSuccess()); + entry.append(DELIM); + entry.append(DateUtil.convertToStringMid(eventTime)); + entry.append(DELIM); + entry.append(null == error ? "-" : error); + + return entry.toString(); + } + + public TYPE getType() { + return type; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("DuplicationEvent:["); + sb.append(getEntry()); + sb.append("]"); + return sb.toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DuplicationEvent)) { + return false; + } + + DuplicationEvent that = (DuplicationEvent) o; + + if (contentId != null ? !contentId.equals(that.contentId) : + that.contentId != null) { + return false; + } + if (spaceId != null ? !spaceId.equals(that.spaceId) : + that.spaceId != null) { + return false; + } + if (type != that.type) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = spaceId != null ? spaceId.hashCode() : 0; + result = 31 * result + (contentId != null ? contentId.hashCode() : 0); + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } +} diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationResult.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationResult.java deleted file mode 100644 index 32c5f5a5a..000000000 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationResult.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * The contents of this file are subject to the license and copyright - * detailed in the LICENSE and NOTICE files at the root of the source - * tree and available online at - * - * http://duracloud.org/license/ - */ -package org.duracloud.services.duplication.result; - -/** - * This class holds details of a duplication result. - * - * @author Andrew Woods - * Date: 9/14/11 - */ -public class DuplicationResult { - // TODO: implement -} diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationResultListener.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationResultListener.java index d500fa2f1..b02424cb2 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationResultListener.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/DuplicationResultListener.java @@ -7,7 +7,19 @@ */ package org.duracloud.services.duplication.result; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; import org.duracloud.client.ContentStore; +import org.duracloud.error.ContentStoreException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; /** * This class listens for duplication events and reports on their success or @@ -18,16 +30,108 @@ */ public class DuplicationResultListener implements ResultListener { + private final Logger log = + LoggerFactory.getLogger(DuplicationResultListener.class); + + private static final String newline = System.getProperty("line.separator"); + + private ContentStore contentStore; + private String spaceId; + private String reportId; + private File resultsFile; public DuplicationResultListener(ContentStore contentStore, String spaceId, String reportId, String workDir) { - // Default method body + this.contentStore = contentStore; + this.spaceId = spaceId; + this.reportId = reportId; + + this.resultsFile = new File(workDir, this.reportId); + if (resultsFile.exists()) { + resultsFile.delete(); + } } @Override - public void processResult(DuplicationResult result) { - // Default method body + public void processResult(DuplicationEvent event) { + log.debug("processing event: {}", event); + + if (isRecursiveUpdate(event)) { + log.debug("not propagating recursive update: {}", event); + return; + } + + writeToLocalResultsFile(event); + InputStream resultsStream = getLocalResultsFileStream(); + try { + contentStore.addContent(spaceId, + reportId, + resultsStream, + resultsFile.length(), + "text/csv", + null, + null); + + } catch (ContentStoreException e) { + String err = "Error attempting to store duplication service " + + "results to {}/{}, due to: {}"; + log.error(err, new Object[]{spaceId, reportId, e.getMessage()}); + + } finally { + IOUtils.closeQuietly(resultsStream); + } + } + + private boolean isRecursiveUpdate(DuplicationEvent event) { + return spaceId.equals(event.getSpaceId()) && + reportId.equals(event.getContentId()); } + + private void writeToLocalResultsFile(DuplicationEvent event) { + if (!resultsFile.exists()) { + mkdir(resultsFile); + write(event.getHeader()); + } + write(event.getEntry()); + } + + private void write(String text) { + boolean append = true; + FileWriter writer; + try { + writer = new FileWriter(resultsFile, append); + writer.append(text); + writer.append(newline); + writer.close(); + + } catch (IOException e) { + StringBuilder sb = new StringBuilder("Error writing event: '"); + sb.append(text); + sb.append("' to results file: "); + sb.append(resultsFile.getAbsolutePath()); + sb.append(", exception: "); + sb.append(e.getMessage()); + log.error(sb.toString()); + } + } + + private void mkdir(File file) { + try { + FileUtils.forceMkdir(file.getParentFile()); + } catch (IOException e) { + // do nothing + } + } + + private InputStream getLocalResultsFileStream() { + try { + return new FileInputStream(resultsFile); + } catch (FileNotFoundException e) { + throw new RuntimeException( + "Could not create results stream: " + e.getMessage(), e); + } + } + } diff --git a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/ResultListener.java b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/ResultListener.java index 3baf45581..00d93d971 100644 --- a/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/ResultListener.java +++ b/services/duplicationservice/src/main/java/org/duracloud/services/duplication/result/ResultListener.java @@ -16,10 +16,10 @@ public interface ResultListener { /** - * This method processes the arg duplication result. + * This method processes the arg duplication event. * - * @param result to be processed + * @param event to be processed */ - public void processResult(DuplicationResult result); + public void processResult(DuplicationEvent event); } diff --git a/services/duplicationservice/src/test/java/org/duracloud/services/duplication/ContentDuplicatorUpdateTest.java b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/ContentDuplicatorUpdateTest.java index 2e893f39d..3f4265243 100644 --- a/services/duplicationservice/src/test/java/org/duracloud/services/duplication/ContentDuplicatorUpdateTest.java +++ b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/ContentDuplicatorUpdateTest.java @@ -100,13 +100,25 @@ public void testUpdateContentGetPropertiesException() throws Exception { @Test public void testUpdateContentSetPropertiesException() throws Exception { init(Mode.SET_PROPERTIES_EXCEPTION); - replicator.updateContent(spaceId, contentId); + try { + replicator.updateContent(spaceId, contentId); + Assert.fail("exception expected"); + + } catch (DuplicationException e) { + Assert.assertNotNull(e.getMessage()); + } } @Test public void testUpdateContentNotFound() throws Exception { init(Mode.NOT_FOUND); - replicator.updateContent(spaceId, contentId); + try { + replicator.updateContent(spaceId, contentId); + Assert.fail("exception expected"); + + } catch (DuplicationException e) { + Assert.assertNotNull(e.getMessage()); + } } @Test @@ -181,7 +193,18 @@ private ContentStore createMockToStore(Mode cmd) throws ContentStoreException { ContentStore store = EasyMock.createMock("ToStore", ContentStore.class); - int times = cmd == Mode.NOT_FOUND ? 2 : 1; + int times; + switch (cmd) { + case NOT_FOUND: + times = 3; + break; + case SET_PROPERTIES_EXCEPTION: + times = 2; + break; + default: + times = 1; + } + EasyMock.expect(store.getStorageProviderType()) .andReturn("t-type") .times(times); diff --git a/services/duplicationservice/src/test/java/org/duracloud/services/duplication/impl/ContentDuplicatorReportingImplTest.java b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/impl/ContentDuplicatorReportingImplTest.java new file mode 100644 index 000000000..eabd6b4fc --- /dev/null +++ b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/impl/ContentDuplicatorReportingImplTest.java @@ -0,0 +1,262 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.duplication.impl; + +import org.duracloud.services.duplication.ContentDuplicator; +import org.duracloud.services.duplication.error.DuplicationException; +import org.duracloud.services.duplication.result.DuplicationEvent; +import org.duracloud.services.duplication.result.ResultListener; +import org.easymock.Capture; +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.CREATE_SUCCESS; +import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.UPDATE_SUCCESS; +import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.DELETE_SUCCESS; +import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.CREATE_ERROR; +import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.UPDATE_ERROR; +import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.DELETE_ERROR; + +/** + * @author Andrew Woods + * Date: 9/18/11 + */ +public class ContentDuplicatorReportingImplTest { + private ContentDuplicatorReportingImpl contentDuplicatorReporting; + + private ContentDuplicator contentDuplicator; + private ResultListener listener; + + private final String spaceId = "space-id"; + private final String contentId = "content-id"; + private final long waitMillis = 1; + + @Before + public void setUp() throws Exception { + contentDuplicator = EasyMock.createMock("ContentDuplicator", + ContentDuplicator.class); + listener = EasyMock.createMock("ResultListener", ResultListener.class); + } + + @After + public void tearDown() throws Exception { + EasyMock.verify(contentDuplicator, listener); + contentDuplicatorReporting.stop(); + } + + private void replayMocks() { + EasyMock.replay(contentDuplicator, listener); + } + + @Test + public void testStop() throws Exception { + // set up mocks + List<String> contents = new ArrayList<String>(); + List<Capture<DuplicationEvent>> captures = + new ArrayList<Capture<DuplicationEvent>>(); + createStopMocks(contents, captures); + replayMocks(); + + // create object under test + contentDuplicatorReporting = new ContentDuplicatorReportingImpl( + contentDuplicator, + listener); + + // exercise the test scenario + for (String content : contents) { + contentDuplicatorReporting.createContent(spaceId, content); + } + contentDuplicatorReporting.stop(); + + // verify + Assert.assertEquals(contents.size(), captures.size()); + for (Capture<DuplicationEvent> capture : captures) { + DuplicationEvent event = capture.getValue(); + Assert.assertNotNull(event); + Assert.assertFalse(event.isSuccess()); + } + + Assert.assertFalse(contentDuplicatorReporting.eventsExist()); + } + + private void createStopMocks(List<String> contents, + List<Capture<DuplicationEvent>> captures) { + for (int i = 0; i < 5; ++i) { + String content = contentId + "-" + i; + contents.add(content); + + Capture<DuplicationEvent> capture = new Capture<DuplicationEvent>(); + captures.add(capture); + + listener.processResult(EasyMock.capture(capture)); + EasyMock.expectLastCall(); + } + EasyMock.makeThreadSafe(contentDuplicator, true); + } + + @Test + public void testCreateSpace() throws Exception { + doTestSpace(CREATE_SUCCESS); + } + + @Test + public void testCreateSpaceError() throws Exception { + doTestSpace(CREATE_ERROR); + } + + @Test + public void testUpdateSpace() throws Exception { + doTestSpace(UPDATE_SUCCESS); + } + + @Test + public void testUpdateSpaceError() throws Exception { + doTestSpace(UPDATE_ERROR); + } + + @Test + public void testDeleteSpace() throws Exception { + doTestSpace(DELETE_SUCCESS); + } + + @Test + public void testDeleteSpaceError() throws Exception { + doTestSpace(DELETE_ERROR); + } + + private void doTestSpace(MODE mode) throws Exception { + Capture<DuplicationEvent> capture = createMocks(mode); + replayMocks(); + + contentDuplicatorReporting = new ContentDuplicatorReportingImpl( + contentDuplicator, + listener, + waitMillis); + + switch (mode) { + case CREATE_SUCCESS: + case CREATE_ERROR: + contentDuplicatorReporting.createContent(spaceId, contentId); + break; + + case UPDATE_SUCCESS: + case UPDATE_ERROR: + contentDuplicatorReporting.updateContent(spaceId, contentId); + break; + + case DELETE_SUCCESS: + case DELETE_ERROR: + contentDuplicatorReporting.deleteContent(spaceId, contentId); + break; + } + waitForCompletion(); + + DuplicationEvent event = capture.getValue(); + Assert.assertNotNull(event); + + Assert.assertEquals(mode.isValid(), event.isSuccess()); + Assert.assertEquals(mode.getType(), event.getType()); + } + + private Capture<DuplicationEvent> createMocks(MODE mode) { + switch (mode) { + case CREATE_SUCCESS: + EasyMock.expect(contentDuplicator.createContent(spaceId, + contentId)) + .andReturn("md5"); + break; + + case UPDATE_SUCCESS: + contentDuplicator.updateContent(spaceId, contentId); + EasyMock.expectLastCall(); + break; + + case DELETE_SUCCESS: + contentDuplicator.deleteContent(spaceId, contentId); + EasyMock.expectLastCall(); + break; + + case CREATE_ERROR: + contentDuplicator.createContent(spaceId, contentId); + EasyMock.expectLastCall().andThrow(new DuplicationException( + "canned-exception")).times( + SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); + EasyMock.makeThreadSafe(contentDuplicator, true); + break; + + case UPDATE_ERROR: + contentDuplicator.updateContent(spaceId, contentId); + EasyMock.expectLastCall().andThrow(new DuplicationException( + "canned-exception")).times( + SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); + EasyMock.makeThreadSafe(contentDuplicator, true); + break; + + case DELETE_ERROR: + contentDuplicator.deleteContent(spaceId, contentId); + EasyMock.expectLastCall().andThrow(new DuplicationException( + "canned-exception")).times( + SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); + EasyMock.makeThreadSafe(contentDuplicator, true); + break; + + default: + Assert.fail("Unexpected mode: " + mode); + } + + Capture<DuplicationEvent> capturedResult = + new Capture<DuplicationEvent>(); + listener.processResult(EasyMock.capture(capturedResult)); + + return capturedResult; + } + + private void waitForCompletion() throws InterruptedException { + final long maxWait = 5000; + long waited = 0; + long wait = 400; + while (contentDuplicatorReporting.eventsExist()) { + Thread.sleep(wait); + waited += wait; + if (waited > maxWait) { + Assert.fail("test exceeded time limit: " + maxWait); + } + } + } + + protected enum MODE { + CREATE_SUCCESS(true, DuplicationEvent.TYPE.CONTENT_CREATE), + UPDATE_SUCCESS(true, DuplicationEvent.TYPE.CONTENT_UPDATE), + DELETE_SUCCESS(true, DuplicationEvent.TYPE.CONTENT_DELETE), + CREATE_ERROR(false, DuplicationEvent.TYPE.CONTENT_CREATE), + UPDATE_ERROR(false, DuplicationEvent.TYPE.CONTENT_UPDATE), + DELETE_ERROR(false, DuplicationEvent.TYPE.CONTENT_DELETE); + + private boolean valid; + private DuplicationEvent.TYPE type; + + private MODE(boolean valid, DuplicationEvent.TYPE type) { + this.valid = valid; + this.type = type; + } + + public boolean isValid() { + return valid; + } + + public DuplicationEvent.TYPE getType() { + return type; + } + } +} diff --git a/services/duplicationservice/src/test/java/org/duracloud/services/duplication/impl/SpaceDuplicatorReportingImplTest.java b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/impl/SpaceDuplicatorReportingImplTest.java new file mode 100644 index 000000000..e57d151c6 --- /dev/null +++ b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/impl/SpaceDuplicatorReportingImplTest.java @@ -0,0 +1,267 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.duplication.impl; + +import org.duracloud.services.duplication.SpaceDuplicator; +import org.duracloud.services.duplication.error.DuplicationException; +import org.duracloud.services.duplication.result.DuplicationEvent; +import org.duracloud.services.duplication.result.ResultListener; +import org.easymock.Capture; +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.duracloud.services.duplication.impl.SpaceDuplicatorReportingImplTest.MODE.CREATE_ERROR; +import static org.duracloud.services.duplication.impl.SpaceDuplicatorReportingImplTest.MODE.CREATE_SUCCESS; +import static org.duracloud.services.duplication.impl.SpaceDuplicatorReportingImplTest.MODE.DELETE_ERROR; +import static org.duracloud.services.duplication.impl.SpaceDuplicatorReportingImplTest.MODE.DELETE_SUCCESS; +import static org.duracloud.services.duplication.impl.SpaceDuplicatorReportingImplTest.MODE.UPDATE_ERROR; +import static org.duracloud.services.duplication.impl.SpaceDuplicatorReportingImplTest.MODE.UPDATE_SUCCESS; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.SPACE_CREATE; + +/** + * @author Andrew Woods + * Date: 9/16/11 + */ +public class SpaceDuplicatorReportingImplTest { + + private SpaceDuplicatorReportingImpl spaceDuplicatorReporting; + + private SpaceDuplicator spaceDuplicator; + private ResultListener listener; + + private final String spaceId = "space-id"; + private final long waitMillis = 1; + + @Before + public void setUp() throws Exception { + spaceDuplicator = EasyMock.createMock("SpaceDuplicator", + SpaceDuplicator.class); + listener = EasyMock.createMock("ResultListener", ResultListener.class); + } + + @After + public void tearDown() throws Exception { + EasyMock.verify(spaceDuplicator, listener); + spaceDuplicatorReporting.stop(); + } + + private void replayMocks() { + EasyMock.replay(spaceDuplicator, listener); + } + + @Test + public void testStop() throws Exception { + // set up mocks + List<String> spaces = new ArrayList<String>(); + List<Capture<DuplicationEvent>> captures = + new ArrayList<Capture<DuplicationEvent>>(); + createStopMocks(spaces, captures); + replayMocks(); + + // create object under test + spaceDuplicatorReporting = new SpaceDuplicatorReportingImpl( + spaceDuplicator, + listener); + + // exercise the test scenario + for (String space : spaces) { + spaceDuplicatorReporting.createSpace(space); + } + spaceDuplicatorReporting.stop(); + + // verify + Assert.assertEquals(spaces.size(), captures.size()); + for (Capture<DuplicationEvent> capture : captures) { + DuplicationEvent event = capture.getValue(); + Assert.assertNotNull(event); + Assert.assertFalse(event.isSuccess()); + } + + Assert.assertFalse(spaceDuplicatorReporting.retriesExist()); + } + + private void createStopMocks(List<String> spaces, + List<Capture<DuplicationEvent>> captures) { + for (int i = 0; i < 5; ++i) { + String space = spaceId + "-" + i; + spaces.add(space); + + spaceDuplicator.createSpace(space); + EasyMock.expectLastCall().andThrow(new DuplicationException( + "canned-exception")); + + Capture<DuplicationEvent> capture = new Capture<DuplicationEvent>(); + captures.add(capture); + + listener.processResult(EasyMock.capture(capture)); + EasyMock.expectLastCall(); + } + EasyMock.makeThreadSafe(spaceDuplicator, true); + } + + @Test + public void testCreateSpace() throws Exception { + doTestSpace(CREATE_SUCCESS); + } + + @Test + public void testCreateSpaceError() throws Exception { + doTestSpace(CREATE_ERROR); + } + + @Test + public void testUpdateSpace() throws Exception { + doTestSpace(UPDATE_SUCCESS); + } + + @Test + public void testUpdateSpaceError() throws Exception { + doTestSpace(UPDATE_ERROR); + } + + @Test + public void testDeleteSpace() throws Exception { + doTestSpace(DELETE_SUCCESS); + } + + @Test + public void testDeleteSpaceError() throws Exception { + doTestSpace(DELETE_ERROR); + } + + private void doTestSpace(MODE mode) throws Exception { + Capture<DuplicationEvent> capture = createMocks(mode); + replayMocks(); + + spaceDuplicatorReporting = new SpaceDuplicatorReportingImpl( + spaceDuplicator, + listener, + waitMillis); + + switch (mode) { + case CREATE_SUCCESS: + case CREATE_ERROR: + spaceDuplicatorReporting.createSpace(spaceId); + break; + + case UPDATE_SUCCESS: + case UPDATE_ERROR: + spaceDuplicatorReporting.updateSpace(spaceId); + break; + + case DELETE_SUCCESS: + case DELETE_ERROR: + spaceDuplicatorReporting.deleteSpace(spaceId); + break; + } + waitForCompletion(); + + DuplicationEvent event = capture.getValue(); + Assert.assertNotNull(event); + + Assert.assertEquals(mode.isValid(), event.isSuccess()); + Assert.assertEquals(mode.getType(), event.getType()); + } + + private Capture<DuplicationEvent> createMocks(MODE mode) { + switch (mode) { + case CREATE_SUCCESS: + spaceDuplicator.createSpace(spaceId); + EasyMock.expectLastCall(); + break; + + case UPDATE_SUCCESS: + spaceDuplicator.updateSpace(spaceId); + EasyMock.expectLastCall(); + break; + + case DELETE_SUCCESS: + spaceDuplicator.deleteSpace(spaceId); + EasyMock.expectLastCall(); + break; + + case CREATE_ERROR: + spaceDuplicator.createSpace(spaceId); + EasyMock.expectLastCall().andThrow(new DuplicationException( + "canned-exception")).times( + SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); + EasyMock.makeThreadSafe(spaceDuplicator, true); + break; + + case UPDATE_ERROR: + spaceDuplicator.updateSpace(spaceId); + EasyMock.expectLastCall().andThrow(new DuplicationException( + "canned-exception")).times( + SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); + EasyMock.makeThreadSafe(spaceDuplicator, true); + break; + + case DELETE_ERROR: + spaceDuplicator.deleteSpace(spaceId); + EasyMock.expectLastCall().andThrow(new DuplicationException( + "canned-exception")).times( + SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); + EasyMock.makeThreadSafe(spaceDuplicator, true); + break; + + default: + Assert.fail("Unexpected mode: " + mode); + } + + Capture<DuplicationEvent> capturedResult = + new Capture<DuplicationEvent>(); + listener.processResult(EasyMock.capture(capturedResult)); + + return capturedResult; + } + + private void waitForCompletion() throws InterruptedException { + final long maxWait = 5000; + long waited = 0; + long wait = 400; + while (spaceDuplicatorReporting.retriesExist()) { + Thread.sleep(wait); + waited += wait; + if (waited > maxWait) { + Assert.fail("test exceeded time limit: " + maxWait); + } + } + } + + protected enum MODE { + CREATE_SUCCESS(true, SPACE_CREATE), + UPDATE_SUCCESS(true, DuplicationEvent.TYPE.SPACE_UPDATE), + DELETE_SUCCESS(true, DuplicationEvent.TYPE.SPACE_DELETE), + CREATE_ERROR(false, SPACE_CREATE), + UPDATE_ERROR(false, DuplicationEvent.TYPE.SPACE_UPDATE), + DELETE_ERROR(false, DuplicationEvent.TYPE.SPACE_DELETE); + + private boolean valid; + private DuplicationEvent.TYPE type; + + private MODE(boolean valid, DuplicationEvent.TYPE type) { + this.valid = valid; + this.type = type; + } + + public boolean isValid() { + return valid; + } + + public DuplicationEvent.TYPE getType() { + return type; + } + } + +} diff --git a/services/duplicationservice/src/test/java/org/duracloud/services/duplication/result/DuplicationEventTest.java b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/result/DuplicationEventTest.java new file mode 100644 index 000000000..8e1a1edc1 --- /dev/null +++ b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/result/DuplicationEventTest.java @@ -0,0 +1,246 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.duplication.result; + +import org.duracloud.common.util.DateUtil; +import org.duracloud.services.ComputeService; +import org.junit.Assert; +import org.junit.Test; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.CONTENT_CREATE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.CONTENT_UPDATE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.SPACE_CREATE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.SPACE_DELETE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.SPACE_UPDATE; + +/** + * @author Andrew Woods + * Date: 9/18/11 + */ +public class DuplicationEventTest { + + private DuplicationEvent event; + + private static final String spaceId = "space-id"; + private static final String contentId = "content-id"; + + @Test + public void testGetDelay() throws Exception { + event = new DuplicationEvent(spaceId, SPACE_UPDATE); + + // before setting a delay, delay shows as expired + long delay = event.getDelay(NANOSECONDS); + Assert.assertTrue("delay: " + delay, delay < 0); + + // set delay for 500 millis out + long delayMillis = 500; + event.setDelay(delayMillis); + delay = event.getDelay(NANOSECONDS); + + // verify + long expectedDelay = NANOSECONDS.convert(delayMillis, MILLISECONDS); + Assert.assertTrue("delay / expected: " + delay + " / " + expectedDelay, + delay <= expectedDelay); + + // rest a moment + Thread.sleep(delayMillis + 1); + + // verify delay has expired + delay = event.getDelay(NANOSECONDS); + Assert.assertTrue("delay: " + delay, delay < 0); + } + + @Test + public void testCompareTo() throws Exception { + DuplicationEvent e0 = new DuplicationEvent(spaceId, SPACE_UPDATE); + DuplicationEvent e1 = new DuplicationEvent(spaceId, SPACE_UPDATE); + DuplicationEvent e2 = new DuplicationEvent(spaceId, SPACE_UPDATE); + + Assert.assertEquals(0, e0.compareTo(e0)); + Assert.assertEquals(0, e1.compareTo(e1)); + Assert.assertEquals(0, e2.compareTo(e2)); + + Assert.assertEquals(0, e0.compareTo(e1)); + Assert.assertEquals(0, e0.compareTo(e2)); + Assert.assertEquals(0, e1.compareTo(e2)); + + e1.setDelay(500); + e2.setDelay(1000); + + long delay0 = e0.getDelay(NANOSECONDS); + long delay1 = e1.getDelay(NANOSECONDS); + long delay2 = e2.getDelay(NANOSECONDS); + + Assert.assertTrue(delay0 + ":" + delay1, e0.compareTo(e1) < 0); + Assert.assertTrue(delay0 + ":" + delay2, e0.compareTo(e2) < 0); + Assert.assertTrue(delay1 + ":" + delay2, e1.compareTo(e2) < 0); + + Assert.assertTrue(delay2 + ":" + delay0, e2.compareTo(e0) > 0); + Assert.assertTrue(delay2 + ":" + delay1, e2.compareTo(e1) > 0); + Assert.assertTrue(delay1 + ":" + delay0, e1.compareTo(e0) > 0); + } + + @Test + public void testGetSpaceId() throws Exception { + event = new DuplicationEvent(spaceId, SPACE_DELETE); + Assert.assertEquals(spaceId, event.getSpaceId()); + } + + @Test + public void testGetContentId() throws Exception { + event = new DuplicationEvent(spaceId, SPACE_DELETE); + Assert.assertNull(event.getContentId()); + + event = new DuplicationEvent(spaceId, contentId, CONTENT_CREATE); + Assert.assertEquals(contentId, event.getContentId()); + } + + @Test + public void testIsSuccess() throws Exception { + event = new DuplicationEvent(spaceId, SPACE_DELETE); + Assert.assertTrue(event.isSuccess()); + + event.fail("canned-message"); + Assert.assertTrue(!event.isSuccess()); + } + + @Test + public void testFail() throws Exception { + event = new DuplicationEvent(spaceId, SPACE_DELETE); + + String msg = "test-event-failed"; + Assert.assertTrue(!event.getEntry().contains(msg)); + + event.fail(msg); + Assert.assertTrue(event.getEntry().contains(msg)); + } + + @Test + public void testGetHeader() throws Exception { + event = new DuplicationEvent(spaceId, SPACE_DELETE); + String header = event.getHeader(); + + List<String> fields = new ArrayList<String>(); + fields.add("space-id"); + fields.add("content-id"); + fields.add("md5"); + fields.add("event"); + fields.add("success"); + fields.add("date-time"); + fields.add("message"); + + verifyEntry(fields, header); + } + + @Test + public void testGetEntrySpace() throws Exception { + DuplicationEvent.TYPE type = SPACE_CREATE; + event = new DuplicationEvent(spaceId, type); + + String entry = event.getEntry(); + + List<String> fields = new ArrayList<String>(); + fields.add(spaceId); + fields.add("-"); + fields.add("-"); + fields.add(type.name()); + fields.add(Boolean.TRUE.toString()); + fields.add(DateUtil.convertToStringMid(System.currentTimeMillis())); + fields.add("-"); + + verifyEntry(fields, entry); + } + + @Test + public void testGetEntryContent() throws Exception { + DuplicationEvent.TYPE type = CONTENT_UPDATE; + String error = "canned-message"; + + event = new DuplicationEvent(spaceId, contentId, type); + event.fail(error); + + String entry = event.getEntry(); + + List<String> fields = new ArrayList<String>(); + fields.add(spaceId); + fields.add(contentId); + fields.add("-"); + fields.add(type.name()); + fields.add(Boolean.FALSE.toString()); + fields.add(DateUtil.convertToStringMid(System.currentTimeMillis())); + fields.add(error); + + verifyEntry(fields, entry); + } + + private void verifyEntry(List<String> fields, String entry) + throws ParseException { + Assert.assertNotNull(entry); + + String[] cols = entry.split(Character.toString(ComputeService.DELIM)); + Assert.assertEquals(fields.size(), cols.length); + + for (int i = 0; i < fields.size(); ++i) { + String field = fields.get(i); + String col = cols[i]; + Assert.assertEquals(i + ": " + field + "|" + col, field, col); + } + } + + @Test + public void testGetType() throws Exception { + DuplicationEvent.TYPE type = SPACE_CREATE; + event = new DuplicationEvent(spaceId, type); + + Assert.assertEquals(type, event.getType()); + } + + @Test + public void testEquals() throws Exception { + DuplicationEvent e0 = new DuplicationEvent(spaceId, SPACE_UPDATE); + DuplicationEvent e1 = new DuplicationEvent(spaceId, SPACE_UPDATE); + DuplicationEvent e2 = new DuplicationEvent(spaceId, SPACE_UPDATE); + + e0.setDelay(500); + e1.setDelay(5000); + e2.setDelay(50000); + + Assert.assertEquals(e0, e0); + Assert.assertEquals(e0, e1); + Assert.assertEquals(e0, e2); + Assert.assertEquals(e1, e2); + + e0.fail("error-msg"); + e1.fail("error-msg-different"); + + Assert.assertEquals(e0, e0); + Assert.assertEquals(e0, e1); + Assert.assertEquals(e0, e2); + Assert.assertEquals(e1, e2); + } + + @Test + public void testEqualsNot() throws Exception { + DuplicationEvent e0 = new DuplicationEvent(spaceId, SPACE_UPDATE); + DuplicationEvent e1 = new DuplicationEvent(spaceId, SPACE_CREATE); + DuplicationEvent e2 = new DuplicationEvent(spaceId, + contentId, + CONTENT_UPDATE); + + Assert.assertTrue(!e0.equals(e1)); + Assert.assertTrue(!e0.equals(e2)); + Assert.assertTrue(!e1.equals(e2)); + } + +} diff --git a/services/duplicationservice/src/test/java/org/duracloud/services/duplication/result/DuplicationResultListenerTest.java b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/result/DuplicationResultListenerTest.java new file mode 100644 index 000000000..4b5dffe10 --- /dev/null +++ b/services/duplicationservice/src/test/java/org/duracloud/services/duplication/result/DuplicationResultListenerTest.java @@ -0,0 +1,148 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.duplication.result; + +import org.duracloud.client.ContentStore; +import org.duracloud.error.ContentStoreException; +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.InputStream; +import java.util.Map; + +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.CONTENT_CREATE; +import static org.duracloud.services.duplication.result.DuplicationEvent.TYPE.SPACE_CREATE; +import static org.duracloud.services.duplication.result.DuplicationResultListenerTest.MODE.INVALID; +import static org.duracloud.services.duplication.result.DuplicationResultListenerTest.MODE.VALID; +import static org.duracloud.services.duplication.result.DuplicationResultListenerTest.MODE.VALID_REPORT; + +/** + * @author Andrew Woods + * Date: 9/16/11 + */ +public class DuplicationResultListenerTest { + + private DuplicationResultListener listener; + + private ContentStore contentStore; + private final String spaceId = "space-id"; + private final String reportId = "report-content-id"; + private String workDir; + + @Before + public void setUp() throws Exception { + contentStore = EasyMock.createMock("ContentStore", ContentStore.class); + + File target = new File("target"); + Assert.assertTrue("target directory must exist!", target.exists()); + + File work = new File(target, "test-dup-listener"); + if (!work.exists()) { + Assert.assertTrue("Error: " + work.getAbsolutePath(), work.mkdir()); + } + + workDir = work.getAbsolutePath(); + } + + @After + public void tearDown() throws Exception { + EasyMock.verify(contentStore); + } + + private void replayMocks() { + EasyMock.replay(contentStore); + } + + @Test + public void testProcessResult() throws Exception { + createProcessResultMocks(VALID); + replayMocks(); + + listener = new DuplicationResultListener(contentStore, + spaceId, + reportId, + workDir); + + DuplicationEvent event = new DuplicationEvent(spaceId, SPACE_CREATE); + listener.processResult(event); + } + + @Test + public void testProcessResultReportId() throws Exception { + createProcessResultMocks(VALID_REPORT); + replayMocks(); + + listener = new DuplicationResultListener(contentStore, + spaceId, + reportId, + workDir); + + DuplicationEvent event = new DuplicationEvent(spaceId, + reportId, + CONTENT_CREATE); + listener.processResult(event); + } + + @Test + public void testProcessResultError() throws Exception { + createProcessResultMocks(INVALID); + replayMocks(); + + listener = new DuplicationResultListener(contentStore, + spaceId, + reportId, + workDir); + + DuplicationEvent event = new DuplicationEvent(spaceId, SPACE_CREATE); + + // catches exception and writes a log. + listener.processResult(event); + } + + private void createProcessResultMocks(MODE mode) + throws ContentStoreException { + switch (mode) { + case VALID: + EasyMock.expect(contentStore.addContent(EasyMock.eq(spaceId), + EasyMock.eq(reportId), + EasyMock.<InputStream>anyObject(), + EasyMock.anyInt(), + EasyMock.eq("text/csv"), + EasyMock.<String>isNull(), + EasyMock.<Map<String, String>>isNull())) + .andReturn("md5"); + break; + + case VALID_REPORT: + break; + + case INVALID: + EasyMock.expect(contentStore.addContent(EasyMock.eq(spaceId), + EasyMock.eq(reportId), + EasyMock.<InputStream>anyObject(), + EasyMock.anyInt(), + EasyMock.eq("text/csv"), + EasyMock.<String>isNull(), + EasyMock.<Map<String, String>>isNull())) + .andThrow(new ContentStoreException("canned-exception")); + break; + + default: + Assert.fail("unexpected mode: " + mode); + } + + } + + protected enum MODE { + VALID, VALID_REPORT, INVALID; + } +}
96be7e81f00cd7d01a45d59793f02274a0dd4395
Valadoc
libvaladoc/api: Hide unbrowsable property getters and setters
c
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/api/propertyaccessor.vala b/src/libvaladoc/api/propertyaccessor.vala index 82e1ce4759..56e0f4918f 100644 --- a/src/libvaladoc/api/propertyaccessor.vala +++ b/src/libvaladoc/api/propertyaccessor.vala @@ -102,9 +102,15 @@ public class Valadoc.Api.PropertyAccessor : Symbol { protected override Inline build_signature () { var signature = new SignatureBuilder (); - if (!is_public) { + // FIXME + if (!do_document) { + return signature.get (); + } + + if (((Property) parent).accessibility != accessibility) { signature.append_keyword (accessibility.to_string ()); } + if (is_set || is_construct) { if (is_construct) { signature.append_keyword ("construct");
6468e8aa21f0fcf95bdd3eebb2e5109ba723621b
tapiji
Adapts the namespace of all TapiJI plug-ins to org.eclipselabs.tapiji.*.
p
https://github.com/tapiji/tapiji
diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_128.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_128.png new file mode 100644 index 00000000..98514e0e Binary files /dev/null and b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_128.png differ diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_16.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_16.png new file mode 100644 index 00000000..73b82c2f Binary files /dev/null and b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_16.png differ diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_32.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_32.png new file mode 100644 index 00000000..3984eba6 Binary files /dev/null and b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_32.png differ diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_48.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_48.png new file mode 100644 index 00000000..190a92e4 Binary files /dev/null and b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_48.png differ diff --git a/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_64.png b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_64.png new file mode 100644 index 00000000..89988073 Binary files /dev/null and b/at.ac.tuwien.inso.eclipse.tapiji/icons/TapiJI_64.png differ
8e2825d4b810af42170b471359accd677872ed0e
Vala
vapigen: add support for type_arguments on signal parameters
a
https://github.com/GNOME/vala/
diff --git a/vapigen/valagidlparser.vala b/vapigen/valagidlparser.vala index 771146fe42..3b154793bb 100644 --- a/vapigen/valagidlparser.vala +++ b/vapigen/valagidlparser.vala @@ -2302,6 +2302,11 @@ public class Vala.GIdlParser : CodeVisitor { p.parameter_type = param_type; } ((UnresolvedType) param_type).unresolved_symbol = new UnresolvedSymbol (null, eval (nv[1])); + } else if (nv[0] == "type_arguments") { + var type_args = eval (nv[1]).split (","); + foreach (string type_arg in type_args) { + p.parameter_type.add_type_argument (get_type_from_string (type_arg)); + } } else if (nv[0] == "namespace_name") { ns_name = eval (nv[1]); }
b1cdf8765d0d958217fe65568631c4be776eaaba
Delta Spike
DELTASPIKE-458 lookup UserTransaction via @Resource Fallback to JNDI only if the injected UserTransaction is not available (null)
c
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java index f08087a59..556b6d8a0 100644 --- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java +++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java @@ -24,6 +24,7 @@ import org.apache.deltaspike.jpa.api.transaction.TransactionConfig; import org.apache.deltaspike.jpa.impl.transaction.context.EntityManagerEntry; +import javax.annotation.Resource; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Alternative; import javax.persistence.EntityManager; @@ -55,6 +56,9 @@ public class BeanManagedUserTransactionStrategy extends ResourceLocalTransaction private transient TransactionConfig transactionConfig; + @Resource + private UserTransaction userTransaction; + @Override protected EntityManagerEntry createEntityManagerEntry( EntityManager entityManager, Class<? extends Annotation> qualifier) @@ -158,6 +162,11 @@ protected void beforeProceed(EntityManagerEntry entityManagerEntry) protected UserTransaction resolveUserTransaction() { + if (userTransaction != null) + { + return userTransaction; + } + return JndiUtils.lookup(USER_TRANSACTION_JNDI_NAME, UserTransaction.class); }
ebece5174a5ab834576c0f981682b78f7a6efe25
camel
CAMEL-1099: Added FileIdempotentRepositry--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@723291 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java b/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java index 776c5e3debfd8..d56f6c290bf61 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java +++ b/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.util.Map; import java.util.Scanner; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.camel.spi.IdempotentRepository; import org.apache.camel.util.LRUCache; @@ -40,34 +41,53 @@ public class FileIdempotentRepository implements IdempotentRepository<String> { private static final transient Log LOG = LogFactory.getLog(FileIdempotentRepository.class); private static final String STORE_DELIMITER = "\n"; private Map<String, Object> cache; - private File store; - private long maxStoreSize = 1024 * 1000L; // 1mb store file + private File fileStore; + private long maxFileStoreSize = 1024 * 1000L; // 1mb store file + private AtomicBoolean init = new AtomicBoolean(); - public FileIdempotentRepository(final File store, final Map<String, Object> set) { - this.store = store; + public FileIdempotentRepository() { + // default use a 1st level cache + this.cache = new LRUCache<String, Object>(1000); + } + + public FileIdempotentRepository(File fileStore, Map<String, Object> set) { + this.fileStore = fileStore; this.cache = set; - loadStore(); } /** * Creates a new file based repository using a {@link org.apache.camel.util.LRUCache} * as 1st level cache with a default of 1000 entries in the cache. * - * @param store the file store + * @param fileStore the file store */ - public static IdempotentRepository fileIdempotentRepository(File store) { - return fileIdempotentRepository(store, 1000); + public static IdempotentRepository fileIdempotentRepository(File fileStore) { + return fileIdempotentRepository(fileStore, 1000); } /** * Creates a new file based repository using a {@link org.apache.camel.util.LRUCache} * as 1st level cache. * - * @param store the file store + * @param fileStore the file store * @param cacheSize the cache size */ - public static IdempotentRepository fileIdempotentRepository(File store, int cacheSize) { - return fileIdempotentRepository(store, new LRUCache<String, Object>(cacheSize)); + public static IdempotentRepository fileIdempotentRepository(File fileStore, int cacheSize) { + return fileIdempotentRepository(fileStore, new LRUCache<String, Object>(cacheSize)); + } + + /** + * Creates a new file based repository using a {@link org.apache.camel.util.LRUCache} + * as 1st level cache. + * + * @param fileStore the file store + * @param cacheSize the cache size + * @param maxFileStoreSize the max size in bytes for the filestore file + */ + public static IdempotentRepository fileIdempotentRepository(File fileStore, int cacheSize, long maxFileStoreSize) { + FileIdempotentRepository repository = new FileIdempotentRepository(fileStore, new LRUCache<String, Object>(cacheSize)); + repository.setMaxFileStoreSize(maxFileStoreSize); + return repository; } /** @@ -86,11 +106,16 @@ public static IdempotentRepository fileIdempotentRepository(File store, Map<Stri public boolean add(String messageId) { synchronized (cache) { + // init store if not loaded before + if (init.compareAndSet(false, true)) { + loadStore(); + } + if (cache.containsKey(messageId)) { return false; } else { cache.put(messageId, messageId); - if (store.length() < maxStoreSize) { + if (fileStore.length() < maxFileStoreSize) { // just append to store appendToStore(messageId); } else { @@ -105,16 +130,20 @@ public boolean add(String messageId) { public boolean contains(String key) { synchronized (cache) { + // init store if not loaded before + if (init.compareAndSet(false, true)) { + loadStore(); + } return cache.containsKey(key); } } - public File getStore() { - return store; + public File getFileStore() { + return fileStore; } - public void setStore(File store) { - this.store = store; + public void setFileStore(File fileStore) { + this.fileStore = fileStore; } public Map<String, Object> getCache() { @@ -125,8 +154,8 @@ public void setCache(Map<String, Object> cache) { this.cache = cache; } - public long getMaxStoreSize() { - return maxStoreSize; + public long getMaxFileStoreSize() { + return maxFileStoreSize; } /** @@ -134,8 +163,18 @@ public long getMaxStoreSize() { * <p/> * The default is 1mb. */ - public void setMaxStoreSize(long maxStoreSize) { - this.maxStoreSize = maxStoreSize; + public void setMaxFileStoreSize(long maxFileStoreSize) { + this.maxFileStoreSize = maxFileStoreSize; + } + + /** + * Sets the cache size + */ + public void setCacheSize(int size) { + if (cache != null) { + cache.clear(); + } + cache = new LRUCache<String, Object>(size); } /** @@ -145,11 +184,16 @@ public void setMaxStoreSize(long maxStoreSize) { */ protected void appendToStore(final String messageId) { if (LOG.isDebugEnabled()) { - LOG.debug("Appending " + messageId + " to idempotent filestore: " + store); + LOG.debug("Appending " + messageId + " to idempotent filestore: " + fileStore); } FileOutputStream fos = null; try { - fos = new FileOutputStream(store, true); + // create store if missing + if (!fileStore.exists()) { + fileStore.createNewFile(); + } + // append to store + fos = new FileOutputStream(fileStore, true); fos.write(messageId.getBytes()); fos.write(STORE_DELIMITER.getBytes()); } catch (IOException e) { @@ -165,11 +209,11 @@ protected void appendToStore(final String messageId) { */ protected void trunkStore() { if (LOG.isDebugEnabled()) { - LOG.debug("Trunking idempotent filestore: " + store); + LOG.debug("Trunking idempotent filestore: " + fileStore); } FileOutputStream fos = null; try { - fos = new FileOutputStream(store); + fos = new FileOutputStream(fileStore); for (String key : cache.keySet()) { fos.write(key.getBytes()); fos.write(STORE_DELIMITER.getBytes()); @@ -186,17 +230,17 @@ protected void trunkStore() { */ protected void loadStore() { if (LOG.isTraceEnabled()) { - LOG.trace("Loading to 1st level cache from idempotent filestore: " + store); + LOG.trace("Loading to 1st level cache from idempotent filestore: " + fileStore); } - if (!store.exists()) { + if (!fileStore.exists()) { return; } cache.clear(); Scanner scanner = null; try { - scanner = new Scanner(store); + scanner = new Scanner(fileStore); scanner.useDelimiter(STORE_DELIMITER); while (scanner.hasNextLine()) { String line = scanner.nextLine(); @@ -211,7 +255,7 @@ protected void loadStore() { } if (LOG.isDebugEnabled()) { - LOG.debug("Loaded " + cache.size() + " to the 1st level cache from idempotent filestore: " + store); + LOG.debug("Loaded " + cache.size() + " to the 1st level cache from idempotent filestore: " + fileStore); } } diff --git a/camel-core/src/main/java/org/apache/camel/processor/idempotent/MemoryIdempotentRepository.java b/camel-core/src/main/java/org/apache/camel/processor/idempotent/MemoryIdempotentRepository.java index ae22aca8bb7f3..700f0edb87f00 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/idempotent/MemoryIdempotentRepository.java +++ b/camel-core/src/main/java/org/apache/camel/processor/idempotent/MemoryIdempotentRepository.java @@ -33,6 +33,10 @@ public class MemoryIdempotentRepository implements IdempotentRepository<String> private Map<String, Object> cache; + public MemoryIdempotentRepository() { + this.cache = new LRUCache<String, Object>(1000); + } + public MemoryIdempotentRepository(Map<String, Object> set) { this.cache = set; } @@ -42,7 +46,7 @@ public MemoryIdempotentRepository(Map<String, Object> set) { * with a default of 1000 entries in the cache. */ public static IdempotentRepository memoryIdempotentRepository() { - return memoryIdempotentRepository(1000); + return new MemoryIdempotentRepository(); } /** diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/idempotent/FileConsumerIdempotentTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/idempotent/FileConsumerIdempotentTest.java new file mode 100644 index 0000000000000..46c038f1f741b --- /dev/null +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/idempotent/FileConsumerIdempotentTest.java @@ -0,0 +1,77 @@ +/** + * 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.spring.processor.idempotent; + +import java.io.File; + +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.component.file.FileComponent; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.spi.IdempotentRepository; +import static org.apache.camel.spring.processor.SpringTestHelper.createSpringCamelContext; + +public class FileConsumerIdempotentTest extends ContextTestSupport { + + private IdempotentRepository repo; + + protected CamelContext createCamelContext() throws Exception { + return createSpringCamelContext(this, "org/apache/camel/spring/processor/idempotent/fileConsumerIdempotentTest.xml"); + } + + @Override + protected void setUp() throws Exception { + deleteDirectory("target/fileidempotent"); + + super.setUp(); + repo = context.getRegistry().lookup("fileStore", IdempotentRepository.class); + } + + + public void testIdempotent() throws Exception { + assertFalse(repo.contains("report.txt")); + + // send a file + template.sendBodyAndHeader("file://target/fileidempotent/", "Hello World", FileComponent.HEADER_FILE_NAME, "report.txt"); + + // consume the file the first time + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedMessageCount(1); + + assertMockEndpointsSatisfied(); + + // reset mock and set new expectations + mock.reset(); + mock.expectedMessageCount(0); + + // move file back + File file = new File("target/fileidempotent/done/report.txt"); + File renamed = new File("target/fileidempotent/report.txt"); + file = file.getAbsoluteFile(); + file.renameTo(renamed.getAbsoluteFile()); + + // sleep to let the consumer try to poll the file + Thread.sleep(2000); + + // should NOT consume the file again, let 2 secs pass to let the consumer try to consume it but it should not + assertMockEndpointsSatisfied(); + + assertTrue(repo.contains("report.txt")); + } + +} + diff --git a/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/idempotent/fileConsumerIdempotentTest.xml b/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/idempotent/fileConsumerIdempotentTest.xml new file mode 100644 index 0000000000000..8714d14db6bd3 --- /dev/null +++ b/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/idempotent/fileConsumerIdempotentTest.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd + http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring.xsd + "> + + <!-- START SNIPPET: example --> + <!-- this is our file based idempotent store configured to use the .filestore.dat as file --> + <bean id="fileStore" class="org.apache.camel.processor.idempotent.FileIdempotentRepository"> + <!-- the filename for the store --> + <property name="fileStore" value="target/fileidempotent/.filestore.dat"/> + <!-- the max filesize in bytes for the file. Camel will trunk and flush the cache + if the file gets bigger --> + <property name="maxFileStoreSize" value="512000"/> + <!-- the number of elements in our store --> + <property name="cacheSize" value="250"/> + </bean> + + <camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring"> + <route> + <from uri="file://target/fileidempotent/?idempotent=true&amp;idempotentRepositoryRef=fileStore&amp;moveNamePrefix=done/"/> + <to uri="mock:result"/> + </route> + </camelContext> + <!-- END SNIPPET: example --> +</beans>
13c851fc730cc900605f28582caeb12b8dcc89d9
Mylyn Reviews
322734: Open Review Compare in another editor
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java index 07d8d272..772324ca 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java @@ -10,18 +10,21 @@ *******************************************************************************/ package org.eclipse.mylyn.reviews.ui.editors; +import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.compare.CompareConfiguration; +import org.eclipse.compare.CompareEditorInput; import org.eclipse.compare.CompareUI; -import org.eclipse.compare.contentmergeviewer.TextMergeViewer; import org.eclipse.compare.patch.IFilePatch2; import org.eclipse.compare.patch.PatchConfiguration; -import org.eclipse.compare.structuremergeviewer.DiffNode; +import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.resource.CompositeImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; +import org.eclipse.jface.viewers.DoubleClickEvent; +import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; @@ -46,7 +49,6 @@ import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; -import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Image; @@ -55,7 +57,6 @@ 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.ISharedImages; import org.eclipse.ui.PlatformUI; @@ -69,11 +70,6 @@ public class ReviewTaskEditorPart extends AbstractTaskEditorPart { public static final String ID_PART_REVIEW = "org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPart"; //$NON-NLS-1$ private TableViewer fileList; - private Viewer viewer; - private boolean viewerInitialized; - private int[] weights; - private SashForm sashComposite; - private CompareConfiguration configuration; private Composite composite; public ReviewTaskEditorPart() { @@ -95,13 +91,9 @@ public void createControl(Composite parent, FormToolkit toolkit) { composite.setLayout(new GridLayout(1, true)); - sashComposite = new SashForm(composite, SWT.HORIZONTAL); - sashComposite - .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - fileList = new TableViewer(sashComposite); + fileList = new TableViewer(composite); fileList.getControl().setLayoutData( - new GridData(SWT.DEFAULT, SWT.FILL, false, true)); + new GridData(SWT.FILL, SWT.FILL, true, true)); TableViewerColumn column = new TableViewerColumn(fileList, SWT.LEFT); column.getColumn().setText(""); @@ -173,49 +165,47 @@ public Object[] getElements(Object inputElement) { return model; } }); + fileList.addDoubleClickListener(new IDoubleClickListener() { - fileList.addSelectionChangedListener(new ISelectionChangedListener() { - - public void selectionChanged(SelectionChangedEvent event) { + public void doubleClick(DoubleClickEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection sel = (IStructuredSelection) selection; if (sel.getFirstElement() instanceof ReviewDiffModel) { - ReviewDiffModel diffModel = ((ReviewDiffModel) sel + final ReviewDiffModel diffModel = ((ReviewDiffModel) sel .getFirstElement()); if (diffModel.canReview()) { - weights = sashComposite.getWeights(); - Viewer newViewer = CompareUI.findContentViewer( - viewerInitialized ? viewer : null, - diffModel.getCompareInput(), sashComposite, - configuration); - if (newViewer != null && newViewer != viewer) { - viewer.getControl().dispose(); - viewer = newViewer; - configureLayoutForDiffViewer(); - viewer.setInput(diffModel.getCompareInput()); - } + CompareConfiguration configuration = new CompareConfiguration(); + configuration.setLeftEditable(false); + configuration.setRightEditable(false); + configuration + .setLeftLabel(Messages.EditorSupport_Original); + configuration + .setRightLabel(Messages.EditorSupport_Patched); + configuration.setProperty( + CompareConfiguration.IGNORE_WHITESPACE, + false); + configuration + .setProperty( + CompareConfiguration.USE_OUTLINE_VIEW, + true); + CompareUI.openCompareEditor(new CompareEditorInput( + configuration) { + + @Override + protected Object prepareInput( + IProgressMonitor monitor) + throws InvocationTargetException, + InterruptedException { + return diffModel.getCompareInput(); + } + }, true); } } } } }); setInput(); - configuration = new CompareConfiguration(); - configuration.setLeftEditable(false); - configuration.setRightEditable(false); - configuration.setLeftLabel(Messages.EditorSupport_Original); - configuration.setRightLabel(Messages.EditorSupport_Patched); - configuration - .setProperty(CompareConfiguration.IGNORE_WHITESPACE, false); - configuration.setProperty(CompareConfiguration.USE_OUTLINE_VIEW, true); - // TODO - - viewerInitialized = false; - viewer = new TextMergeViewer(sashComposite, SWT.BORDER, configuration); - weights = new int[] { 1, 3 }; - configureLayoutForDiffViewer(); - viewer.setInput(getDiffEditorNullInput()); createResultFields(composite, toolkit); @@ -254,10 +244,11 @@ private void createResultFields(Composite composite, FormToolkit toolkit) { Composite resultComposite = toolkit.createComposite(composite); toolkit.paintBordersFor(resultComposite); resultComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, - false)); - resultComposite.setLayout(new GridLayout(2, false)); + false)); + resultComposite.setLayout(new GridLayout(2, false)); - toolkit.createLabel(resultComposite, "Rating").setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); + toolkit.createLabel(resultComposite, "Rating").setForeground( + toolkit.getColors().getColor(IFormColors.TITLE)); CCombo ratingsCombo = new CCombo(resultComposite, SWT.READ_ONLY | SWT.FLAT); ratingsCombo.setData(FormToolkit.KEY_DRAW_BORDER, @@ -294,7 +285,8 @@ public Image getImage(Object element) { ratingList.getControl().setLayoutData( new GridData(SWT.LEFT, SWT.TOP, false, false)); - toolkit.createLabel(resultComposite, "Review comment").setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); + toolkit.createLabel(resultComposite, "Review comment").setForeground( + toolkit.getColors().getColor(IFormColors.TITLE)); final Text commentText = toolkit.createText(resultComposite, "", SWT.BORDER | SWT.MULTI); GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); @@ -351,15 +343,6 @@ private Review parseFromAttachments() { return null; } - private void configureLayoutForDiffViewer() { - viewer.getControl().setLayoutData( - new GridData(SWT.FILL, SWT.FILL, true, true)); - if (getControl() != null) { - ((Composite) this.getControl()).layout(true); - } - sashComposite.setWeights(weights); - } - /** * Retrieves the review from the review data manager and fills the left * table with the files. @@ -372,10 +355,6 @@ private void setInput() { } } - private DiffNode getDiffEditorNullInput() { - return new DiffNode(new DiffNode(SWT.LEFT), new DiffNode(SWT.RIGHT)); - } - private static class MissingFile extends CompositeImageDescriptor { ISharedImages sharedImages = PlatformUI.getWorkbench() .getSharedImages(); @@ -433,10 +412,6 @@ private ImageData getBaseImageData() { } - public Control getSashComposite() { - return sashComposite; - } - @Override protected void fillToolBar(ToolBarManager manager) { // Depends on 288171
70f4fa9a293229d051b9f23ad54e8a3c40d5a686
Valadoc
libvaladoc: gir-reader: accept #[id].[id|func]
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/ctyperesolver.vala b/src/libvaladoc/ctyperesolver.vala index 74051360f3..863cc38851 100755 --- a/src/libvaladoc/ctyperesolver.vala +++ b/src/libvaladoc/ctyperesolver.vala @@ -70,7 +70,7 @@ public class Valadoc.CTypeResolver : Visitor { return !last_was_underscore; } - private string? translate_cname (string name) { + private string? translate_cname_to_g (string name) { if (is_capitalized_and_underscored (name)) { string[] segments = name.split ("_"); unowned string last_segment = segments[segments.length - 1]; @@ -143,7 +143,7 @@ public class Valadoc.CTypeResolver : Visitor { return node; } - string? alternative = translate_cname (_name); + string? alternative = translate_cname_to_g (_name); if (alternative != null) { return nodes.get (alternative); } @@ -162,6 +162,13 @@ public class Valadoc.CTypeResolver : Visitor { return this.tree.search_symbol_str (null, "GLib.FileStream.printf"); } + int dotpos = _name.index_of_char ('.'); + if (dotpos > 0) { + string fst = _name.substring (0, dotpos); + string snd = _name.substring (dotpos + 1); + return nodes.get (fst + ":" + snd); + } + return null; } @@ -283,7 +290,6 @@ public class Valadoc.CTypeResolver : Visitor { string parent_cname = get_parent_type_cname (item); if (parent_cname != null) { register_symbol (parent_cname+"->"+item.get_cname (), item); - register_symbol (parent_cname+"."+item.get_cname (), item); } } } diff --git a/src/libvaladoc/documentation/gtkdoccommentscanner.vala b/src/libvaladoc/documentation/gtkdoccommentscanner.vala index afc6f79522..62b102a945 100644 --- a/src/libvaladoc/documentation/gtkdoccommentscanner.vala +++ b/src/libvaladoc/documentation/gtkdoccommentscanner.vala @@ -331,25 +331,30 @@ public class Valadoc.Gtkdoc.Scanner { } else { id_len += id_len2 + separator_len; } - } else if (this.pos.has_prefix ("->")) { + } else if (this.pos.has_prefix ("->") || this.pos.has_prefix (".")) { unowned string sep_start = this.pos; int sep_column_start = this.column; + int separator_len = 1; + + if (this.pos.has_prefix ("->")) { + separator_len = 2; + next_char (); + } next_char (); - next_char (); Token? func_token = function_prefix (); if (func_token == null) { int id_len2; if ((id_len2 = id_prefix ()) > 0) { - id_len += 2 + id_len2; + id_len += separator_len + id_len2; } else { this.column = sep_column_start; this.pos = sep_start; } } else { - id_len += 2 + func_token.content.length; + id_len += separator_len + func_token.content.length; } }
291e15e330c9b71a0d0238e9d56d4b2a473356af
camel
CAMEL-1665 fixed the unit test error--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@781238 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/camel-core/src/test/java/org/apache/camel/processor/TransformToTest.java b/camel-core/src/test/java/org/apache/camel/processor/TransformToTest.java index b61690f5dd763..48def13c95e83 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/TransformToTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/TransformToTest.java @@ -52,7 +52,7 @@ public void testTransformToInvalidEndpoint() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { - from("direct:bar").transform(to("bar")); + from("direct:bar").transform(sendTo("bar")); } }); context.start(); @@ -71,7 +71,7 @@ protected RouteBuilder createRouteBuilder() throws Exception { @Override public void configure() throws Exception { from("direct:start") - .transform(to("direct:foo")).to("mock:result"); + .transform(sendTo("direct:foo")).to("mock:result"); from("direct:foo").process(new Processor() { public void process(Exchange exchange) throws Exception {
1153de63158a534c230cb541ca3f74764aa0a50c
Vala
json-glib-1.0: hide user data arguments from two methods
c
https://github.com/GNOME/vala/
diff --git a/vapi/json-glib-1.0.vapi b/vapi/json-glib-1.0.vapi index f5195cb762..f496c2cc1a 100644 --- a/vapi/json-glib-1.0.vapi +++ b/vapi/json-glib-1.0.vapi @@ -16,7 +16,7 @@ namespace Json { public void add_object_element (owned Json.Object value); public void add_string_element (string value); public unowned Json.Node dup_element (uint index_); - public void foreach_element (Json.ArrayForeach func, void* data); + public void foreach_element (Json.ArrayForeach func); public unowned Json.Array get_array_element (uint index_); public bool get_boolean_element (uint index_); public double get_double_element (uint index_); @@ -85,7 +85,7 @@ namespace Json { public Object (); public void add_member (string member_name, owned Json.Node node); public unowned Json.Node dup_member (string member_name); - public void foreach_member (Json.ObjectForeach func, void* data); + public void foreach_member (Json.ObjectForeach func); public unowned Json.Array get_array_member (string member_name); public bool get_boolean_member (string member_name); public double get_double_member (string member_name); diff --git a/vapi/packages/json-glib-1.0/json-glib-1.0.metadata b/vapi/packages/json-glib-1.0/json-glib-1.0.metadata index ed1a81c450..59ede143b3 100644 --- a/vapi/packages/json-glib-1.0/json-glib-1.0.metadata +++ b/vapi/packages/json-glib-1.0/json-glib-1.0.metadata @@ -10,6 +10,7 @@ json_serialize_gobject cheader_filename="json-glib/json-glib.h,json-glib/json-go json_serialize_gobject.length is_out="1" json_array_add_array_element.value transfer_ownership="1" json_array_add_element.node transfer_ownership="1" +json_array_foreach_element.data hidden="1" json_array_add_object_element.value transfer_ownership="1" json_array_get_elements type_arguments="unowned Node" transfer_ownership="1" json_gobject_to_data transfer_ownership="1" @@ -24,6 +25,7 @@ json_node_take_object.object transfer_ownership="1" json_object_get_members type_arguments="unowned string" transfer_ownership="1" json_object_get_values type_arguments="unowned Node" transfer_ownership="1" json_object_add_member.node transfer_ownership="1" +json_object_foreach_member.data hidden="1" json_object_set_array_member.value transfer_ownership="1" json_object_set_object_member.value transfer_ownership="1" json_parser_load_from_data.length default_value="-1"
c1af71dbf3e85cba514b7cda53ffa20618f7cda3
hidendra$lwc
FULL removal of Memory Database. Every single usage of it has been removed - gone. Still may be UNSTABLE and volatile; it has not be tested extensively just yet !! [#53] The current implementation will be smoothed out later on.
p
https://github.com/hidendra/lwc
diff --git a/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java b/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java index 0ac0df12b..cf9c04c67 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java +++ b/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java @@ -19,6 +19,7 @@ import com.griefcraft.lwc.LWC; import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCBlockInteractEvent; @@ -41,9 +42,9 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { LWC lwc = event.getLWC(); Protection protection = event.getProtection(); - Player player = event.getPlayer(); + LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); - Action action = lwc.getMemoryDatabase().getAction("forceowner", player.getName()); + Action action = player.getAction("forceowner"); String newOwner = action.getData(); protection.setOwner(newOwner); @@ -106,10 +107,15 @@ public void onCommand(LWCCommandEvent event) { return; } - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String newOwner = args[1]; - lwc.getMemoryDatabase().registerAction("forceowner", player.getName(), newOwner); + Action action = new Action(); + action.setName("forceowner"); + action.setPlayer(player); + action.setData(newOwner); + player.addAction(action); + lwc.sendLocale(sender, "protection.admin.forceowner.finalize", "player", newOwner); return; diff --git a/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java b/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java index 408b80120..32f56cd3d 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java @@ -20,6 +20,7 @@ import com.griefcraft.lwc.LWC; import com.griefcraft.model.AccessRight; import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.model.ProtectionTypes; import com.griefcraft.scripting.JavaModule; @@ -29,7 +30,6 @@ import com.griefcraft.scripting.event.LWCProtectionInteractEvent; import com.griefcraft.scripting.event.LWCProtectionRegisterEvent; import com.griefcraft.scripting.event.LWCProtectionRegistrationPostEvent; -import com.griefcraft.sql.MemDB; import com.griefcraft.sql.PhysDB; import com.griefcraft.util.Colors; import com.griefcraft.util.StringUtils; @@ -76,16 +76,15 @@ public void onBlockInteract(LWCBlockInteractEvent event) { LWC lwc = event.getLWC(); Block block = event.getBlock(); - Player player = event.getPlayer(); + LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); if (!lwc.isProtectable(block)) { return; } PhysDB physDb = lwc.getPhysicalDatabase(); - MemDB memDb = lwc.getMemoryDatabase(); - Action action = memDb.getAction("create", player.getName()); + Action action = player.getAction("create"); String actionData = action.getData(); String[] split = actionData.split(" "); String protectionType = split[0].toLowerCase(); @@ -107,8 +106,8 @@ public void onBlockInteract(LWCBlockInteractEvent event) { int blockZ = block.getZ(); lwc.removeModes(player); - Result registerProtection = lwc.getModuleLoader().dispatchEvent(Event.REGISTER_PROTECTION, player, block); - LWCProtectionRegisterEvent evt = new LWCProtectionRegisterEvent(player, block); + Result registerProtection = lwc.getModuleLoader().dispatchEvent(Event.REGISTER_PROTECTION, player.getBukkitPlayer(), block); + LWCProtectionRegisterEvent evt = new LWCProtectionRegisterEvent(player.getBukkitPlayer(), block); lwc.getModuleLoader().dispatchEvent(evt); // another plugin cancelled the registration @@ -126,7 +125,7 @@ public void onBlockInteract(LWCBlockInteractEvent event) { String password = lwc.encrypt(protectionData); protection = physDb.registerProtection(block.getTypeId(), ProtectionTypes.PASSWORD, worldName, playerName, password, blockX, blockY, blockZ); - memDb.registerPlayer(playerName, protection.getId()); + player.addAccessibleProtection(protection); lwc.sendLocale(player, "protection.interact.create.finalize"); lwc.sendLocale(player, "protection.interact.create.password"); @@ -234,7 +233,7 @@ public void onCommand(LWCCommandEvent event) { return; } - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String full = StringUtils.join(args, 0); String type = args[0].toLowerCase(); @@ -272,12 +271,15 @@ public void onCommand(LWCCommandEvent event) { return; } - MemDB db = lwc.getMemoryDatabase(); - db.unregisterAllActions(player.getName()); - db.registerAction("create", player.getName(), full); + Action action = new Action(); + action.setName("create"); + action.setPlayer(player); + action.setData(full); + + player.removeAllActions(); + player.addAction(action); lwc.sendLocale(player, "protection.create.finalize", "type", lwc.getLocale(type)); - return; } } diff --git a/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java b/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java index 8d000e82f..92576dcde 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java @@ -19,13 +19,13 @@ import com.griefcraft.lwc.LWC; import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCCommandEvent; import com.griefcraft.scripting.event.LWCProtectionInteractEvent; import com.griefcraft.util.StringUtils; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; public class BaseFlagModule extends JavaModule { @@ -37,9 +37,9 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { LWC lwc = event.getLWC(); Protection protection = event.getProtection(); - Player player = event.getPlayer(); + LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); - Action action = lwc.getMemoryDatabase().getAction("flag", player.getName()); + Action action = player.getAction("flag"); String data = action.getData(); event.setResult(Result.CANCEL); @@ -99,7 +99,7 @@ public void onCommand(LWCCommandEvent event) { return; } - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String flagName = args[0]; String type = args[1].toLowerCase(); String internalType; // + or - @@ -142,8 +142,14 @@ public void onCommand(LWCCommandEvent event) { return; } - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); - lwc.getMemoryDatabase().registerAction("flag", player.getName(), internalType + flagName); + Action action = new Action(); + action.setName("flag"); + action.setPlayer(player); + action.setData(internalType + flagName); + + player.removeAllActions(); + player.addAction(action); + lwc.sendLocale(sender, "protection.flag.finalize"); return; diff --git a/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java b/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java index d880ebc4f..86dca114e 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java @@ -18,6 +18,8 @@ package com.griefcraft.modules.free; import com.griefcraft.lwc.LWC; +import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCBlockInteractEvent; @@ -110,19 +112,19 @@ public void onCommand(LWCCommandEvent event) { } String type = args[0].toLowerCase(); - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); if (type.equals("protection") || type.equals("chest") || type.equals("furnace") || type.equals("dispenser")) { - if (lwc.getMemoryDatabase().hasPendingChest(player.getName())) { - lwc.sendLocale(sender, "protection.general.pending"); - return; - } + Action action = new Action(); + action.setName("free"); + action.setPlayer(player); + + player.removeAllActions(); + player.addAction(action); - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); - lwc.getMemoryDatabase().registerAction("free", player.getName()); lwc.sendLocale(sender, "protection.remove.protection.finalize"); } else if (type.equals("modes")) { - lwc.getMemoryDatabase().unregisterAllModes(player.getName()); + player.disableAllModes(); lwc.sendLocale(sender, "protection.remove.modes.finalize"); } else { lwc.sendSimpleUsage(sender, "/lwc -r <protection|modes>"); diff --git a/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java b/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java index 840d8e71d..24a8f6e21 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java @@ -18,6 +18,8 @@ package com.griefcraft.modules.info; import com.griefcraft.lwc.LWC; +import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCBlockInteractEvent; @@ -99,7 +101,7 @@ public void onCommand(LWCCommandEvent event) { return; } - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String type = "info"; if (args.length > 0) { @@ -107,8 +109,13 @@ public void onCommand(LWCCommandEvent event) { } if (type.equals("info")) { - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); - lwc.getMemoryDatabase().registerAction("info", player.getName()); + Action action = new Action(); + action.setName("info"); + action.setPlayer(player); + + player.removeAllActions(); + player.addAction(action); + lwc.sendLocale(player, "protection.info.finalize"); } diff --git a/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java b/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java index 7e1e90db0..cbd0eb625 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java @@ -18,6 +18,9 @@ package com.griefcraft.modules.modes; import com.griefcraft.lwc.LWC; +import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; +import com.griefcraft.model.Mode; import com.griefcraft.model.Protection; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCCommandEvent; @@ -48,8 +51,8 @@ public void load(LWC lwc) { * @param player * @return */ - private boolean isPlayerDropTransferring(String player) { - return lwc.getMemoryDatabase().hasMode(player, "+dropTransfer"); + private boolean isPlayerDropTransferring(LWCPlayer player) { + return player.hasMode("+dropTransfer"); } /** @@ -58,8 +61,9 @@ private boolean isPlayerDropTransferring(String player) { * @param player * @return */ - private int getPlayerDropTransferTarget(String player) { - String target = lwc.getMemoryDatabase().getModeData(player, "dropTransfer"); + private int getPlayerDropTransferTarget(LWCPlayer player) { + Mode mode = player.getMode("dropTransfer"); + String target = mode.getData(); try { return Integer.parseInt(target); @@ -70,14 +74,15 @@ private int getPlayerDropTransferTarget(String player) { } @Override - public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) { - int protectionId = getPlayerDropTransferTarget(player.getName()); + public Result onDropItem(LWC lwc, Player bPlayer, Item item, ItemStack itemStack) { + LWCPlayer player = lwc.wrapPlayer(bPlayer); + int protectionId = getPlayerDropTransferTarget(player); if (protectionId == -1) { return DEFAULT; } - if (!isPlayerDropTransferring(player.getName())) { + if (!isPlayerDropTransferring(player)) { return DEFAULT; } @@ -85,7 +90,7 @@ public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) if (protection == null) { player.sendMessage(Colors.Red + "Protection no longer exists"); - lwc.getMemoryDatabase().unregisterMode(player.getName(), "dropTransfer"); + player.disableMode(player.getMode("dropTransfer")); return DEFAULT; } @@ -94,7 +99,7 @@ public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) if (world == null) { player.sendMessage(Colors.Red + "Invalid world!"); - lwc.getMemoryDatabase().unregisterMode(player.getName(), "dropTransfer"); + player.disableMode(player.getMode("dropTransfer")); return DEFAULT; } @@ -105,36 +110,46 @@ public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) player.sendMessage("Chest could not hold all the items! Have the remaining items back."); for (ItemStack temp : remaining.values()) { - player.getInventory().addItem(temp); + bPlayer.getInventory().addItem(temp); } } - player.updateInventory(); // if they're in the chest and dropping items, this is required + bPlayer.updateInventory(); // if they're in the chest and dropping items, this is required item.remove(); return DEFAULT; } @Override - public Result onProtectionInteract(LWC lwc, Player player, Protection protection, List<String> actions, boolean canAccess, boolean canAdmin) { + public Result onProtectionInteract(LWC lwc, Player bPlayer, Protection protection, List<String> actions, boolean canAccess, boolean canAdmin) { if (!actions.contains("dropTransferSelect")) { return DEFAULT; } + LWCPlayer player = lwc.wrapPlayer(bPlayer); + if (!canAccess) { lwc.sendLocale(player, "protection.interact.dropxfer.noaccess"); } else { if (protection.getBlockId() != Material.CHEST.getId()) { lwc.sendLocale(player, "protection.interact.dropxfer.notchest"); - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); + player.removeAllActions(); return CANCEL; } - lwc.getMemoryDatabase().registerMode(player.getName(), "dropTransfer", protection.getId() + ""); - lwc.getMemoryDatabase().registerMode(player.getName(), "+dropTransfer"); + Mode mode = new Mode(); + mode.setName("dropTransfer"); + mode.setData(protection.getId() + ""); + mode.setPlayer(bPlayer); + player.enableMode(mode); + mode = new Mode(); + mode.setName("+dropTransfer"); + mode.setPlayer(bPlayer); + player.enableMode(mode); + lwc.sendLocale(player, "protection.interact.dropxfer.finalize"); } - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); // ignore the persist mode + player.removeAllActions(); // ignore the persist mode return DEFAULT; } @@ -145,7 +160,7 @@ public Result onBlockInteract(LWC lwc, Player player, Block block, List<String> } lwc.sendLocale(player, "protection.interact.dropxfer.notprotected"); - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); + lwc.removeModes(player); return DEFAULT; } @@ -164,7 +179,7 @@ public void onCommand(LWCCommandEvent event) { CommandSender sender = event.getSender(); String[] args = event.getArgs(); - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String mode = args[0].toLowerCase(); if (!mode.equals("droptransfer")) { @@ -185,40 +200,48 @@ public void onCommand(LWCCommandEvent event) { String playerName = player.getName(); if (action.equals("select")) { - if (isPlayerDropTransferring(playerName)) { + if (isPlayerDropTransferring(player)) { lwc.sendLocale(player, "protection.modes.dropxfer.select.error"); return; } - lwc.getMemoryDatabase().unregisterMode(playerName, mode); - lwc.getMemoryDatabase().registerAction("dropTransferSelect", playerName, ""); + player.disableMode(player.getMode(mode)); + Action temp = new Action(); + temp.setName("dropTransferSelect"); + temp.setPlayer(player); + + player.addAction(temp); lwc.sendLocale(player, "protection.modes.dropxfer.select.finalize"); } else if (action.equals("on")) { - int target = getPlayerDropTransferTarget(playerName); + int target = getPlayerDropTransferTarget(player); if (target == -1) { lwc.sendLocale(player, "protection.modes.dropxfer.selectchest"); return; } - lwc.getMemoryDatabase().registerMode(playerName, "+dropTransfer"); + Mode temp = new Mode(); + temp.setName("+dropTransfer"); + temp.setPlayer(player.getBukkitPlayer()); + + player.enableMode(temp); lwc.sendLocale(player, "protection.modes.dropxfer.on.finalize"); } else if (action.equals("off")) { - int target = getPlayerDropTransferTarget(playerName); + int target = getPlayerDropTransferTarget(player); if (target == -1) { lwc.sendLocale(player, "protection.modes.dropxfer.selectchest"); return; } - lwc.getMemoryDatabase().unregisterMode(playerName, "+dropTransfer"); + player.disableMode(player.getMode("+dropTransfer")); lwc.sendLocale(player, "protection.modes.dropxfer.off.finalize"); } else if (action.equals("status")) { - if (getPlayerDropTransferTarget(playerName) == -1) { + if (getPlayerDropTransferTarget(player) == -1) { lwc.sendLocale(player, "protection.modes.dropxfer.status.off"); } else { - if (isPlayerDropTransferring(playerName)) { + if (isPlayerDropTransferring(player)) { lwc.sendLocale(player, "protection.modes.dropxfer.status.active"); } else { lwc.sendLocale(player, "protection.modes.dropxfer.status.inactive"); diff --git a/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java b/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java index ef14c3da7..abf81768a 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java @@ -18,13 +18,12 @@ package com.griefcraft.modules.modes; import com.griefcraft.lwc.LWC; +import com.griefcraft.model.LWCPlayer; +import com.griefcraft.model.Mode; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCCommandEvent; import com.griefcraft.scripting.event.LWCSendLocaleEvent; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.List; public class NoSpamModule extends JavaModule { @@ -42,37 +41,36 @@ public void onCommand(LWCCommandEvent event) { CommandSender sender = event.getSender(); String[] args = event.getArgs(); - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String mode = args[0].toLowerCase(); if (!mode.equals("nospam")) { return; } - List<String> modes = lwc.getMemoryDatabase().getModes(player.getName()); + if (!player.hasMode(mode)) { + Mode temp = new Mode(); + temp.setName(mode); + temp.setPlayer(player.getBukkitPlayer()); - if (!modes.contains(mode)) { - lwc.getMemoryDatabase().registerMode(player.getName(), mode); + player.enableMode(temp); lwc.sendLocale(player, "protection.modes.nospam.finalize"); } else { - lwc.getMemoryDatabase().unregisterMode(player.getName(), mode); + player.disableMode(player.getMode(mode)); lwc.sendLocale(player, "protection.modes.nospam.off"); } event.setCancelled(true); - return; } @Override public void onSendLocale(LWCSendLocaleEvent event) { LWC lwc = event.getLWC(); - Player player = event.getPlayer(); + LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); String locale = event.getLocale(); - List<String> modes = lwc.getMemoryDatabase().getModes(player.getName()); - // they don't intrigue us - if (!modes.contains("nospam")) { + if (!player.hasMode("nospam")) { return; } diff --git a/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java b/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java index 6d082be9a..cd91987ad 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java @@ -18,12 +18,11 @@ package com.griefcraft.modules.modes; import com.griefcraft.lwc.LWC; +import com.griefcraft.model.LWCPlayer; +import com.griefcraft.model.Mode; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCCommandEvent; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.List; public class PersistModule extends JavaModule { @@ -41,25 +40,26 @@ public void onCommand(LWCCommandEvent event) { CommandSender sender = event.getSender(); String[] args = event.getArgs(); - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String mode = args[0].toLowerCase(); if (!mode.equals("persist")) { return; } - List<String> modes = lwc.getMemoryDatabase().getModes(player.getName()); + if (!player.hasMode(mode)) { + Mode temp = new Mode(); + temp.setName(mode); + temp.setPlayer(player.getBukkitPlayer()); - if (!modes.contains(mode)) { - lwc.getMemoryDatabase().registerMode(player.getName(), mode); + player.enableMode(temp); lwc.sendLocale(player, "protection.modes.persist.finalize"); } else { - lwc.getMemoryDatabase().unregisterMode(player.getName(), mode); + player.disableMode(player.getMode(mode)); lwc.sendLocale(player, "protection.modes.persist.off"); } event.setCancelled(true); - return; } } diff --git a/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java b/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java index deed3ec5e..3a5e6e5fe 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java @@ -20,6 +20,7 @@ import com.griefcraft.lwc.LWC; import com.griefcraft.model.AccessRight; import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCBlockInteractEvent; @@ -46,11 +47,11 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { LWC lwc = event.getLWC(); Protection protection = event.getProtection(); - Player player = event.getPlayer(); + LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); event.setResult(Result.CANCEL); - if (lwc.canAdminProtection(player, protection)) { - Action action = lwc.getMemoryDatabase().getAction("modify", player.getName()); + if (lwc.canAdminProtection(player.getBukkitPlayer(), protection)) { + Action action = player.getAction("modify"); final String defaultEntities = action.getData(); String[] entities = new String[0]; @@ -172,10 +173,16 @@ public void onCommand(LWCCommandEvent event) { } String full = join(args, 0); - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); + + Action action = new Action(); + action.setName("modify"); + action.setPlayer(player); + action.setData(full); + + player.removeAllActions(); + player.addAction(action); - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); - lwc.getMemoryDatabase().registerAction("modify", player.getName(), full); lwc.sendLocale(sender, "protection.modify.finalize"); return; } diff --git a/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java b/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java index 7657f6176..f280e7379 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java @@ -20,6 +20,7 @@ import com.griefcraft.lwc.LWC; import com.griefcraft.model.AccessRight; import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.scripting.JavaModule; import com.griefcraft.scripting.event.LWCBlockInteractEvent; @@ -46,10 +47,10 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { LWC lwc = event.getLWC(); Protection protection = event.getProtection(); - Player player = event.getPlayer(); + LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); event.setResult(Result.CANCEL); - Action action = lwc.getMemoryDatabase().getAction("owners", player.getName()); + Action action = player.getAction("owners"); int accessPage = Integer.parseInt(action.getData()); /* @@ -142,7 +143,7 @@ public void onCommand(LWCCommandEvent event) { return; } - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); int page = 1; if (args.length > 0) { @@ -154,8 +155,14 @@ public void onCommand(LWCCommandEvent event) { } } - lwc.getMemoryDatabase().unregisterAllActions(player.getName()); - lwc.getMemoryDatabase().registerAction("owners", player.getName(), page + ""); + Action action = new Action(); + action.setName("owners"); + action.setPlayer(player); + action.setData(page + ""); + + player.removeAllActions(); + player.addAction(action); + lwc.sendLocale(sender, "protection.owners.finalize"); return; } diff --git a/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java b/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java index 5475424e5..139deca8f 100644 --- a/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java +++ b/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java @@ -18,6 +18,8 @@ package com.griefcraft.modules.unlock; import com.griefcraft.lwc.LWC; +import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.model.ProtectionTypes; import com.griefcraft.scripting.JavaModule; @@ -61,38 +63,35 @@ public void onCommand(LWCCommandEvent event) { return; } - Player player = (Player) sender; + LWCPlayer player = lwc.wrapPlayer(sender); String password = join(args, 0); password = encrypt(password); - if (!lwc.getMemoryDatabase().hasPendingUnlock(player.getName())) { + // see if they have the protection interaction action + Action action = player.getAction("interacted"); + + if (action == null) { player.sendMessage(Colors.Red + "Nothing selected. Open a locked protection first."); - return; } else { - int protectionId = lwc.getMemoryDatabase().getUnlockID(player.getName()); + Protection protection = action.getProtection(); - if (protectionId == -1) { + if (protection == null) { lwc.sendLocale(player, "protection.internalerror", "id", "unlock"); return; } - Protection entity = lwc.getPhysicalDatabase().loadProtection(protectionId); - - if (entity.getType() != ProtectionTypes.PASSWORD) { + if (protection.getType() != ProtectionTypes.PASSWORD) { lwc.sendLocale(player, "protection.unlock.notpassword"); return; } - if (entity.getData().equals(password)) { - lwc.getMemoryDatabase().unregisterUnlock(player.getName()); - lwc.getMemoryDatabase().registerPlayer(player.getName(), protectionId); + if (protection.getData().equals(password)) { + player.addAccessibleProtection(protection); lwc.sendLocale(player, "protection.unlock.password.valid"); } else { lwc.sendLocale(player, "protection.unlock.password.invalid"); } } - - return; } } diff --git a/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java b/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java index 475d235f5..e6251cc9a 100644 --- a/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java +++ b/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java @@ -18,6 +18,8 @@ package com.griefcraft.lwc; import com.griefcraft.bukkit.LWCSpoutPlugin; +import com.griefcraft.model.Action; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.model.ProtectionTypes; import com.griefcraft.scripting.JavaModule; @@ -104,9 +106,12 @@ public void onButtonClicked(ButtonClickEvent event) { Button button = event.getButton(); SpoutPlayer player = event.getPlayer(); LWC lwc = LWC.getInstance(); + LWCPlayer lwcPlayer = lwc.wrapPlayer(player); + + Action action = lwcPlayer.getAction("interacted"); // if they don't have an unlock req, why is the screen open? - if (!lwc.getMemoryDatabase().hasPendingUnlock(player.getName())) { + if (action == null) { player.getMainScreen().closePopup(); return; } @@ -117,24 +122,21 @@ public void onButtonClicked(ButtonClickEvent event) { // check their password String password = lwc.encrypt(textField.getText().trim()); - int protectionId = lwc.getMemoryDatabase().getUnlockID(player.getName()); + // load the protection they had clicked + Protection protection = action.getProtection(); - if (protectionId == -1) { + if (protection == null) { lwc.sendLocale(player, "protection.internalerror", "id", "unlock"); return; } - // load the protection they had clicked - Protection protection = lwc.getPhysicalDatabase().loadProtection(protectionId); - if (protection.getType() != ProtectionTypes.PASSWORD) { lwc.sendLocale(player, "protection.unlock.notpassword"); return; } if (protection.getData().equals(password)) { - lwc.getMemoryDatabase().unregisterUnlock(player.getName()); - lwc.getMemoryDatabase().registerPlayer(player.getName(), protectionId); + lwcPlayer.addAccessibleProtection(protection); player.getMainScreen().closePopup(); // open the chest that they clicked :P diff --git a/skel/doors.yml b/skel/doors.yml index c602913bc..4ce685a32 100644 --- a/skel/doors.yml +++ b/skel/doors.yml @@ -10,7 +10,7 @@ doors: # toggle: the door will just open if it's closed, or close if it's opened. Will not auto close. # openAndClose: the door will automatically close after <interval>. If it was already opened, it will NOT re-open. # - action: toggle + name: toggle - # The amount of seconds after opening a door for it to close. No effect if openAndClose action is not being used. + # The amount of seconds after opening a door for it to close. No effect if openAndClose name is not being used. interval: 3 \ No newline at end of file diff --git a/src/lang/lwc_cz.properties b/src/lang/lwc_cz.properties index b52246589..737f1fae4 100644 --- a/src/lang/lwc_cz.properties +++ b/src/lang/lwc_cz.properties @@ -45,7 +45,7 @@ protection.general.locked.password=\ %red%Musis napsat %gold%%cunlock% <heslo>%red% k odemknuti ! protection.general.locked.private=%green%%block% %white%->%red% objekt je uzamknut magickym klicem ! %white%:-) -# Pending action +# Pending name protection.general.pending=%red%Jiz mas nevyrizeny prikaz s LWC! ################## diff --git a/src/lang/lwc_da.properties b/src/lang/lwc_da.properties index 8bee5fd15..6e43e768c 100644 --- a/src/lang/lwc_da.properties +++ b/src/lang/lwc_da.properties @@ -44,7 +44,7 @@ protection.general.locked.password=\ %red%Skriv %gold%%cunlock% <Kodeord>%red% for at låse op. protection.general.locked.private=%red%Denne %block% er låst med en trylleformular -# Pending action +# Pending name protection.general.pending=%red%Du har allerede en ventende handling. ################## diff --git a/src/lang/lwc_de.properties b/src/lang/lwc_de.properties index 0faeb46e9..6eee83e52 100644 --- a/src/lang/lwc_de.properties +++ b/src/lang/lwc_de.properties @@ -45,7 +45,7 @@ protection.general.locked.password=\ %red%Schreibe %gold%%cunlock% <Passwort> %red%zum entriegeln. protection.general.locked.private=%red%Diese %block% ist abgeschlossen. -# Pending action +# Pending name protection.general.pending=%red%Du hast derzeit noch eine offene Anfrage. ################## diff --git a/src/lang/lwc_en.properties b/src/lang/lwc_en.properties index a9e491641..e641a3ba2 100644 --- a/src/lang/lwc_en.properties +++ b/src/lang/lwc_en.properties @@ -44,8 +44,8 @@ protection.general.locked.password=\ %red%Type %gold%%cunlock% <Password>%red% to unlock it. protection.general.locked.private=%red%This %block% is locked with a magical spell -# Pending action -protection.general.pending=%red%You already have a pending action. +# Pending name +protection.general.pending=%red%You already have a pending name. ################## ## Commands ## diff --git a/src/lang/lwc_es.properties b/src/lang/lwc_es.properties index 00bd24fbc..f37e00bf5 100644 --- a/src/lang/lwc_es.properties +++ b/src/lang/lwc_es.properties @@ -35,7 +35,7 @@ protection.general.locked.password=\ %red%Escribe %gold%%cunlock% <Password>%red% para desbloquearlo. protection.general.locked.private=%red%Este %block% esta protegido con un hechizo magico. -# Pending action +# Pending name protection.general.pending=%red%Ya tienes una accion pendiente. ################## diff --git a/src/lang/lwc_fr.properties b/src/lang/lwc_fr.properties index be4addd2b..3a78963f8 100644 --- a/src/lang/lwc_fr.properties +++ b/src/lang/lwc_fr.properties @@ -31,8 +31,8 @@ protection.general.locked.password=\ %red%Veuillez taper %gold%%cunlock% <Password>%red% pour le/la déverrouiller. protection.general.locked.private=%red%Ce/Cette %block% est bloqué par un sort magique. -# Pending action -protection.general.pending=%red%Vous avez déjà une action en cours. +# Pending name +protection.general.pending=%red%Vous avez déjà une name en cours. ################## ## Commands ## diff --git a/src/lang/lwc_nl.properties b/src/lang/lwc_nl.properties index 813313d55..d7e779b01 100644 --- a/src/lang/lwc_nl.properties +++ b/src/lang/lwc_nl.properties @@ -35,7 +35,7 @@ protection.general.locked.password=\ %red%Typ %gold%%cunlock% <Wachtwoord>%red% om er toegang tot te krijgen. protection.general.locked.private=%red%deze %block% is beveiligd met een magische spreuk. -# Pending action +# Pending name protection.general.pending=%red%Er is al een actie bezig. ################## diff --git a/src/lang/lwc_pl.properties b/src/lang/lwc_pl.properties index e8657902c..d44c07529 100644 --- a/src/lang/lwc_pl.properties +++ b/src/lang/lwc_pl.properties @@ -44,7 +44,7 @@ protection.general.locked.password=\ %gold%%cunlock% <haslo>%red%, aby odblokowac. protection.general.locked.private=%red%Ten %block% jest zablokowany magicznym zakleciem. -# Pending action +# Pending name protection.general.pending=%red%Juz wykonujesz akcje. ################## diff --git a/src/lang/lwc_ru.properties b/src/lang/lwc_ru.properties index f9243536c..b312d7dc1 100644 --- a/src/lang/lwc_ru.properties +++ b/src/lang/lwc_ru.properties @@ -43,7 +43,7 @@ protection.general.locked.password=\ %red%Введите %gold%%cunlock% <Пароль>%red% чтобы открыть его. protection.general.locked.private=%red%%block% защищён магией. -# Pending action +# Pending name protection.general.pending=%red%Вы уже выполняете это действие ################## diff --git a/src/lang/lwc_sv.properties b/src/lang/lwc_sv.properties index 7c025c889..d19e1f4d4 100644 --- a/src/lang/lwc_sv.properties +++ b/src/lang/lwc_sv.properties @@ -44,7 +44,7 @@ protection.general.locked.password=\ %red%Skriv %gold%%cunlock% <Lösenord>%red% för att låsa upp den. protection.general.locked.private=%red%Detta %block% är låst med en trollformel -# Pending action +# Pending name protection.general.pending=%red%Du har redan et pågående utspel. ################## diff --git a/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java b/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java index de6a125b9..2fd2c88a7 100644 --- a/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java +++ b/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java @@ -19,6 +19,7 @@ import com.griefcraft.lwc.LWC; import com.griefcraft.lwc.LWCPlugin; +import com.griefcraft.model.LWCPlayer; import com.griefcraft.model.Protection; import com.griefcraft.scripting.Module; import com.griefcraft.scripting.Module.Result; @@ -43,6 +44,7 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; +import java.util.ArrayList; import java.util.List; public class LWCPlayerListener extends PlayerListener { @@ -103,6 +105,7 @@ public void onPlayerInteract(PlayerInteractEvent event) { LWC lwc = plugin.getLWC(); Player player = event.getPlayer(); + LWCPlayer lwcPlayer = lwc.wrapPlayer(player); Block clickedBlock = event.getClickedBlock(); Location location = clickedBlock.getLocation(); @@ -122,12 +125,22 @@ public void onPlayerInteract(PlayerInteractEvent event) { } try { - List<String> actions = lwc.getMemoryDatabase().getActions(player.getName()); + List<String> actions = new ArrayList<String>(lwcPlayer.getActionNames()); Protection protection = lwc.findProtection(block); Module.Result result = Module.Result.CANCEL; boolean canAccess = lwc.canAccessProtection(player, protection); boolean canAdmin = lwc.canAdminProtection(player, protection); + // register in an action what protection they interacted with (if applicable.) + if (protection != null) { + com.griefcraft.model.Action action = new com.griefcraft.model.Action(); + action.setName("interacted"); + action.setPlayer(lwcPlayer); + action.setProtection(protection); + + lwcPlayer.addAction(action); + } + if (event.getAction() == Action.LEFT_CLICK_BLOCK) { boolean ignoreLeftClick = Boolean.parseBoolean(lwc.resolveProtectionConfiguration(material, "ignoreLeftClick")); @@ -188,14 +201,10 @@ public void onPlayerQuit(PlayerQuitEvent event) { return; } - LWC lwc = plugin.getLWC(); - String player = event.getPlayer().getName(); - - lwc.getMemoryDatabase().unregisterPlayer(player); - lwc.getMemoryDatabase().unregisterUnlock(player); - lwc.getMemoryDatabase().unregisterPendingLock(player); - lwc.getMemoryDatabase().unregisterAllActions(player); - lwc.getMemoryDatabase().unregisterAllModes(player); + LWCPlayer player = LWC.getInstance().wrapPlayer(event.getPlayer()); + player.removeAllAccessibleProtections(); + player.removeAllActions(); + player.disableAllModes(); } } diff --git a/src/main/java/com/griefcraft/lwc/LWC.java b/src/main/java/com/griefcraft/lwc/LWC.java index 1081b9642..595656229 100644 --- a/src/main/java/com/griefcraft/lwc/LWC.java +++ b/src/main/java/com/griefcraft/lwc/LWC.java @@ -66,7 +66,6 @@ import com.griefcraft.scripting.ModuleLoader.Event; import com.griefcraft.scripting.event.LWCSendLocaleEvent; import com.griefcraft.sql.Database; -import com.griefcraft.sql.MemDB; import com.griefcraft.sql.PhysDB; import com.griefcraft.util.Colors; import com.griefcraft.util.Performance; @@ -142,11 +141,6 @@ public class LWC { */ private CacheSet caches; - /** - * Memory database instance - */ - private MemDB memoryDatabase; - /** * Physical database instance */ @@ -205,11 +199,19 @@ public LWC(LWCPlugin plugin) { /** * Create an LWCPlayer object for a player * - * @param player + * @param sender * @return */ - public LWCPlayer wrapPlayer(Player player) { - return new LWCPlayer(this, player); + public LWCPlayer wrapPlayer(CommandSender sender) { + if (sender instanceof LWCPlayer) { + return (LWCPlayer) sender; + } + + if (!(sender instanceof Player)) { + return null; + } + + return LWCPlayer.getPlayer((Player) sender); } /** @@ -254,11 +256,17 @@ public CacheSet getCaches() { /** * Remove all modes if the player is not in persistent mode * - * @param player + * @param sender */ - public void removeModes(Player player) { - if (notInPersistentMode(player.getName())) { - memoryDatabase.unregisterAllActions(player.getName()); + public void removeModes(CommandSender sender) { + if (sender instanceof Player) { + Player bPlayer = (Player) sender; + + if (notInPersistentMode(bPlayer.getName())) { + wrapPlayer(bPlayer).getActions().clear(); + } + } else if (sender instanceof LWCPlayer) { + removeModes(((LWCPlayer) sender).getBukkitPlayer()); } } @@ -369,7 +377,7 @@ public boolean canAccessProtection(Player player, Protection protection) { return true; case ProtectionTypes.PASSWORD: - return memoryDatabase.hasAccess(player.getName(), protection); + return wrapPlayer(player).getAccessibleProtections().contains(protection); case ProtectionTypes.PRIVATE: if (playerName.equalsIgnoreCase(protection.getOwner())) { @@ -437,7 +445,7 @@ public boolean canAdminProtection(Player player, Protection protection) { return player.getName().equalsIgnoreCase(protection.getOwner()); case ProtectionTypes.PASSWORD: - return player.getName().equalsIgnoreCase(protection.getOwner()) && memoryDatabase.hasAccess(player.getName(), protection); + return player.getName().equalsIgnoreCase(protection.getOwner()) && wrapPlayer(player).getAccessibleProtections().contains(protection); case ProtectionTypes.PRIVATE: if (playerName.equalsIgnoreCase(protection.getOwner())) { @@ -483,12 +491,7 @@ public void destruct() { physicalDatabase.dispose(); } - if (memoryDatabase != null) { - memoryDatabase.dispose(); - } - physicalDatabase = null; - memoryDatabase = null; } /** @@ -576,8 +579,7 @@ public boolean enforceAccess(Player player, Block block) { switch (protection.getType()) { case ProtectionTypes.PASSWORD: if (!hasAccess) { - getMemoryDatabase().unregisterUnlock(player.getName()); - getMemoryDatabase().registerUnlock(player.getName(), protection.getId()); + wrapPlayer(player).addAccessibleProtection(protection); sendLocale(player, "protection.general.locked.password", "block", materialToString(block)); } @@ -778,13 +780,6 @@ public String getLocale(String key, Object... args) { return value; } - /** - * @return memory database object - */ - public MemDB getMemoryDatabase() { - return memoryDatabase; - } - /** * @return the Permissions handler */ @@ -1060,7 +1055,6 @@ public void load() { Performance.init(); physicalDatabase = new PhysDB(); - memoryDatabase = new MemDB(); updateThread = new UpdateThread(this); // Permissions init @@ -1114,10 +1108,7 @@ public void load() { log("Loading " + Database.DefaultType); try { physicalDatabase.connect(); - memoryDatabase.connect(); - physicalDatabase.load(); - memoryDatabase.load(); log("Using: " + StringUtils.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { @@ -1257,7 +1248,7 @@ public ItemStack[] mergeInventories(List<Block> blocks) { * @return true if the player is NOT in persistent mode */ public boolean notInPersistentMode(String player) { - return !memoryDatabase.hasMode(player, "persist"); + return !wrapPlayer(Bukkit.getServer().getPlayer(player)).hasMode("persist"); } /** diff --git a/src/main/java/com/griefcraft/model/Action.java b/src/main/java/com/griefcraft/model/Action.java index 5ea7d69f0..e5b68e884 100644 --- a/src/main/java/com/griefcraft/model/Action.java +++ b/src/main/java/com/griefcraft/model/Action.java @@ -19,24 +19,23 @@ public class Action { - public int id; - private String action; - private int protectionId; + private String name; + private Protection protection; private String data; - private String player; + private LWCPlayer player; /** - * @return the action + * @return the name */ - public String getAction() { - return action; + public String getName() { + return name; } /** - * @return the protectionId + * @return the Protection associated with this action */ - public int getProtectionId() { - return protectionId; + public Protection getProtection() { + return protection; } /** @@ -46,32 +45,25 @@ public String getData() { return data; } - /** - * @return the id - */ - public int getId() { - return id; - } - /** * @return the player */ - public String getPlayer() { + public LWCPlayer getPlayer() { return player; } /** - * @param action the action to set + * @param name the name to set */ - public void setAction(String action) { - this.action = action; + public void setName(String name) { + this.name = name; } /** - * @param protectionId the protectionId to set + * @param protection the Protection to set */ - public void setProtectionId(int protectionId) { - this.protectionId = protectionId; + public void setProtection(Protection protection) { + this.protection = protection; } /** @@ -81,17 +73,10 @@ public void setData(String data) { this.data = data; } - /** - * @param id the id to set - */ - public void setId(int id) { - this.id = id; - } - /** * @param player the player to set */ - public void setPlayer(String player) { + public void setPlayer(LWCPlayer player) { this.player = player; } diff --git a/src/main/java/com/griefcraft/model/LWCPlayer.java b/src/main/java/com/griefcraft/model/LWCPlayer.java index e0ad1e771..bc93c9aaa 100644 --- a/src/main/java/com/griefcraft/model/LWCPlayer.java +++ b/src/main/java/com/griefcraft/model/LWCPlayer.java @@ -18,21 +18,269 @@ package com.griefcraft.model; import com.griefcraft.lwc.LWC; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.Plugin; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; -public class LWCPlayer { +public class LWCPlayer implements CommandSender { + /** + * The LWC instance + */ private LWC lwc; + + /** + * The player instance + */ private Player player; + /** + * Cache of LWCPlayer objects + */ + private final static Map<Player, LWCPlayer> players = new HashMap<Player, LWCPlayer>(); + + /** + * The modes bound to all players + */ + private final static Map<LWCPlayer, Set<Mode>> modes = Collections.synchronizedMap(new HashMap<LWCPlayer, Set<Mode>>()); + + /** + * The actions bound to all players + */ + private final static Map<LWCPlayer, Set<Action>> actions = Collections.synchronizedMap(new HashMap<LWCPlayer, Set<Action>>()); + + /** + * Map of protections a player can temporarily access + */ + private final static Map<LWCPlayer, Set<Protection>> accessibleProtections = Collections.synchronizedMap(new HashMap<LWCPlayer, Set<Protection>>()); + public LWCPlayer(LWC lwc, Player player) { this.lwc = lwc; this.player = player; } + /** + * Get the LWCPlayer object from a Player object + * + * @param player + * @return + */ + public static LWCPlayer getPlayer(Player player) { + if (!players.containsKey(player)) { + players.put(player, new LWCPlayer(LWC.getInstance(), player)); + } + + return players.get(player); + } + + /** + * @return the Bukkit Player object + */ + public Player getBukkitPlayer() { + return player; + } + + /** + * @return the player's name + */ + public String getName() { + return player.getName(); + } + + /** + * Enable a mode on the player + * + * @param mode + * @return + */ + public boolean enableMode(Mode mode) { + return getModes().add(mode); + } + + /** + * Disable a mode on the player + * + * @param mode + * @return + */ + public boolean disableMode(Mode mode) { + return getModes().remove(mode); + } + + /** + * Disable all modes enabled by the player + * + * @return + */ + public void disableAllModes() { + getModes().clear(); + } + + /** + * Check if the player has an action + * + * @param name + * @return + */ + public boolean hasAction(String name) { + return getAction(name) != null; + } + + /** + * Get the action represented by the name + * + * @param name + * @return + */ + public Action getAction(String name) { + for (Action action : getActions()) { + if (action.getName().equals(name)) { + return action; + } + } + + return null; + } + + /** + * Add an action + * + * @param action + * @return + */ + public boolean addAction(Action action) { + return getActions().add(action); + } + + /** + * Remove an action + * + * @param action + * @return + */ + public boolean removeAction(Action action) { + return getActions().remove(action); + } + + /** + * Remove all actions + */ + public void removeAllActions() { + getActions().clear(); + } + + /** + * Retrieve a Mode object for a player + * + * @param name + * @return + */ + public Mode getMode(String name) { + for (Mode mode : getModes()) { + if (mode.getName().equals(name)) { + return mode; + } + } + + return null; + } + + /** + * Check if the player has the given mode + * + * @param name + * @return + */ + public boolean hasMode(String name) { + return getMode(name) != null; + } + + /** + * @return the Set of modes the player has activated + */ + public Set<Mode> getModes() { + if (!modes.containsKey(this)) { + modes.put(this, new HashSet<Mode>()); + } + + return modes.get(this); + } + + /** + * @return the Set of actions the player has + */ + public Set<Action> getActions() { + if (!actions.containsKey(this)) { + actions.put(this, new HashSet<Action>()); + } + + return actions.get(this); + } + + /** + * @return a Set containing all of the action names + */ + public Set<String> getActionNames() { + Set<Action> actions = getActions(); + Set<String> names = new HashSet<String>(actions.size()); + + for (Action action : actions) { + names.add(action.getName()); + } + + return names; + } + + /** + * @return the set of protections the player can temporarily access + */ + public Set<Protection> getAccessibleProtections() { + if (!accessibleProtections.containsKey(this)) { + accessibleProtections.put(this, new HashSet<Protection>()); + } + + return accessibleProtections.get(this); + } + + /** + * Add an accessible protection for the player + * + * @param protection + * @return + */ + public boolean addAccessibleProtection(Protection protection) { + return getAccessibleProtections().add(protection); + } + + /** + * Remove an accessible protection from the player + * + * @param protection + * @return + */ + public boolean removeAccessibleProtection(Protection protection) { + return getAccessibleProtections().remove(protection); + } + + /** + * Remove all accessible protections + */ + public void removeAllAccessibleProtections() { + getAccessibleProtections().clear(); + } + /** * Create a History object that is attached to this protection * @@ -84,4 +332,63 @@ public List<History> getRelatedHistory(History.Type type) { return related; } + public void sendMessage(String s) { + player.sendMessage(s); + } + + public Server getServer() { + return player.getServer(); + } + + public boolean isPermissionSet(String s) { + return player.isPermissionSet(s); + } + + public boolean isPermissionSet(Permission permission) { + return player.isPermissionSet(permission); + } + + public boolean hasPermission(String s) { + return player.hasPermission(s); + } + + public boolean hasPermission(Permission permission) { + return player.hasPermission(permission); + } + + public PermissionAttachment addAttachment(Plugin plugin, String s, boolean b) { + return player.addAttachment(plugin, s, b); + } + + public PermissionAttachment addAttachment(Plugin plugin) { + return player.addAttachment(plugin); + } + + public PermissionAttachment addAttachment(Plugin plugin, String s, boolean b, int i) { + return player.addAttachment(plugin, s, b, i); + } + + public PermissionAttachment addAttachment(Plugin plugin, int i) { + return player.addAttachment(plugin, i); + } + + public void removeAttachment(PermissionAttachment permissionAttachment) { + player.removeAttachment(permissionAttachment); + } + + public void recalculatePermissions() { + player.recalculatePermissions(); + } + + public Set<PermissionAttachmentInfo> getEffectivePermissions() { + return player.getEffectivePermissions(); + } + + public boolean isOp() { + return player.isOp(); + } + + public void setOp(boolean b) { + player.setOp(b); + } } diff --git a/src/main/java/com/griefcraft/model/Mode.java b/src/main/java/com/griefcraft/model/Mode.java new file mode 100644 index 000000000..75a5450cd --- /dev/null +++ b/src/main/java/com/griefcraft/model/Mode.java @@ -0,0 +1,63 @@ +/** + * This file is part of LWC (https://github.com/Hidendra/LWC) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package com.griefcraft.model; + +import org.bukkit.entity.Player; + +public class Mode { + + /** + * The name of this mode + */ + private String name; + + /** + * The player this mode belongs to + */ + private Player player; + + /** + * Mode data + */ + private String data; + + public String getName() { + return name; + } + + public Player getPlayer() { + return player; + } + + public String getData() { + return data; + } + + public void setName(String name) { + this.name = name; + } + + public void setPlayer(Player player) { + this.player = player; + } + + public void setData(String data) { + this.data = data; + } + +} diff --git a/src/main/java/com/griefcraft/sql/MemDB.java b/src/main/java/com/griefcraft/sql/MemDB.java deleted file mode 100755 index b92531459..000000000 --- a/src/main/java/com/griefcraft/sql/MemDB.java +++ /dev/null @@ -1,831 +0,0 @@ -/** - * This file is part of LWC (https://github.com/Hidendra/LWC) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -package com.griefcraft.sql; - -import com.griefcraft.model.Action; -import com.griefcraft.model.Protection; -import com.griefcraft.util.Performance; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -public class MemDB extends Database { - - public MemDB() { - super(); - } - - public MemDB(Type currentType) { - super(currentType); - } - - @Override - protected void postPrepare() { - Performance.addMemDBQuery(); - } - - public Action getAction(String action, String player) { - try { - PreparedStatement statement = prepare("SELECT * FROM " + prefix + "actions WHERE player = ? AND action = ?"); - statement.setString(1, player); - statement.setString(2, action); - - ResultSet set = statement.executeQuery(); - - if (set.next()) { - final int id = set.getInt("id"); - final String actionString = set.getString("action"); - final String playerString = set.getString("player"); - final int chestID = set.getInt("chest"); - final String data = set.getString("data"); - - final Action act = new Action(); - act.setId(id); - act.setAction(actionString); - act.setPlayer(playerString); - act.setProtectionId(chestID); - act.setData(data); - - return act; - } - - - } catch (final Exception e) { - printException(e); - } - - return null; - } - - /** - * Get the chest ID associated with a player's unlock request - * - * @param player the player to lookup - * @return the chest ID - */ - public int getActionID(String action, String player) { - try { - int chestID = -1; - - PreparedStatement statement = prepare("SELECT chest FROM " + prefix + "actions WHERE action = ? AND player = ?"); - statement.setString(1, action); - statement.setString(2, player); - - final ResultSet set = statement.executeQuery(); - - while (set.next()) { - chestID = set.getInt("chest"); - } - - - return chestID; - } catch (final Exception e) { - printException(e); - } - - return -1; - } - - /** - * Get all the active actions for a player - * - * @param player the player to get actions for - * @return the List<String> of actions - */ - public List<String> getActions(String player) { - final List<String> actions = new ArrayList<String>(); - - try { - PreparedStatement statement = prepare("SELECT action FROM " + prefix + "actions WHERE player = ?"); - statement.setString(1, player); - - final ResultSet set = statement.executeQuery(); - - while (set.next()) { - final String action = set.getString("action"); - - actions.add(action); - } - - } catch (final Exception e) { - printException(e); - } - - return actions; - } - - /** - * @return the path where the database file should be saved - */ - @Override - public String getDatabasePath() { - // if we're using mysql, just open another connection - if (currentType == Type.MySQL) { - return super.getDatabasePath(); - } - - return ":memory:"; - } - - /** - * Get the password submitted for a pending chest lock - * - * @param player the player to lookup - * @return the password for the pending lock - */ - public String getLockPassword(String player) { - try { - String password = ""; - - PreparedStatement statement = prepare("SELECT password FROM " + prefix + "locks WHERE player = ?"); - statement.setString(1, player); - - final ResultSet set = statement.executeQuery(); - - while (set.next()) { - password = set.getString("password"); - } - - - return password; - } catch (final Exception e) { - printException(e); - } - - return null; - } - - /** - * Get the mode data for a player's mode - * - * @param player - * @param mode - * @return - */ - public String getModeData(String player, String mode) { - String ret = null; - try { - PreparedStatement statement = prepare("SELECT data FROM " + prefix + "modes WHERE player = ? AND mode = ?"); - statement.setString(1, player); - statement.setString(2, mode); - - final ResultSet set = statement.executeQuery(); - if (set.next()) { - ret = set.getString("data"); - } - - - } catch (final Exception e) { - printException(e); - } - return ret; - } - - /** - * Get the modes a player has activated - * - * @param player the player to get - * @return the List of modes the player is using - */ - public List<String> getModes(String player) { - final List<String> modes = new ArrayList<String>(); - - try { - PreparedStatement statement = prepare("SELECT * FROM " + prefix + "modes WHERE player = ?"); - statement.setString(1, player); - - final ResultSet set = statement.executeQuery(); - - while (set.next()) { - final String mode = set.getString("mode"); - - modes.add(mode); - } - - - } catch (final Exception e) { - printException(e); - } - - return modes; - } - - /** - * Get all of the users "logged in" to a chest - * - * @param chestID the chest ID to look at - * @return - */ - public List<String> getSessionUsers(int chestID) { - final List<String> sessionUsers = new ArrayList<String>(); - - try { - PreparedStatement statement = prepare("SELECT player FROM " + prefix + "sessions WHERE chest = ?"); - statement.setInt(1, chestID); - - final ResultSet set = statement.executeQuery(); - - while (set.next()) { - final String player = set.getString("player"); - - sessionUsers.add(player); - } - - } catch (final Exception e) { - printException(e); - } - - return sessionUsers; - } - - /** - * Get the chest ID associated with a player's unlock request - * - * @param player the player to lookup - * @return the chest ID - */ - public int getUnlockID(String player) { - return getActionID("unlock", player); - } - - /** - * Check if a player has an active chest session - * - * @param player the player to check - * @param chestID the chest ID to check - * @return true if the player has access - */ - public boolean hasAccess(String player, int chestID) { - try { - PreparedStatement statement = prepare("SELECT player FROM " + prefix + "sessions WHERE chest = ?"); - statement.setInt(1, chestID); - - final ResultSet set = statement.executeQuery(); - - while (set.next()) { - final String player2 = set.getString("player"); - - if (player.equals(player2)) { - - - return true; - } - } - - - } catch (final Exception e) { - printException(e); - } - - return false; - } - - /** - * Check if a player has an active chest session - * - * @param player the player to check - * @param chest the chest to check - * @return true if the player has access - */ - public boolean hasAccess(String player, Protection chest) { - return chest == null || hasAccess(player, chest.getId()); - - } - - /** - * Return if a player has the mode - * - * @param player the player to check - * @param mode the mode to check - */ - public boolean hasMode(String player, String mode) { - List<String> modes = getModes(player); - - return modes.size() > 0 && modes.contains(mode); - } - - /** - * Check if a player has a pending action - * - * @param player the player to check - * @param action the action to check - * @return true if they have a record - */ - public boolean hasPendingAction(String action, String player) { - return getAction(action, player) != null; - } - - /** - * Check if a player has a pending chest request - * - * @param player The player to check - * @return true if the player has a pending chest request - */ - public boolean hasPendingChest(String player) { - try { - PreparedStatement statement = prepare("SELECT id FROM " + prefix + "locks WHERE player = ?"); - statement.setString(1, player); - - ResultSet set = statement.executeQuery(); - - if (set.next()) { - set.close(); - return true; - } - - set.close(); - } catch (final Exception e) { - printException(e); - } - - return false; - } - - /** - * Check if a player has a pending unlock request - * - * @param player the player to check - * @return true if the player has a pending unlock request - */ - public boolean hasPendingUnlock(String player) { - return getUnlockID(player) != -1; - } - - /** - * create the in-memory table which hold sessions, users that have activated a chest. Not needed past a restart, so no need for extra disk i/o - */ - @Override - public void load() { - if (loaded) { - return; - } - - try { - // reusable column - Column column; - - Table sessions = new Table(this, "sessions"); - sessions.setMemory(true); - - { - column = new Column("id"); - column.setType("INTEGER"); - column.setPrimary(true); - sessions.add(column); - - column = new Column("player"); - column.setType("VARCHAR(255)"); - sessions.add(column); - - column = new Column("chest"); - column.setType("INTEGER"); - sessions.add(column); - } - - Table locks = new Table(this, "locks"); - locks.setMemory(true); - - { - column = new Column("id"); - column.setType("INTEGER"); - column.setPrimary(true); - locks.add(column); - - column = new Column("player"); - column.setType("VARCHAR(255)"); - locks.add(column); - - column = new Column("password"); - column.setType("VARCHAR(100)"); - locks.add(column); - } - - Table actions = new Table(this, "actions"); - actions.setMemory(true); - - { - column = new Column("id"); - column.setType("INTEGER"); - column.setPrimary(true); - actions.add(column); - - column = new Column("action"); - column.setType("VARCHAR(255)"); - actions.add(column); - - column = new Column("player"); - column.setType("VARCHAR(255)"); - actions.add(column); - - column = new Column("chest"); - column.setType("INTEGER"); - actions.add(column); - - column = new Column("data"); - column.setType("VARCHAR(255)"); - actions.add(column); - } - - Table modes = new Table(this, "modes"); - modes.setMemory(true); - - { - column = new Column("id"); - column.setType("INTEGER"); - column.setPrimary(true); - modes.add(column); - - column = new Column("player"); - column.setType("VARCHAR(255)"); - modes.add(column); - - column = new Column("mode"); - column.setType("VARCHAR(255)"); - modes.add(column); - - column = new Column("data"); - column.setType("VARCHAR(255)"); - modes.add(column); - } - - // now create all of the tables - sessions.execute(); - locks.execute(); - actions.execute(); - modes.execute(); - } catch (final Exception e) { - printException(e); - } - - loaded = true; - } - - /** - * @return the number of pending chest locks - */ - public int pendingCount() { - int count = 0; - - try { - Statement statement = connection.createStatement(); - final ResultSet set = statement.executeQuery("SELECT id FROM " + prefix + "locks"); - - while (set.next()) { - count++; - } - - statement.close(); - - } catch (final Exception e) { - printException(e); - } - - return count; - } - - /** - * Register a pending chest unlock, for when the player does /unlock <pass> - * - * @param action - * @param player - */ - public void registerAction(String action, String player) { - try { - /* - * We only want 1 action per player, no matter what! - */ - unregisterAction(action, player); - - PreparedStatement statement = prepare("INSERT INTO " + prefix + "actions (action, player, chest) VALUES (?, ?, ?)"); - statement.setString(1, action); - statement.setString(2, player); - statement.setInt(3, -1); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Register a pending chest unlock, for when the player does /unlock <pass> - * - * @param player the player to register - * @param chestID the chestID to unlock - */ - public void registerAction(String action, String player, int chestID) { - try { - /* - * We only want 1 action per player, no matter what! - */ - unregisterAction(action, player); - - PreparedStatement statement = prepare("INSERT INTO " + prefix + "actions (action, player, chest) VALUES (?, ?, ?)"); - statement.setString(1, action); - statement.setString(2, player); - statement.setInt(3, chestID); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Register an action, used for various actions (stating the obvious here) - * - * @param player the player to register - * @param data data - */ - public void registerAction(String action, String player, String data) { - try { - /* - * We only want 1 action per player, no matter what! - */ - unregisterAction(action, player); - - PreparedStatement statement = prepare("INSERT INTO " + prefix + "actions (action, player, data) VALUES (?, ?, ?)"); - statement.setString(1, action); - statement.setString(2, player); - statement.setString(3, data); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Register a mode to a player (temporary) - * - * @param player the player to register the mode to - * @param mode the mode to register - */ - public void registerMode(String player, String mode) { - try { - PreparedStatement statement = prepare("INSERT INTO " + prefix + "modes (player, mode) VALUES (?, ?)"); - statement.setString(1, player); - statement.setString(2, mode); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Register a mode with data to a player (temporary) - * - * @param player the player to register the mode to - * @param mode the mode to register - * @param data additional data - */ - public void registerMode(String player, String mode, String data) { - try { - PreparedStatement statement = prepare("INSERT INTO " + prefix + "modes (player, mode, data) VALUES (?, ?, ?)"); - statement.setString(1, player); - statement.setString(2, mode); - statement.setString(3, data); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Register a pending lock request to a player - * - * @param player the player to assign the chest to - * @param password the password to register with - */ - public void registerPendingLock(String player, String password) { - try { - PreparedStatement statement = prepare("INSERT INTO " + prefix + "locks (player, password) VALUES (?, ?)"); - statement.setString(1, player); - statement.setString(2, password); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Add a player to be allowed to access a chest - * - * @param player the player to add - * @param chestID the chest ID to allow them to access - */ - public void registerPlayer(String player, int chestID) { - try { - PreparedStatement statement = prepare("INSERT INTO " + prefix + "sessions (player, chest) VALUES(?, ?)"); - statement.setString(1, player); - statement.setInt(2, chestID); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Register a pending chest unlock, for when the player does /unlock <pass> - * - * @param player the player to register - * @param chestID the chestID to unlock - */ - public void registerUnlock(String player, int chestID) { - registerAction("unlock", player, chestID); - } - - /** - * @return the number of active session - */ - public int sessionCount() { - int count = 0; - - try { - Statement statement = connection.createStatement(); - final ResultSet set = statement.executeQuery("SELECT id FROM " + prefix + "sessions"); - - while (set.next()) { - count++; - } - - statement.close(); - - } catch (final Exception e) { - printException(e); - } - - return count; - } - - /** - * Unregister a pending chest unlock - * - * @param player the player to unregister - */ - public void unregisterAction(String action, String player) { - try { - PreparedStatement statement = prepare("DELETE FROM " + prefix + "actions WHERE action = ? AND player = ?"); - statement.setString(1, action); - statement.setString(2, player); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Unregister all of the actions for a player - * - * @param player the player to unregister - */ - public void unregisterAllActions(String player) { - try { - PreparedStatement statement = prepare("DELETE FROM " + prefix + "actions WHERE player = ?"); - statement.setString(1, player); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Remove all the pending chest requests - */ - public void unregisterAllChests() { - try { - Statement statement = connection.createStatement(); - statement.executeUpdate("DELETE FROM " + prefix + "locks"); - - statement.close(); - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Unregister all of the modes FROM " + prefix + "a player - * - * @param player the player to unregister all modes from - */ - public void unregisterAllModes(String player) { - try { - PreparedStatement statement = prepare("DELETE FROM " + prefix + "modes WHERE player = ?"); - statement.setString(1, player); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Unregister a mode FROM " + prefix + "a player - * - * @param player the player to register the mode to - * @param mode the mode to unregister - */ - public void unregisterMode(String player, String mode) { - try { - PreparedStatement statement = prepare("DELETE FROM " + prefix + "modes WHERE player = ? AND mode = ?"); - statement.setString(1, player); - statement.setString(2, mode); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Remove a pending lock request FROM " + prefix + "a player - * - * @param player the player to remove - */ - public void unregisterPendingLock(String player) { - try { - PreparedStatement statement = prepare("DELETE FROM " + prefix + "locks WHERE player = ?"); - statement.setString(1, player); - - statement.executeUpdate(); - - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Remove a player FROM " + prefix + "any sessions - * - * @param player the player to remove - */ - public void unregisterPlayer(String player) { - try { - PreparedStatement statement = prepare("DELETE FROM " + prefix + "sessions WHERE player = ?"); - statement.setString(1, player); - - statement.executeUpdate(); - - } catch (final Exception e) { - printException(e); - } - } - - /** - * Unregister a pending chest unlock - * - * @param player the player to unregister - */ - public void unregisterUnlock(String player) { - unregisterAction("unlock", player); - } - -}
b6096079c17488b1232f7db942c529c7eb5f9843
ReactiveX-RxJava
Unlock in finally block--
c
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java b/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java index fdd6e844ad..14c9612e07 100644 --- a/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java +++ b/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java @@ -63,25 +63,24 @@ public void onNext(T t) { } while (!state.compareAndSet(current, newState)); if (newState.shouldProcess()) { - if (newState == State.PROCESS_SELF) { - s.onNext(t); - - // finish processing to let this thread move on - do { - current = state.get(); - newState = current.finishProcessing(1); - } while (!state.compareAndSet(current, newState)); - } else { - // drain queue - Object[] items = newState.queue; - for (int i = 0; i < items.length; i++) { - s.onNext((T) items[i]); + int numItemsProcessed = 0; + try { + if (newState == State.PROCESS_SELF) { + s.onNext(t); + numItemsProcessed++; + } else { + // drain queue + Object[] items = newState.queue; + for (int i = 0; i < items.length; i++) { + s.onNext((T) items[i]); + numItemsProcessed++; + } } - + } finally { // finish processing to let this thread move on do { current = state.get(); - newState = current.finishProcessing(items.length); + newState = current.finishProcessing(numItemsProcessed); } while (!state.compareAndSet(current, newState)); } }
391e4b4c4ce7d9be1c0051614b970c85cce91c9f
restlet-framework-java
- Fixed plugin descriptors for some extensions.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/build.number b/build.number index 7a31427663..43097911f6 100644 --- a/build.number +++ b/build.number @@ -1,3 +1,3 @@ #Build Number for ANT. Do not edit! -#Sun Oct 15 18:28:20 CEST 2006 -build.number=340 +#Mon Oct 16 14:37:01 CEST 2006 +build.number=341 diff --git a/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF index 3a3d86e53f..e79eac8b14 100644 --- a/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF +++ b/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF @@ -8,8 +8,8 @@ Bundle-Localization: plugin Require-Bundle: org.restlet, com.noelios.restlet, com.noelios.restlet.ext.net, - com.noelios.restlet.ext.jetty6;resolution:=optional, com.noelios.restlet.ext.simple;resolution:=optional, + com.noelios.restlet.ext.jetty6;resolution:=optional, com.noelios.restlet.ext.asyncweb;resolution:=optional, org.apache.mina;resolution:=optional, org.apache.commons.logging;resolution:=optional, diff --git a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java index 4ef292b45c..2bd921295f 100644 --- a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java +++ b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java @@ -23,7 +23,6 @@ package com.noelios.restlet.example.misc; import org.restlet.Container; -import org.restlet.Context; import org.restlet.Restlet; import org.restlet.data.Form; import org.restlet.data.MediaType; @@ -43,16 +42,15 @@ public static void main(String[] args) try { // Create a new Restlet container - Container myContainer = new Container(); - Context myContext = myContainer.getContext(); + Container container = new Container(); // Create the HTTP server connector, then add it as a server // connector to the Restlet container. Note that the container // is the call restlet. - myContainer.getServers().add(Protocol.HTTP, 9876); + container.getServers().add(Protocol.HTTP, 9876); // Prepare and attach a test Restlet - Restlet testRestlet = new Restlet(myContext) + Restlet handler = new Restlet(container.getContext()) { public void handlePut(Request request, Response response) { @@ -78,10 +76,10 @@ public void handlePut(Request request, Response response) } }; - myContainer.getDefaultHost().attach("/test", testRestlet); + container.getDefaultHost().attach("/test", handler); // Now, start the container - myContainer.start(); + container.start(); } catch(Exception e) { diff --git a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java index a65dec98c5..795198ccb3 100644 --- a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java +++ b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java @@ -38,11 +38,11 @@ public class Tutorial05 public static void main(String[] args) throws Exception { // Create a new Restlet container and add a HTTP server connector to it - Container myContainer = new Container(); - myContainer.getServers().add(Protocol.HTTP, 8182); + Container container = new Container(); + container.getServers().add(Protocol.HTTP, 8182); // Create a new Restlet that will display some path information. - Restlet myRestlet = new Restlet() + Restlet handler = new Restlet() { public void handleGet(Request request, Response response) { @@ -56,11 +56,11 @@ public void handleGet(Request request, Response response) }; // Then attach it to the local host - myContainer.getDefaultHost().attach("/trace", myRestlet); + container.getDefaultHost().attach("/trace", handler); // Now, let's start the container! // Note that the HTTP server connector is also automatically started. - myContainer.start(); + container.start(); } } diff --git a/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF index a45210028b..a2c10fbba7 100644 --- a/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF +++ b/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF @@ -9,3 +9,4 @@ Require-Bundle: org.restlet, com.noelios.restlet, javax.servlet5, org.mortbay.jetty6 +Export-Package: com.noelios.restlet.ext.jetty diff --git a/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF index c772339c84..d896bf6f3a 100644 --- a/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF +++ b/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF @@ -7,3 +7,4 @@ Bundle-Vendor: Noelios Consulting Bundle-Localization: plugin Require-Bundle: org.restlet, com.noelios.restlet +Export-Package: com.noelios.restlet.ext.net diff --git a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF index f80e299ed6..fa7b7d1afe 100644 --- a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF +++ b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF @@ -8,3 +8,4 @@ Bundle-Localization: plugin Require-Bundle: org.restlet, com.noelios.restlet, javax.servlet4 +Export-Package: com.noelios.restlet.ext.servlet diff --git a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java index a3d2d56df1..b1701d3c28 100644 --- a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java +++ b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java @@ -43,22 +43,21 @@ * &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; * &lt;!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"&gt; * &lt;web-app&gt; - * &lt;display-name&gt;Server Servlet&lt;/display-name&gt; - * &lt;description&gt;Servlet acting as a Restlet server connector&lt;/description&gt; + * &lt;display-name&gt;Restlet adapter&lt;/display-name&gt; * - * &lt;!-- Application class handling calls --&gt; + * &lt;!-- Your application class name --&gt; * &lt;context-param&gt; * &lt;param-name&gt;org.restlet.application&lt;/param-name&gt; * &lt;param-value&gt;com.noelios.restlet.test.TraceApplication&lt;/param-value&gt; * &lt;/context-param&gt; * - * &lt;!-- ServerServlet class or a subclass --&gt; + * &lt;!-- Restlet adapter --&gt; * &lt;servlet&gt; * &lt;servlet-name&gt;ServerServlet&lt;/servlet-name&gt; * &lt;servlet-class&gt;com.noelios.restlet.ext.servlet.ServerServlet&lt;/servlet-class&gt; * &lt;/servlet&gt; * - * &lt;!-- Mapping of requests to the ServerServlet --&gt; + * &lt;!-- Catch all requests --&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;ServerServlet&lt;/servlet-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; diff --git a/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF index f8146a7664..cb9f582bcd 100644 --- a/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF +++ b/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF @@ -8,3 +8,4 @@ Bundle-Localization: plugin Require-Bundle: org.restlet, com.noelios.restlet, org.simpleframework;bundle-version="3.1.0" +Export-Package: com.noelios.restlet.ext.simple diff --git a/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF index 248ea19fa2..4a1b9b2663 100644 --- a/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF +++ b/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF @@ -13,3 +13,4 @@ Require-Bundle: org.restlet, com.noelios.restlet.ext.simple;resolution:=optional, com.noelios.restlet.ext.asyncweb;resolution:=optional, com.noelios.restlet.ext.atom +Export-Package: com.noelios.restlet.test
f8a5c25714f866a85290634e7b0344f02f6b930b
kotlin
Fix for the code to compile--
c
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/lang/cfg/Label.java b/idea/src/org/jetbrains/jet/lang/cfg/Label.java index ce3472befa2ae..9996252097706 100644 --- a/idea/src/org/jetbrains/jet/lang/cfg/Label.java +++ b/idea/src/org/jetbrains/jet/lang/cfg/Label.java @@ -3,19 +3,6 @@ /** * @author abreslav */ -public class Label { - private final String name; - - public Label(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return name; - } +public interface Label { + String getName(); } diff --git a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java index 0cfe7f36960a7..2948f9b131891 100644 --- a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java +++ b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java @@ -27,7 +27,7 @@ public JetControlFlowInstructionsGenerator() { } private void pushBuilder() { - Pseudocode parentPseudocode = builder == null ? new Pseudocode(null) : builders.peek().getPseudocode(); + Pseudocode parentPseudocode = builder == null ? new Pseudocode() : builders.peek().getPseudocode(); JetControlFlowInstructionsGeneratorWorker worker = new JetControlFlowInstructionsGeneratorWorker(parentPseudocode); builders.push(worker); builder = worker; @@ -90,16 +90,16 @@ public Label getExitPoint() { } } - private class JetControlFlowInstructionsGeneratorWorker implements JetControlFlowBuilder { - private final Stack<BlockInfo> loopInfo = new Stack<BlockInfo>(); - private final Stack<BlockInfo> subroutineInfo = new Stack<BlockInfo>(); + private final Stack<BlockInfo> loopInfo = new Stack<BlockInfo>(); + private final Stack<BlockInfo> subroutineInfo = new Stack<BlockInfo>(); + private final Map<JetElement, BlockInfo> elementToBlockInfo = new HashMap<JetElement, BlockInfo>(); - private final Map<JetElement, BlockInfo> elementToBlockInfo = new HashMap<JetElement, BlockInfo>(); + private class JetControlFlowInstructionsGeneratorWorker implements JetControlFlowBuilder { private final Pseudocode pseudocode; private JetControlFlowInstructionsGeneratorWorker(@Nullable Pseudocode parent) { - this.pseudocode = new Pseudocode(parent); + this.pseudocode = new Pseudocode(); } public Pseudocode getPseudocode() { @@ -113,7 +113,7 @@ private void add(Instruction instruction) { @NotNull @Override public final Label createUnboundLabel() { - return new Label("l" + labelCount++); + return pseudocode.createLabel("l" + labelCount++); } @Override diff --git a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java index d08d38f8c7761..9e40dd604b7b0 100644 --- a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java +++ b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java @@ -11,14 +11,44 @@ * @author abreslav */ public class Pseudocode { + public class PseudocodeLabel implements Label { + private final String name; + + private PseudocodeLabel(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public String toString() { + return name; + } + + @Nullable + private List<Instruction> resolve() { + Integer result = labels.get(this); + assert result != null; + return instructions.subList(result, instructions.size()); + } + + } + private final List<Instruction> instructions = new ArrayList<Instruction>(); private final Map<Label, Integer> labels = new LinkedHashMap<Label, Integer>(); - @Nullable - private final Pseudocode parent; +// @Nullable +// private final Pseudocode parent; +// +// public Pseudocode(Pseudocode parent) { +// this.parent = parent; +// } - public Pseudocode(Pseudocode parent) { - this.parent = parent; + public PseudocodeLabel createLabel(String name) { + return new PseudocodeLabel(name); } public void addInstruction(Instruction instruction) { @@ -29,15 +59,6 @@ public void addLabel(Label label) { labels.put(label, instructions.size()); } - @Nullable - private Integer resolveLabel(Label targetLabel) { - Integer result = labels.get(targetLabel); - if (result == null && parent != null) { - return parent.resolveLabel(targetLabel); - } - return result; - } - public void postProcess() { for (int i = 0, instructionsSize = instructions.size(); i < instructionsSize; i++) { Instruction instruction = instructions.get(i); @@ -95,22 +116,21 @@ public void visitInstruction(Instruction instruction) { @NotNull private Instruction getJumpTarget(@NotNull Label targetLabel) { - Integer targetPosition = resolveLabel(targetLabel); - return getTargetInstruction(targetPosition); + return getTargetInstruction(((PseudocodeLabel) targetLabel).resolve()); } @NotNull - private Instruction getTargetInstruction(@NotNull Integer targetPosition) { + private Instruction getTargetInstruction(@NotNull List<Instruction> instructions) { while (true) { - assert targetPosition != null; - Instruction targetInstruction = instructions.get(targetPosition); + assert instructions != null; + Instruction targetInstruction = instructions.get(0); if (false == targetInstruction instanceof UnconditionalJumpInstruction) { return targetInstruction; } Label label = ((UnconditionalJumpInstruction) targetInstruction).getTargetLabel(); - targetPosition = resolveLabel(label); + instructions = ((PseudocodeLabel)label).resolve(); } } @@ -118,7 +138,7 @@ private Instruction getTargetInstruction(@NotNull Integer targetPosition) { private Instruction getNextPosition(int currentPosition) { int targetPosition = currentPosition + 1; assert targetPosition < instructions.size() : currentPosition; - return getTargetInstruction(targetPosition); + return getTargetInstruction(instructions.subList(targetPosition, instructions.size())); } public void dumpInstructions(@NotNull PrintStream out) { @@ -140,6 +160,7 @@ public void dumpGraph(@NotNull final PrintStream out) { private void dumpSubgraph(final PrintStream out, String graphHeader, final int[] count, String style) { out.println(graphHeader + " {"); + out.println(style); final Map<Instruction, String> nodeToName = new HashMap<Instruction, String>(); for (Instruction node : instructions) { @@ -174,7 +195,7 @@ else if (node instanceof FunctionLiteralValueInstruction) { @Override public void visitFunctionLiteralValue(FunctionLiteralValueInstruction instruction) { int index = count[0]; - instruction.getBody().dumpSubgraph(out, "subgraph f" + index, count, "color=blue;\ntlabel = \"process #" + index + "\";"); + instruction.getBody().dumpSubgraph(out, "subgraph cluster_" + index, count, "color=blue;\nlabel = \"f" + index + "\";"); printEdge(out, nodeToName.get(instruction), "n" + index, null); visitInstructionWithNext(instruction); } @@ -228,7 +249,6 @@ public void visitInstruction(Instruction instruction) { } }); } - out.println(style); out.println("}"); } diff --git a/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java b/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java index 67a58cd7cd4dd..6d9bac71f1704 100644 --- a/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java +++ b/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java @@ -230,21 +230,21 @@ private void processFunction(@NotNull WritableScope declaringScope, JetFunction declaringScope.addFunctionDescriptor(descriptor); functions.put(function, descriptor); - JetExpression bodyExpression = function.getBodyExpression(); - if (bodyExpression != null) { - System.out.println("-------------"); - JetControlFlowInstructionsGenerator instructionsGenerator = new JetControlFlowInstructionsGenerator(); - new JetControlFlowProcessor(semanticServices, trace, instructionsGenerator).generate(function, bodyExpression); - Pseudocode pseudocode = instructionsGenerator.getPseudocode(); - pseudocode.postProcess(); - pseudocode.dumpInstructions(System.out); - System.out.println("-------------"); - try { - pseudocode.dumpGraph(new PrintStream("/Users/abreslav/work/cfg.dot")); - } catch (FileNotFoundException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } +// JetExpression bodyExpression = function.getBodyExpression(); +// if (bodyExpression != null) { +// System.out.println("-------------"); +// JetControlFlowInstructionsGenerator instructionsGenerator = new JetControlFlowInstructionsGenerator(); +// new JetControlFlowProcessor(semanticServices, trace, instructionsGenerator).generate(function, bodyExpression); +// Pseudocode pseudocode = instructionsGenerator.getPseudocode(); +// pseudocode.postProcess(); +// pseudocode.dumpInstructions(System.out); +// System.out.println("-------------"); +// try { +// pseudocode.dumpGraph(new PrintStream("/Users/abreslav/work/cfg.dot")); +// } catch (FileNotFoundException e) { +// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. +// } +// } } private void processProperty(WritableScope declaringScope, JetProperty property) { diff --git a/idea/testData/psi/ControlStructures.txt b/idea/testData/psi/ControlStructures.txt index d2c6a510a0403..45e96659ef3b7 100644 --- a/idea/testData/psi/ControlStructures.txt +++ b/idea/testData/psi/ControlStructures.txt @@ -86,7 +86,9 @@ JetFile: ControlStructures.jet BREAK PsiElement(break)('break') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiElement(COMMA)(',') PsiWhiteSpace('\n ') VALUE_PARAMETER @@ -120,7 +122,9 @@ JetFile: ControlStructures.jet CONTINUE PsiElement(continue)('continue') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiElement(COMMA)(',') PsiWhiteSpace('\n ') VALUE_PARAMETER @@ -207,7 +211,9 @@ JetFile: ControlStructures.jet BREAK PsiElement(break)('break') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiWhiteSpace('\n ') CONTINUE PsiElement(continue)('continue') @@ -219,7 +225,9 @@ JetFile: ControlStructures.jet CONTINUE PsiElement(continue)('continue') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiWhiteSpace('\n ') IF PsiElement(if)('if') diff --git a/idea/testData/psi/Labels.txt b/idea/testData/psi/Labels.txt index ad500e937ff33..422cafa58e8e8 100644 --- a/idea/testData/psi/Labels.txt +++ b/idea/testData/psi/Labels.txt @@ -37,18 +37,24 @@ JetFile: Labels.jet PsiWhiteSpace('\n\n ') RETURN PsiElement(return)('return') - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace(' ') INTEGER_CONSTANT PsiElement(INTEGER_LITERAL)('1') PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace(' ') PARENTHESIZED PsiElement(LPAR)('(') @@ -62,7 +68,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace(' ') PREFIX_EXPRESSION OPERATION_REFERENCE @@ -73,18 +81,24 @@ JetFile: Labels.jet PsiWhiteSpace('\n\n ') RETURN PsiElement(return)('return') - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiWhiteSpace(' ') INTEGER_CONSTANT PsiElement(INTEGER_LITERAL)('1') PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiWhiteSpace(' ') PARENTHESIZED PsiElement(LPAR)('(') @@ -98,7 +112,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiWhiteSpace(' ') PREFIX_EXPRESSION OPERATION_REFERENCE @@ -109,18 +125,24 @@ JetFile: Labels.jet PsiWhiteSpace('\n\n ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace(' ') INTEGER_CONSTANT PsiElement(INTEGER_LITERAL)('1') PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace(' ') PARENTHESIZED PsiElement(LPAR)('(') @@ -134,7 +156,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace(' ') PREFIX_EXPRESSION OPERATION_REFERENCE @@ -149,7 +173,9 @@ JetFile: Labels.jet PsiWhiteSpace(' ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace('\n ') PREFIX_EXPRESSION OPERATION_REFERENCE @@ -157,7 +183,9 @@ JetFile: Labels.jet PsiWhiteSpace(' ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace(' ') INTEGER_CONSTANT PsiElement(INTEGER_LITERAL)('1') @@ -168,7 +196,9 @@ JetFile: Labels.jet PsiWhiteSpace(' ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace(' ') PARENTHESIZED PsiElement(LPAR)('(') @@ -186,7 +216,9 @@ JetFile: Labels.jet PsiWhiteSpace(' ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace(' ') PREFIX_EXPRESSION OPERATION_REFERENCE @@ -200,30 +232,42 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') BREAK PsiElement(break)('break') - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace('\n ') BREAK PsiElement(break)('break') - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiWhiteSpace('\n ') BREAK PsiElement(break)('break') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace('\n\n ') CONTINUE PsiElement(continue)('continue') PsiWhiteSpace('\n ') CONTINUE PsiElement(continue)('continue') - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace('\n ') CONTINUE PsiElement(continue)('continue') - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiWhiteSpace('\n ') CONTINUE PsiElement(continue)('continue') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace('\n\n ') DOT_QUALIFIED_EXPRESSION REFERENCE_EXPRESSION @@ -255,7 +299,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(LABEL_IDENTIFIER)('@f') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@f') PsiWhiteSpace(' ') BOOLEAN_CONSTANT PsiElement(true)('true') @@ -292,7 +338,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace(' ') BOOLEAN_CONSTANT PsiElement(true)('true') @@ -329,7 +377,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') RETURN PsiElement(return)('return') - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace(' ') BOOLEAN_CONSTANT PsiElement(true)('true') @@ -341,18 +391,21 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') THIS_EXPRESSION PsiElement(this)('this') - LABEL_REFERENCE - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiWhiteSpace('\n ') THIS_EXPRESSION PsiElement(this)('this') - LABEL_REFERENCE - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiWhiteSpace('\n ') THIS_EXPRESSION PsiElement(this)('this') - LABEL_REFERENCE - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiWhiteSpace('\n\n ') THIS_EXPRESSION PsiElement(this)('this') @@ -365,8 +418,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') THIS_EXPRESSION PsiElement(this)('this') - LABEL_REFERENCE - PsiElement(AT)('@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(AT)('@') PsiElement(LT)('<') TYPE_REFERENCE USER_TYPE @@ -376,8 +430,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') THIS_EXPRESSION PsiElement(this)('this') - LABEL_REFERENCE - PsiElement(LABEL_IDENTIFIER)('@a') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@a') PsiElement(LT)('<') TYPE_REFERENCE USER_TYPE @@ -387,8 +442,9 @@ JetFile: Labels.jet PsiWhiteSpace('\n ') THIS_EXPRESSION PsiElement(this)('this') - LABEL_REFERENCE - PsiElement(ATAT)('@@') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(ATAT)('@@') PsiElement(LT)('<') TYPE_REFERENCE USER_TYPE diff --git a/idea/testData/psi/SimpleExpressions.txt b/idea/testData/psi/SimpleExpressions.txt index ee8ea4924d68e..8f4dc0157c43c 100644 --- a/idea/testData/psi/SimpleExpressions.txt +++ b/idea/testData/psi/SimpleExpressions.txt @@ -575,7 +575,9 @@ JetFile: SimpleExpressions.jet BREAK PsiElement(break)('break') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiElement(COMMA)(',') PsiWhiteSpace('\n ') VALUE_PARAMETER @@ -609,7 +611,9 @@ JetFile: SimpleExpressions.jet CONTINUE PsiElement(continue)('continue') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiElement(COMMA)(',') PsiWhiteSpace('\n ') VALUE_PARAMETER @@ -702,7 +706,9 @@ JetFile: SimpleExpressions.jet BREAK PsiElement(break)('break') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiWhiteSpace('\n ') CONTINUE PsiElement(continue)('continue') @@ -714,6 +720,8 @@ JetFile: SimpleExpressions.jet CONTINUE PsiElement(continue)('continue') PsiWhiteSpace(' ') - PsiElement(LABEL_IDENTIFIER)('@la') + LABEL_QUALIFIER + LABEL_REFERENCE + PsiElement(LABEL_IDENTIFIER)('@la') PsiWhiteSpace('\n') PsiElement(RBRACE)('}') \ No newline at end of file diff --git a/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java b/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java index fb257b919d077..70b1519da38ee 100644 --- a/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java +++ b/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java @@ -29,6 +29,6 @@ public void testBinaryCallsOnNullableValues() throws Exception { } public void testQualifiedThis() throws Exception { - doTest("/checker/QualifiedThis.jet", true, true); +// doTest("/checker/QualifiedThis.jet", true, true); } }
55149154710b8bd1825442c308fb9b4b76054a63
camel
[CAMEL-1289] HeaderFilterStrategy - move from- Component to Endpoint (for JHC component)--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@743889 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java index c96d3aa2e2123..20234e7ead3b4 100644 --- a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java +++ b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java @@ -20,21 +20,17 @@ import java.util.Map; import org.apache.camel.Endpoint; -import org.apache.camel.HeaderFilterStrategyAware; import org.apache.camel.impl.DefaultComponent; -import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; -public class JhcComponent extends DefaultComponent implements HeaderFilterStrategyAware { +public class JhcComponent extends DefaultComponent { private HttpParams params; - private HeaderFilterStrategy headerFilterStrategy; public JhcComponent() { - setHeaderFilterStrategy(new JhcHeaderFilterStrategy()); params = new BasicHttpParams() .setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000) @@ -57,11 +53,4 @@ protected Endpoint createEndpoint(String uri, String remaining, Map parameters) return new JhcEndpoint(uri, this, new URI(uri.substring(uri.indexOf(':') + 1))); } - public HeaderFilterStrategy getHeaderFilterStrategy() { - return headerFilterStrategy; - } - - public void setHeaderFilterStrategy(HeaderFilterStrategy strategy) { - headerFilterStrategy = strategy; - } } diff --git a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java index 36131122d0836..6b9677b0a470b 100644 --- a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java +++ b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java @@ -19,7 +19,6 @@ import java.net.URI; import org.apache.camel.Consumer; -import org.apache.camel.HeaderFilterStrategyAware; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; @@ -37,6 +36,7 @@ public class JhcEndpoint extends DefaultEndpoint { private HttpParams params; private URI httpUri; + private HeaderFilterStrategy headerFilterStrategy; public JhcEndpoint(String endpointUri, JhcComponent component, URI httpUri) { super(endpointUri, component); @@ -101,11 +101,12 @@ public Consumer createConsumer(Processor processor) throws Exception { return new JhcConsumer(this, processor); } + public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { + this.headerFilterStrategy = headerFilterStrategy; + } + public HeaderFilterStrategy getHeaderFilterStrategy() { - if (getComponent() instanceof HeaderFilterStrategyAware) { - return ((HeaderFilterStrategyAware)getComponent()).getHeaderFilterStrategy(); - } else { - return new JhcHeaderFilterStrategy(); - } + return headerFilterStrategy; } + }
b2b7e6996be0cea4d872be637c4fc100971d926e
kotlin
Decompiler: Introduce DeserializerForDecompiler--Component which can "resolve" descriptors without project-It builds dummy descriptors for dependencies which are enough to build decompiled text-
a
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/ClassId.java b/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/ClassId.java index 88eac1346c08f..c0efac5d2cd3d 100644 --- a/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/ClassId.java +++ b/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/ClassId.java @@ -22,6 +22,12 @@ import org.jetbrains.jet.lang.resolve.name.Name; public final class ClassId { + + @NotNull + public static ClassId topLevel(@NotNull FqName topLevelFqName) { + return new ClassId(topLevelFqName.parent(), FqNameUnsafe.topLevel(topLevelFqName.shortName())); + } + private final FqName packageFqName; private final FqNameUnsafe relativeClassName; @@ -55,6 +61,7 @@ public boolean isTopLevelClass() { return relativeClassName.parent().isRoot(); } + @NotNull public FqNameUnsafe asSingleFqName() { if (packageFqName.isRoot()) return relativeClassName; return new FqNameUnsafe(packageFqName.asString() + "." + relativeClassName.asString()); diff --git a/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/DescriptorFinder.java b/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/DescriptorFinder.java index d56637c306e1c..6ed1cb6e5b09e 100644 --- a/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/DescriptorFinder.java +++ b/compiler/frontend/serialization/src/org/jetbrains/jet/descriptors/serialization/DescriptorFinder.java @@ -18,6 +18,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.ReadOnly; import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.resolve.name.FqName; import org.jetbrains.jet.lang.resolve.name.Name; @@ -43,6 +44,7 @@ public Collection<Name> getClassNames(@NotNull FqName packageName) { @Nullable ClassDescriptor findClass(@NotNull ClassId classId); + @ReadOnly @NotNull Collection<Name> getClassNames(@NotNull FqName packageName); } diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/DeserializerForDecompiler.kt b/idea/src/org/jetbrains/jet/plugin/libraries/DeserializerForDecompiler.kt new file mode 100644 index 0000000000000..44331f5b8c71c --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/libraries/DeserializerForDecompiler.kt @@ -0,0 +1,188 @@ +/* + * Copyright 2010-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.libraries + +import org.jetbrains.jet.descriptors.serialization.ClassId +import org.jetbrains.jet.descriptors.serialization.DescriptorFinder +import org.jetbrains.jet.descriptors.serialization.JavaProtoBufUtil +import org.jetbrains.jet.descriptors.serialization.descriptors.DeserializedClassDescriptor +import org.jetbrains.jet.lang.descriptors.* +import org.jetbrains.jet.lang.descriptors.impl.MutablePackageFragmentDescriptor +import org.jetbrains.jet.lang.resolve.kotlin.KotlinJvmBinaryClass +import org.jetbrains.jet.lang.resolve.name.FqName +import org.jetbrains.jet.lang.resolve.name.Name +import org.jetbrains.jet.lang.types.ErrorUtils +import org.jetbrains.jet.storage.LockBasedStorageManager +import java.util.Collections +import org.jetbrains.jet.lang.resolve.java.resolver.DescriptorResolverUtils +import com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.jet.lang.resolve.kotlin.KotlinBinaryClassCache +import org.jetbrains.jet.lang.resolve.kotlin.DeserializedResolverUtils +import org.jetbrains.jet.descriptors.serialization.descriptors.DeserializedPackageMemberScope +import org.jetbrains.jet.lang.resolve.kotlin.AnnotationDescriptorDeserializer +import org.jetbrains.jet.lang.resolve.java.resolver.ErrorReporter +import org.jetbrains.jet.lang.types.ErrorUtils.getErrorModule +import org.jetbrains.jet.lang.types.error.MissingDependencyErrorClassDescriptor +import org.jetbrains.jet.lang.resolve.java.PackageClassUtils +import com.intellij.openapi.diagnostic.Logger +import org.jetbrains.jet.lang.resolve.kotlin.KotlinClassFinder +import org.jetbrains.jet.lang.resolve.name.FqNameUnsafe + +public fun DeserializerForDecompiler(classFile: VirtualFile): DeserializerForDecompiler { + val kotlinClass = KotlinBinaryClassCache.getKotlinBinaryClass(classFile) + val classFqName = kotlinClass.getClassName().getFqNameForClassNameWithoutDollars() + val packageFqName = classFqName.parent() + return DeserializerForDecompiler(classFile.getParent()!!, packageFqName) +} + +public class DeserializerForDecompiler(val packageDirectory: VirtualFile, val directoryPackageFqName: FqName) : ResolverForDecompiler { + + override fun resolveClass(classFqName: FqName) = classes(classFqName.toClassId()) + + override fun resolveDeclarationsInPackage(packageFqName: FqName): Collection<DeclarationDescriptor> { + assert(packageFqName == directoryPackageFqName, "Was called for $packageFqName but only $directoryPackageFqName is expected.") + val packageClassFqName = PackageClassUtils.getPackageClassFqName(packageFqName) + val binaryClassForPackageClass = localClassFinder.findKotlinClass(packageClassFqName) + val annotationData = binaryClassForPackageClass?.getClassHeader()?.getAnnotationData() + if (annotationData == null) { + LOG.error("Could not read annotation data for $packageFqName from ${binaryClassForPackageClass?.getClassName()}") + return Collections.emptyList() + } + val membersScope = DeserializedPackageMemberScope( + storageManager, + createDummyPackageFragment(packageFqName), + annotationDeserializer, + descriptorFinder, + JavaProtoBufUtil.readPackageDataFrom(annotationData) + ) + return membersScope.getAllDescriptors() + } + + private val localClassFinder = object: KotlinClassFinder { + override fun findKotlinClass(fqName: FqName) = findKotlinClass(fqName.toClassId()) + + fun findKotlinClass(classId: ClassId): KotlinJvmBinaryClass? { + if (classId.getPackageFqName() != directoryPackageFqName) { + return null + } + val segments = DeserializedResolverUtils.kotlinFqNameToJavaFqName(classId.getRelativeClassName()).pathSegments() + val targetName = segments.makeString("$", postfix = ".class") + val virtualFile = packageDirectory.findChild(targetName) + if (virtualFile != null && DecompiledUtils.isKotlinCompiledFile(virtualFile)) { + return KotlinBinaryClassCache.getKotlinBinaryClass(virtualFile) + } + return null + } + } + private val storageManager = LockBasedStorageManager.NO_LOCKS + private val classes = storageManager.createMemoizedFunctionWithNullableValues { + (classId: ClassId) -> + resolveClassByClassId(classId) + } + + private val annotationDeserializer = AnnotationDescriptorDeserializer(storageManager); + { + annotationDeserializer.setClassResolver { + fqName -> + classes(fqName.toClassId()) + } + annotationDeserializer.setKotlinClassFinder(localClassFinder) + annotationDeserializer.setErrorReporter(LOGGING_REPORTER) + } + + private val descriptorFinder = object : DescriptorFinder { + override fun findClass(classId: ClassId): ClassDescriptor? { + return classes(classId) + } + + override fun getClassNames(packageName: FqName): Collection<Name> { + return Collections.emptyList() + } + } + + private val packageFragmentProvider = object : PackageFragmentProvider { + override fun getPackageFragments(fqName: FqName): List<PackageFragmentDescriptor> { + return listOf(createDummyPackageFragment(fqName)) + } + + override fun getSubPackagesOf(fqName: FqName): Collection<FqName> { + throw UnsupportedOperationException("This method is not supposed to be called.") + } + } + + private fun createDummyPackageFragment(fqName: FqName): MutablePackageFragmentDescriptor { + return MutablePackageFragmentDescriptor(ErrorUtils.getErrorModule(), fqName) + } + + private fun resolveClassByClassId(classId: ClassId): ClassDescriptor? { + val fullFqName = classId.asSingleFqName() + if (fullFqName.isSafe()) { + val fromBuiltIns = DescriptorResolverUtils.getKotlinBuiltinClassDescriptor(fullFqName.toSafe()) + if (fromBuiltIns != null) { + return fromBuiltIns + } + } + val binaryClass = localClassFinder.findKotlinClass(classId) + if (binaryClass != null) { + return deserializeBinaryClass(binaryClass) + } + assert(fullFqName.isSafe(), "Safe fq name expected here, got $fullFqName instead") + return MissingDependencyErrorClassDescriptor(fullFqName.toSafe()) + } + + private fun deserializeBinaryClass(kotlinClass: KotlinJvmBinaryClass): ClassDescriptor { + val data = kotlinClass.getClassHeader()?.getAnnotationData() + if (data == null) { + LOG.error("Annotation data missing for ${kotlinClass.getClassName()}") + } + val classData = JavaProtoBufUtil.readClassDataFrom(data!!) + return DeserializedClassDescriptor(storageManager, annotationDeserializer, descriptorFinder, packageFragmentProvider, + classData.getNameResolver(), classData.getClassProto()) + } + + // we need a "magic" way to obtain ClassId from FqName + // the idea behind this function is that we need accurate class ids only for "neighbouring" classes (inner classes, class object, etc) + // for all others we can build any ClassId since it will resolve to MissingDependencyErrorClassDescriptor which only stores fqName + private fun FqName.toClassId(): ClassId { + val segments = pathSegments() + val packageSegmentsCount = directoryPackageFqName.pathSegments().size + if (segments.size <= packageSegmentsCount) { + return ClassId.topLevel(this) + } + val packageFqName = FqName.fromSegments(segments.subList(0, packageSegmentsCount) map { it.asString() }) + if (packageFqName == directoryPackageFqName) { + return ClassId(packageFqName, FqNameUnsafe.fromSegments(segments.subList(packageSegmentsCount, segments.size))) + } + return ClassId.topLevel(this) + } + + class object { + private val LOG = Logger.getInstance(javaClass<DeserializerForDecompiler>()) + + private object LOGGING_REPORTER: ErrorReporter { + override fun reportAnnotationLoadingError(message: String, exception: Exception?) { + LOG.error(message, exception) + } + override fun reportCannotInferVisibility(descriptor: CallableMemberDescriptor) { + LOG.error("Could not infer visibility for $descriptor") + } + override fun reportIncompatibleAbiVersion(kotlinClass: KotlinJvmBinaryClass, actualVersion: Int) { + LOG.error("Incompatible ABI version for class ${kotlinClass.getClassName()}, actual version: $actualVersion") + } + } + } +}
6f259eb229470099173b20b236e55435597b1e3f
ReactiveX-RxJava
Delay: error cut ahead was not properly serialized--
c
https://github.com/ReactiveX/RxJava
diff --git a/src/main/java/rx/internal/operators/OperatorDelay.java b/src/main/java/rx/internal/operators/OperatorDelay.java index 48b8454dc8..00ab5d1b49 100644 --- a/src/main/java/rx/internal/operators/OperatorDelay.java +++ b/src/main/java/rx/internal/operators/OperatorDelay.java @@ -49,22 +49,36 @@ public Subscriber<? super T> call(final Subscriber<? super T> child) { final Worker worker = scheduler.createWorker(); child.add(worker); return new Subscriber<T>(child) { - + // indicates an error cut ahead + // accessed from the worker thread only + boolean done; @Override public void onCompleted() { worker.schedule(new Action0() { @Override public void call() { - child.onCompleted(); + if (!done) { + done = true; + child.onCompleted(); + } } }, delay, unit); } @Override - public void onError(Throwable e) { - child.onError(e); + public void onError(final Throwable e) { + worker.schedule(new Action0() { + @Override + public void call() { + if (!done) { + done = true; + child.onError(e); + worker.unsubscribe(); + } + } + }); } @Override @@ -73,7 +87,9 @@ public void onNext(final T t) { @Override public void call() { - child.onNext(t); + if (!done) { + child.onNext(t); + } } }, delay, unit); diff --git a/src/test/java/rx/internal/operators/OperatorDelayTest.java b/src/test/java/rx/internal/operators/OperatorDelayTest.java index 9f80f0dc73..e4db021eaf 100644 --- a/src/test/java/rx/internal/operators/OperatorDelayTest.java +++ b/src/test/java/rx/internal/operators/OperatorDelayTest.java @@ -798,4 +798,27 @@ public Integer call(Integer t) { ts.assertNoErrors(); assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size()); } + + @Test + public void testErrorRunsBeforeOnNext() { + TestScheduler test = Schedulers.test(); + + PublishSubject<Integer> ps = PublishSubject.create(); + + TestSubscriber<Integer> ts = TestSubscriber.create(); + + ps.delay(1, TimeUnit.SECONDS, test).subscribe(ts); + + ps.onNext(1); + + test.advanceTimeBy(500, TimeUnit.MILLISECONDS); + + ps.onError(new TestException()); + + test.advanceTimeBy(1, TimeUnit.SECONDS); + + ts.assertNoValues(); + ts.assertError(TestException.class); + ts.assertNotCompleted(); + } }
10d01bb9da84d588f57a824ef9dc048562af2f7a
Mylyn Reviews
bug 386204: Allow users to include subtasks in changeset view Refactored part and introduced a model, which allows including subtasks. https://bugs.eclipse.org/bugs/show_bug.cgi?id=386204 Change-Id: I94af1aa42624b69f280d8dca54c8020f877a9f45
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java index b1787d9b..2ca7ca10 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java @@ -14,25 +14,37 @@ import java.util.List; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.ToolBarManager; +import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.viewers.ArrayContentProvider; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.mylyn.internal.tasks.ui.editors.Messages; +import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.tasks.core.ITask; +import org.eclipse.mylyn.tasks.core.ITaskContainer; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart; import org.eclipse.mylyn.versions.core.ChangeSet; import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping; import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet; +import org.eclipse.mylyn.versions.tasks.ui.internal.IChangesetModel; +import org.eclipse.mylyn.versions.tasks.ui.internal.IncludeSubTasksAction; +import org.eclipse.mylyn.versions.tasks.ui.internal.TaskChangesetLabelProvider; +import org.eclipse.mylyn.versions.tasks.ui.internal.TaskVersionsUiPlugin; import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.layout.FillLayout; 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.Menu; +import org.eclipse.ui.forms.events.HyperlinkAdapter; +import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; @@ -43,40 +55,8 @@ */ @SuppressWarnings("restriction") public class ChangesetPart extends AbstractTaskEditorPart { - private static final class TaskChangesetLabelProvider implements - ITableLabelProvider { - public void addListener(ILabelProviderListener listener) { - } - - public void dispose() { - } - - public boolean isLabelProperty(Object element, String property) { - return false; - } - - public void removeListener(ILabelProviderListener listener) { - } - - public Image getColumnImage(Object element, int columnIndex) { - return null; - } - - public String getColumnText(Object element, int columnIndex) { - TaskChangeSet cs = ((TaskChangeSet) element); - switch (columnIndex) { - case 0: - return cs.getChangeset().getId(); - case 1: - return cs.getChangeset().getMessage(); - case 2: - return cs.getChangeset().getAuthor().getEmail(); - case 3: - return cs.getChangeset().getDate().toString(); - } - return element.toString() + " " + columnIndex; - } - } + private TableViewer table; + private ChangesetModel model = new ChangesetModel(); public ChangesetPart() { setPartName("Changeset"); @@ -87,7 +67,7 @@ public ChangesetPart() { public void createControl(Composite parent, FormToolkit toolkit) { Section createSection = createSection(parent, toolkit); Composite composite = createContentComposite(toolkit, createSection); - + createTable(composite); } @@ -113,7 +93,7 @@ private Section createSection(Composite parent, FormToolkit toolkit) { } private void createTable(Composite composite) { - TableViewer table = new TableViewer(composite); + table = new TableViewer(composite); table.getTable().setLinesVisible(true); table.getTable().setHeaderVisible(true); addColumn(table, "Id"); @@ -122,11 +102,22 @@ private void createTable(Composite composite) { addColumn(table, "Date"); table.setContentProvider(ArrayContentProvider.getInstance()); table.setLabelProvider(new TaskChangesetLabelProvider()); - table.setInput(getInput()); + refreshInput(); + registerContextMenu(table); + } + + @Override + protected void fillToolBar(ToolBarManager toolBarManager) { + super.fillToolBar(toolBarManager); + toolBarManager.add(new IncludeSubTasksAction(model)); + } + + private void registerContextMenu(TableViewer table) { MenuManager menuManager = new MenuManager(); menuManager.setRemoveAllWhenShown(true); getTaskEditorPage().getEditorSite().registerContextMenu( - "org.eclipse.mylyn.versions.changesets", menuManager, table, true); + "org.eclipse.mylyn.versions.changesets", menuManager, table, + true); Menu menu = menuManager.createContextMenu(table.getControl()); table.getTable().setMenu(menu); } @@ -138,40 +129,88 @@ private void addColumn(TableViewer table, String name) { tableViewerColumn.getColumn().setWidth(100); } - private List<TaskChangeSet> getInput() { - int score = Integer.MIN_VALUE; + private AbstractChangesetMappingProvider determineBestProvider( + final ITask task) { AbstractChangesetMappingProvider bestProvider = null; - final ITask task = getModel().getTask(); - + int score = Integer.MIN_VALUE; for (AbstractChangesetMappingProvider mappingProvider : TaskChangesetUtil .getMappingProviders()) { - if (score < mappingProvider.getScoreFor(task)) - ; - { + if (score < mappingProvider.getScoreFor(task)) { bestProvider = mappingProvider; } } - final List<TaskChangeSet> changesets = new ArrayList<TaskChangeSet>(); - try { + return bestProvider; + } - IChangeSetMapping changesetsMapping = new IChangeSetMapping() { + private IChangeSetMapping createChangeSetMapping(final ITask task, + final List<TaskChangeSet> changesets) { + return new IChangeSetMapping() { - public ITask getTask() { - return task; - } + public ITask getTask() { + return task; + } + + public void addChangeSet(ChangeSet changeset) { + changesets.add(new TaskChangeSet(task, changeset)); + } + }; + } + + private void refreshInput() { + table.setInput(model.getInput()); + } + + private class ChangesetModel implements IChangesetModel { + + private boolean includeSubTasks; - public void addChangeSet(ChangeSet changeset) { - changesets.add(new TaskChangeSet(task, changeset)); + public boolean isIncludeSubTasks() { + return includeSubTasks; + } + + public void setIncludeSubTasks(boolean includeSubTasks) { + boolean isChanged = this.includeSubTasks ^ includeSubTasks; + this.includeSubTasks = includeSubTasks; + if (isChanged) { + refreshInput(); + } + } + + public List<TaskChangeSet> getInput() { + final ITask task = getModel().getTask(); + + AbstractChangesetMappingProvider bestProvider = determineBestProvider(task); + final List<TaskChangeSet> changesets = new ArrayList<TaskChangeSet>(); + + final List<IChangeSetMapping> changesetsMapping = new ArrayList<IChangeSetMapping>(); + changesetsMapping.add(createChangeSetMapping(task, changesets)); + ; + if (includeSubTasks) { + if (task instanceof ITaskContainer) { + ITaskContainer taskContainer = (ITaskContainer) task; + for (ITask subTask : taskContainer.getChildren()) { + changesetsMapping.add(createChangeSetMapping(subTask, + changesets)); + } } - }; - // FIXME progress monitor - bestProvider.getChangesetsForTask(changesetsMapping, - new NullProgressMonitor()); - } catch (CoreException e) { - // FIXME Auto-generated catch block - e.printStackTrace(); + } + final AbstractChangesetMappingProvider provider = bestProvider; + BusyIndicator.showWhile(Display.getDefault(), new Runnable() { + + public void run() { + try { + for (IChangeSetMapping csm : changesetsMapping) { + provider.getChangesetsForTask(csm, + new NullProgressMonitor()); + } + } catch (CoreException e) { + getTaskEditorPage().getTaskEditor().setMessage("An exception occurred " + e.getMessage(), IMessageProvider.ERROR); + } + } + + }); + + return changesets; } - return changesets; } - } diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java new file mode 100644 index 00000000..8839451c --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.ui.internal; + +/** + * @author Kilian Matt + */ +public interface IChangesetModel { + public void setIncludeSubTasks(boolean includeSubTasks); +} \ No newline at end of file diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java new file mode 100644 index 00000000..1ae383c8 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.ui.internal; + +import org.eclipse.jface.action.Action; +import org.eclipse.mylyn.tasks.ui.TasksUiImages; +import org.eclipse.swt.widgets.Event; + +/** + * @author Kilian Matt + */ +public class IncludeSubTasksAction extends Action { + private IChangesetModel model; + + public IncludeSubTasksAction(IChangesetModel model) { + super("Include subtasks",AS_CHECK_BOX); + setImageDescriptor(TasksUiImages.TASK_NEW_SUB); + this.model = model; + } + + public void run() { + model.setIncludeSubTasks(isChecked()); + } + + public void runWithEvent(Event event) { + model.setIncludeSubTasks(isChecked()); + } + +} diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java new file mode 100644 index 00000000..966afc90 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.ui.internal; + +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet; +import org.eclipse.swt.graphics.Image; + +/** + * @author Kilian Matt + */ +public class TaskChangesetLabelProvider implements ITableLabelProvider { + public void addListener(ILabelProviderListener listener) { + } + + public void dispose() { + } + + public boolean isLabelProperty(Object element, String property) { + return false; + } + + public void removeListener(ILabelProviderListener listener) { + } + + public Image getColumnImage(Object element, int columnIndex) { + return null; + } + + public String getColumnText(Object element, int columnIndex) { + TaskChangeSet cs = ((TaskChangeSet) element); + switch (columnIndex) { + case 0: + return cs.getChangeset().getId(); + case 1: + return cs.getChangeset().getMessage(); + case 2: + return cs.getChangeset().getAuthor().getEmail(); + case 3: + return cs.getChangeset().getDate().toString(); + } + return element.toString() + " " + columnIndex; + } +}
c5f5ced6b4280c73da019703957c8859c14fbb43
buddycloud$buddycloud-server-java
Completed <recent-items> functionality
p
https://github.com/buddycloud/buddycloud-server-java
diff --git a/src/main/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGet.java b/src/main/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGet.java index 0e0c9947..7fc724c6 100644 --- a/src/main/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGet.java +++ b/src/main/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGet.java @@ -1,5 +1,6 @@ package org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.get; +import java.io.StringReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @@ -9,14 +10,19 @@ import org.apache.log4j.Logger; import org.buddycloud.channelserver.channel.ChannelManager; import org.buddycloud.channelserver.channel.Conf; +import org.buddycloud.channelserver.db.CloseableIterator; import org.buddycloud.channelserver.db.exception.NodeStoreException; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubElementProcessor; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubElementProcessorAbstract; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubGet; import org.buddycloud.channelserver.pubsub.model.NodeAffiliation; +import org.buddycloud.channelserver.pubsub.model.NodeItem; +import org.buddycloud.channelserver.pubsub.model.NodeSubscription; import org.buddycloud.channelserver.queue.FederatedQueueManager; +import org.dom4j.DocumentException; import org.dom4j.Element; +import org.dom4j.io.SAXReader; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; @@ -29,22 +35,35 @@ public class RecentItemsGet extends PubSubElementProcessorAbstract { private String firstItem; private String lastItem; private int totalEntriesCount; - + private SimpleDateFormat sdf; - + private Date maxAge; private Integer maxItems; - private static final Logger logger = Logger - .getLogger(RecentItemsGet.class); + private Element pubsub; + private SAXReader xmlReader; + private String nodeEnding = "/posts"; + + // RSM details + private String firstItemId = null; + private String lastItemId = null; + private String afterItemId = null; + private int maxResults = -1; + + private static final Logger logger = Logger.getLogger(RecentItemsGet.class); + + public static final String NS_RSM = "http://jabber.org/protocol/rsm"; public RecentItemsGet(BlockingQueue<Packet> outQueue, ChannelManager channelManager) { setChannelManager(channelManager); setOutQueue(outQueue); + xmlReader = new SAXReader(); + sdf = new SimpleDateFormat(Conf.DATE_FORMAT); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); } @Override @@ -55,36 +74,121 @@ public void process(Element elm, JID actorJID, IQ reqIQ, Element rsm) actor = actorJID; node = elm.attributeValue("node"); resultSetManagement = rsm; - - if (false == validStanza()) { + + if (null == actor) { + actor = request.getFrom(); + } + + if (false == isValidStanza()) { + outQueue.put(response); + return; + } + + if (false == channelManager.isLocalJID(request.getFrom())) { + response.getElement().addAttribute("remote-server-discover", + "false"); + } + pubsub = response.getElement().addElement("pubsub", + JabberPubsub.NAMESPACE_URI); + try { + parseRsmElement(); + addRecentItems(); + addRsmElement(); outQueue.put(response); + } catch (NodeStoreException e) { + logger.error(e); + response.getElement().remove(pubsub); + setErrorCondition(PacketError.Type.wait, + PacketError.Condition.internal_server_error); + } + outQueue.put(response); + + } + + private void parseRsmElement() { + Element rsmElement = pubsub.element("set"); + if (null == rsmElement) return; + Element max; + Element after; + if (null != (max = rsmElement.element("max"))) + maxResults = Integer.parseInt(max.getTextTrim()); + if (null != (after = rsmElement.element("after"))) + afterItemId = after.getTextTrim(); + } + + private void addRsmElement() throws NodeStoreException { + if (null == firstItemId) return; + Element rsm = pubsub.addElement("set"); + rsm.addNamespace("", NS_RSM); + rsm.addElement("first").setText(firstItemId); + rsm.addElement("last").setText(lastItemId); + rsm.addElement("count").setText( + String.valueOf(channelManager.getCountRecentItems(actor, + maxAge, maxItems, nodeEnding))); + } + + private void addRecentItems() throws NodeStoreException { + CloseableIterator<NodeItem> items = channelManager.getRecentItems( + actor, maxAge, maxItems, maxResults, afterItemId, nodeEnding); + String lastNode = ""; + NodeItem item; + Element itemsElement = null; + Element itemElement; + Element entry; + while (items.hasNext()) { + item = items.next(); + + if (false == item.getNodeId().equals(lastNode)) { + itemsElement = pubsub.addElement("items"); + itemsElement.addAttribute("node", item.getNodeId()); + lastNode = item.getNodeId(); + } + try { + entry = xmlReader.read(new StringReader(item.getPayload())) + .getRootElement(); + itemElement = itemsElement.addElement("item"); + itemElement.addAttribute("id", item.getId()); + if (null == firstItemId) + firstItemId = item.getId(); + lastItemId = item.getId(); + itemElement.add(entry); + } catch (DocumentException e) { + logger.error("Error parsing a node entry, ignoring. " + + item.getId()); + } } } - private boolean validStanza() { + private boolean isValidStanza() { Element recentItems = request.getChildElement().element("recent-items"); try { String max = recentItems.attributeValue("max"); if (null == max) { - createExtendedErrorReply(PacketError.Type.modify, PacketError.Condition.bad_request, "max-required"); + createExtendedErrorReply(PacketError.Type.modify, + PacketError.Condition.bad_request, "max-required"); return false; } maxItems = Integer.parseInt(max); - String since = recentItems.attributeValue("since"); - if (null == since) { - createExtendedErrorReply(PacketError.Type.modify, PacketError.Condition.bad_request, "since-required"); + String since = recentItems.attributeValue("since"); + if (null == since) { + createExtendedErrorReply(PacketError.Type.modify, + PacketError.Condition.bad_request, "since-required"); return false; - } - maxAge = sdf.parse(since); + } + maxAge = sdf.parse(since); } catch (NumberFormatException e) { logger.error(e); - createExtendedErrorReply(PacketError.Type.modify, PacketError.Condition.bad_request, "invalid-max-value-provided"); - return false; + createExtendedErrorReply(PacketError.Type.modify, + PacketError.Condition.bad_request, + "invalid-max-value-provided"); + return false; } catch (ParseException e) { - createExtendedErrorReply(PacketError.Type.modify, PacketError.Condition.bad_request, "invalid-since-value-provided"); - logger.error(e); + createExtendedErrorReply(PacketError.Type.modify, + PacketError.Condition.bad_request, + "invalid-since-value-provided"); + logger.error(e); return false; } return true; diff --git a/src/test/java/org/buddycloud/channelserver/db/jdbc/JDBCNodeStoreTest.java b/src/test/java/org/buddycloud/channelserver/db/jdbc/JDBCNodeStoreTest.java index 415a80d9..7ca4251e 100644 --- a/src/test/java/org/buddycloud/channelserver/db/jdbc/JDBCNodeStoreTest.java +++ b/src/test/java/org/buddycloud/channelserver/db/jdbc/JDBCNodeStoreTest.java @@ -1511,6 +1511,135 @@ public void testGetNodeItemById() throws Exception { assertTrue("Unexpected Node content returned", result.getPayload() .contains(TEST_SERVER1_NODE1_ITEM1_CONTENT)); } + + + @Test + public void testGetRecentItems() throws Exception { + + Date since = new Date(); + dbTester.loadData("node_1"); + store.addRemoteNode(TEST_SERVER1_NODE2_ID); + store.addUserSubscription(new NodeSubscriptionImpl( + TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, + Subscriptions.subscribed)); + + NodeItem nodeItem1 = new NodeItemImpl(TEST_SERVER1_NODE1_ID, "123", + new Date(), "payload"); + NodeItem nodeItem2 = new NodeItemImpl(TEST_SERVER1_NODE2_ID, "123", + new Date(), "payload2"); + store.addNodeItem(nodeItem1); + store.addNodeItem(nodeItem2); + + CloseableIterator<NodeItem> items = store.getRecentItems( + TEST_SERVER1_USER1_JID, since, -1, -1, null, null); + + // 2 -> 1 on purpose results are most recent first! + assertSameNodeItem(items.next(), nodeItem2); + assertSameNodeItem(items.next(), nodeItem1); + assertEquals(false, items.hasNext()); + } + + @Test + public void testGetRecentItemsWithNoResultsPerNodeRequestedReturnsExpectedCount() + throws Exception { + Date since = new Date(0); + dbTester.loadData("node_1"); + store.addRemoteNode(TEST_SERVER1_NODE2_ID); + store.addUserSubscription(new NodeSubscriptionImpl( + TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, + Subscriptions.subscribed)); + + NodeItem nodeItem1 = new NodeItemImpl(TEST_SERVER1_NODE1_ID, "1", + new Date(), "payload"); + NodeItem nodeItem2 = new NodeItemImpl(TEST_SERVER1_NODE2_ID, "2", + new Date(), "payload2"); + store.addNodeItem(nodeItem1); + store.addNodeItem(nodeItem2); + + CloseableIterator<NodeItem> items = store.getRecentItems( + TEST_SERVER1_USER1_JID, since, 0, -1, null, null); + + int count = 0; + while (items.hasNext()) { + items.next(); + ++count; + } + assertEquals(0, count); + } + + @Test + public void testCanPageGetRecentItemsUsingResultSetManagement() + throws Exception { + Date since = new Date(0); + + dbTester.loadData("node_1"); + store.addRemoteNode(TEST_SERVER1_NODE2_ID); + store.addUserSubscription(new NodeSubscriptionImpl( + TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, + Subscriptions.subscribed)); + + for (int i = 1; i < 20; i++) { + Thread.sleep(1); + store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE1_ID, String + .valueOf(i), new Date(), "payload" + String.valueOf(i))); + } + + CloseableIterator<NodeItem> items = store.getRecentItems( + TEST_SERVER1_USER1_JID, since, -1, -1, "5", null); + + int count = 0; + int i = 19; + + NodeItem item; + while (items.hasNext()) { + assertSameNodeItem(items.next(), new NodeItemImpl( + TEST_SERVER1_NODE1_ID, String.valueOf(i), new Date(), + "payload" + String.valueOf(i))); + --i; + ++count; + } + assertEquals(15, count); + } + + @Test + public void testGetRecentItemCountWithNoResultsPerNodeRequestedReturnsExpectedCount() + throws Exception { + Date since = new Date(); + dbTester.loadData("node_1"); + store.addRemoteNode(TEST_SERVER1_NODE2_ID); + store.addUserSubscription(new NodeSubscriptionImpl( + TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, + Subscriptions.subscribed)); + + store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE1_ID, "123", + new Date(), "payload")); + store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE2_ID, "123", + new Date(), "payload2")); + + int count = store.getCountRecentItems(TEST_SERVER1_USER1_JID, since, 0, + null); + assertEquals(0, count); + } + + @Test + public void testGetRecentItemCount() throws Exception { + + Date since = new Date(); + dbTester.loadData("node_1"); + store.addRemoteNode(TEST_SERVER1_NODE2_ID); + store.addUserSubscription(new NodeSubscriptionImpl( + TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, + Subscriptions.subscribed)); + Thread.sleep(1); + store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE1_ID, "123", + new Date(), "payload")); + store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE2_ID, "123", + new Date(), "payload2")); + + int count = store.getCountRecentItems(TEST_SERVER1_USER1_JID, since, + -1, null); + assertEquals(2, count); + } @Test public void testAddNodeItem() throws Exception { @@ -1829,83 +1958,4 @@ private void assertSameNodeItem(NodeItem actual, NodeItem expected) { assertEquals(actual.getNodeId(), expected.getNodeId()); assertEquals(actual.getPayload(), expected.getPayload()); } - - //1277 - @Test - public void testGetRecentItemCount() throws Exception { - - Date since = new Date(); - dbTester.loadData("node_1"); - store.addRemoteNode(TEST_SERVER1_NODE2_ID); - store.addUserSubscription(new NodeSubscriptionImpl(TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, Subscriptions.subscribed)); - - store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE1_ID, "123", new Date(), "payload")); - store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE2_ID, "123", new Date(), "payload2")); - - int count = store.getCountRecentItems(TEST_SERVER1_USER1_JID, since, -1, null); - assertEquals(2, count); - } - - @Test - public void testGetRecentItemCountWithNoResultsPerNodeRequestedReturnsExpectedCount() throws Exception { - Date since = new Date(); - dbTester.loadData("node_1"); - store.addRemoteNode(TEST_SERVER1_NODE2_ID); - store.addUserSubscription(new NodeSubscriptionImpl(TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, Subscriptions.subscribed)); - - store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE1_ID, "123", new Date(), "payload")); - store.addNodeItem(new NodeItemImpl(TEST_SERVER1_NODE2_ID, "123", new Date(), "payload2")); - - int count = store.getCountRecentItems(TEST_SERVER1_USER1_JID, since, 0, null); - assertEquals(0, count); - } - - @Test - public void testGetRecentItems() throws Exception { - - Date since = new Date(); - dbTester.loadData("node_1"); - store.addRemoteNode(TEST_SERVER1_NODE2_ID); - store.addUserSubscription(new NodeSubscriptionImpl(TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, Subscriptions.subscribed)); - - NodeItem nodeItem1 = new NodeItemImpl(TEST_SERVER1_NODE1_ID, "123", new Date(), "payload"); - NodeItem nodeItem2 = new NodeItemImpl(TEST_SERVER1_NODE2_ID, "123", new Date(), "payload2"); - store.addNodeItem(nodeItem1); - store.addNodeItem(nodeItem2); - - CloseableIterator<NodeItem> items = store.getRecentItems(TEST_SERVER1_USER1_JID, since, -1, -1, null, null); - - // 2 -> 1 on purpose results are most recent first! - assertSameNodeItem(items.next(), nodeItem2); - assertSameNodeItem(items.next(), nodeItem1); - assertEquals(false, items.hasNext()); - } - - @Test - public void testGetRecentItemsWithNoResultsPerNodeRequestedReturnsExpectedCount() throws Exception { - Date since = new Date(); - dbTester.loadData("node_1"); - store.addRemoteNode(TEST_SERVER1_NODE2_ID); - store.addUserSubscription(new NodeSubscriptionImpl(TEST_SERVER1_NODE2_ID, TEST_SERVER1_USER1_JID, Subscriptions.subscribed)); - - NodeItem nodeItem1 = new NodeItemImpl(TEST_SERVER1_NODE1_ID, "123", new Date(), "payload"); - NodeItem nodeItem2 = new NodeItemImpl(TEST_SERVER1_NODE2_ID, "123", new Date(), "payload2"); - store.addNodeItem(nodeItem1); - store.addNodeItem(nodeItem2); - - CloseableIterator<NodeItem> items = store.getRecentItems(TEST_SERVER1_USER1_JID, since, 0, -1, null, null); - - int count = 0; - while (items.hasNext()) { - items.next(); - ++count; - } - assertEquals(0, count); - } - - @Test - public void testCanPageGetRecentItemsUsingResultSetManagement() throws Exception { - assertTrue(false); - } - } \ No newline at end of file diff --git a/src/test/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGetTest.java b/src/test/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGetTest.java index 9d0b486c..e376de69 100644 --- a/src/test/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGetTest.java +++ b/src/test/java/org/buddycloud/channelserver/packetprocessor/iq/namespace/pubsub/get/RecentItemsGetTest.java @@ -2,6 +2,9 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; @@ -19,6 +22,7 @@ import org.buddycloud.channelserver.pubsub.model.NodeItem; import org.buddycloud.channelserver.pubsub.model.NodeSubscription; import org.buddycloud.channelserver.pubsub.model.impl.NodeAffiliationImpl; +import org.buddycloud.channelserver.pubsub.model.impl.NodeItemImpl; import org.buddycloud.channelserver.pubsub.model.impl.NodeSubscriptionImpl; import org.buddycloud.channelserver.pubsub.subscription.Subscriptions; import org.buddycloud.channelserver.utils.node.NodeAclRefuseReason; @@ -47,14 +51,20 @@ public class RecentItemsGetTest extends IQTestHandler { private JID jid = new JID("[email protected]"); private ChannelManager channelManager; + private String TEST_NODE_1 = "node1"; + private String TEST_NODE_2 = "node2"; + + private JID TEST_JID_1 = new JID("user1@server1"); + private JID TEST_JID_2 = new JID("user2@server1"); + @Before public void setUp() throws Exception { queue = new LinkedBlockingQueue<Packet>(); channelManager = Mockito.mock(ChannelManager.class); - + recentItemsGet = new RecentItemsGet(queue, channelManager); - + request = readStanzaAsIq("/iq/pubsub/recent-items/request.stanza"); element = new BaseElement("recent-items"); } @@ -72,8 +82,9 @@ public void testPassingNotRecentItemsAsElementNameReturnsFalse() { @Test public void testMissingMaxAttributeReturnsErrorStanza() throws Exception { - - request.getChildElement().element("recent-items").addAttribute("max", null); + + request.getChildElement().element("recent-items") + .addAttribute("max", null); recentItemsGet.process(element, jid, request, null); Packet response = queue.poll(); @@ -81,14 +92,14 @@ public void testMissingMaxAttributeReturnsErrorStanza() throws Exception { PacketError error = response.getError(); Assert.assertNotNull(error); Assert.assertEquals(PacketError.Type.modify, error.getType()); - Assert.assertEquals("max-required", - error.getApplicationConditionName()); + Assert.assertEquals("max-required", error.getApplicationConditionName()); } - + @Test public void testInvalidMaxAttributesReturnsErrorStanza() throws Exception { - - request.getChildElement().element("recent-items").addAttribute("max", "three"); + + request.getChildElement().element("recent-items") + .addAttribute("max", "three"); recentItemsGet.process(element, jid, request, null); Packet response = queue.poll(); @@ -99,11 +110,12 @@ public void testInvalidMaxAttributesReturnsErrorStanza() throws Exception { Assert.assertEquals("invalid-max-value-provided", error.getApplicationConditionName()); } - + @Test public void testMissingSinceAttributeReturnsErrorStanza() throws Exception { - - request.getChildElement().element("recent-items").addAttribute("since", null); + + request.getChildElement().element("recent-items") + .addAttribute("since", null); recentItemsGet.process(element, jid, request, null); Packet response = queue.poll(); @@ -114,11 +126,12 @@ public void testMissingSinceAttributeReturnsErrorStanza() throws Exception { Assert.assertEquals("since-required", error.getApplicationConditionName()); } - + @Test public void testInvalidSinceAttributesReturnsErrorStanza() throws Exception { - - request.getChildElement().element("recent-items").addAttribute("since", "a week ago"); + + request.getChildElement().element("recent-items") + .addAttribute("since", "a week ago"); recentItemsGet.process(element, jid, request, null); Packet response = queue.poll(); @@ -128,6 +141,167 @@ public void testInvalidSinceAttributesReturnsErrorStanza() throws Exception { Assert.assertEquals(PacketError.Type.modify, error.getType()); Assert.assertEquals("invalid-since-value-provided", error.getApplicationConditionName()); - } + } + + @Test + public void testNodeStoreExceptionGeneratesAnErrorStanza() throws Exception { + + Mockito.when( + channelManager.getRecentItems(Mockito.any(JID.class), + Mockito.any(Date.class), Mockito.anyInt(), + Mockito.anyInt(), Mockito.anyString(), + Mockito.anyString())).thenThrow( + new NodeStoreException()); + + recentItemsGet.process(element, jid, request, null); + Packet response = queue.poll(); + + PacketError error = response.getError(); + Assert.assertNotNull(error); + Assert.assertEquals(PacketError.Type.wait, error.getType()); + Assert.assertEquals(PacketError.Condition.internal_server_error, + error.getCondition()); + } + + @Test + public void testNoRecentItemsReturnsEmptyStanza() throws Exception { + + Mockito.when( + channelManager.getRecentItems(Mockito.any(JID.class), + Mockito.any(Date.class), Mockito.anyInt(), + Mockito.anyInt(), Mockito.anyString(), + Mockito.anyString())).thenReturn( + new ClosableIteratorImpl<NodeItem>(new ArrayList<NodeItem>() + .iterator())); + + recentItemsGet.process(element, jid, request, null); + IQ response = (IQ) queue.poll(); + + Assert.assertEquals(IQ.Type.result, response.getType()); + Element pubsub = response.getChildElement(); + Assert.assertEquals("pubsub", pubsub.getName()); + Assert.assertEquals(JabberPubsub.NAMESPACE_URI, + pubsub.getNamespaceURI()); + } + + @Test + public void testOutgoingStanzaFormattedAsExpected() throws Exception { + + NodeItem item1 = new NodeItemImpl(TEST_NODE_1, "1", new Date(), + "<entry>item1</entry>"); + NodeItem item2 = new NodeItemImpl(TEST_NODE_2, "1", new Date(), + "<entry>item2</entry>"); + NodeItem item3 = new NodeItemImpl(TEST_NODE_1, "2", new Date(), + "<entry>item3</entry>"); + NodeItem item4 = new NodeItemImpl(TEST_NODE_1, "3", new Date(), + "<entry>item4</entry>"); + + ArrayList<NodeItem> results = new ArrayList<NodeItem>(); + results.add(item1); + results.add(item2); + results.add(item3); + results.add(item4); + + Mockito.when( + channelManager.getRecentItems(Mockito.any(JID.class), + Mockito.any(Date.class), Mockito.anyInt(), + Mockito.anyInt(), Mockito.anyString(), + Mockito.anyString())).thenReturn( + new ClosableIteratorImpl<NodeItem>(results.iterator())); + + recentItemsGet.process(element, jid, request, null); + IQ response = (IQ) queue.poll(); + + Assert.assertEquals(IQ.Type.result, response.getType()); + Element pubsub = response.getChildElement(); + Assert.assertEquals("pubsub", pubsub.getName()); + Assert.assertEquals(JabberPubsub.NAMESPACE_URI, + pubsub.getNamespaceURI()); + + List<Element> items = pubsub.elements("items"); + Assert.assertEquals(3, items.size()); + + Assert.assertEquals(TEST_NODE_1, items.get(0).attributeValue("node")); + Assert.assertEquals(TEST_NODE_2, items.get(1).attributeValue("node")); + Assert.assertEquals(TEST_NODE_1, items.get(2).attributeValue("node")); + + Assert.assertEquals(1, items.get(0).elements("item").size()); + Assert.assertEquals(2, items.get(2).elements("item").size()); + } + + @Test + public void testUnparsableItemEntriesAreSimplyIgnored() throws Exception { + + NodeItem item1 = new NodeItemImpl(TEST_NODE_1, "1", new Date(), + "<entry>item1</entry>"); + NodeItem item2 = new NodeItemImpl(TEST_NODE_1, "2", new Date(), + "<entry>item2"); + + ArrayList<NodeItem> results = new ArrayList<NodeItem>(); + results.add(item1); + results.add(item2); + + Mockito.when( + channelManager.getRecentItems(Mockito.any(JID.class), + Mockito.any(Date.class), Mockito.anyInt(), + Mockito.anyInt(), Mockito.anyString(), + Mockito.anyString())).thenReturn( + new ClosableIteratorImpl<NodeItem>(results.iterator())); + recentItemsGet.process(element, jid, request, null); + IQ response = (IQ) queue.poll(); + Assert.assertEquals(1, response.getChildElement().element("items") + .elements("item").size()); + } + + @Test + public void testCanControlGatheredEntriesUsingRsm() throws Exception { + + NodeItem item2 = new NodeItemImpl(TEST_NODE_2, "node2:1", new Date(), + "<entry>item2</entry>"); + NodeItem item3 = new NodeItemImpl(TEST_NODE_1, "node1:2", new Date(), + "<entry>item3</entry>"); + + ArrayList<NodeItem> results = new ArrayList<NodeItem>(); + results.add(item2); + results.add(item3); + + Mockito.when( + channelManager.getRecentItems(Mockito.any(JID.class), + Mockito.any(Date.class), Mockito.anyInt(), + Mockito.anyInt(), Mockito.anyString(), + Mockito.anyString())).thenReturn( + new ClosableIteratorImpl<NodeItem>(results.iterator())); + Mockito.when( + channelManager.getCountRecentItems(Mockito.any(JID.class), + Mockito.any(Date.class), Mockito.anyInt(), + Mockito.anyString())).thenReturn(2); + + Element rsm = request.getElement().addElement("rsm"); + rsm.addNamespace("", recentItemsGet.NS_RSM); + rsm.addElement("max").addText("2"); + rsm.addElement("after").addText("node1:1"); + + recentItemsGet.process(element, jid, request, null); + IQ response = (IQ) queue.poll(); + + Assert.assertEquals(IQ.Type.result, response.getType()); + Element pubsub = response.getChildElement(); + Assert.assertEquals("pubsub", pubsub.getName()); + Assert.assertEquals(JabberPubsub.NAMESPACE_URI, + pubsub.getNamespaceURI()); + + List<Element> items = pubsub.elements("items"); + Assert.assertEquals(2, items.size()); + + Assert.assertEquals(TEST_NODE_2, items.get(0).attributeValue("node")); + Assert.assertEquals(TEST_NODE_1, items.get(1).attributeValue("node")); + Assert.assertEquals(1, items.get(0).elements("item").size()); + Assert.assertEquals(1, items.get(1).elements("item").size()); + + Element rsmResult = pubsub.element("set"); + Assert.assertEquals("2", rsmResult.element("count").getText()); + Assert.assertEquals("node2:1", rsmResult.element("first").getText()); + Assert.assertEquals("node1:2", rsmResult.element("last").getText()); + } } \ No newline at end of file
c681d992e2faa5fe72494d96afa466dd8d7fc329
agorava$agorava-core
AGOVA-52 Support to programmatically control callback URL per auth request Added support of Internal Callback. Callback servlet uses it now to redirect internaly
a
https://github.com/agorava/agorava-core
diff --git a/agorava-core-api/src/main/java/org/agorava/AgoravaContext.java b/agorava-core-api/src/main/java/org/agorava/AgoravaContext.java index 6ecfd19..4704f0d 100644 --- a/agorava-core-api/src/main/java/org/agorava/AgoravaContext.java +++ b/agorava-core-api/src/main/java/org/agorava/AgoravaContext.java @@ -50,6 +50,8 @@ public class AgoravaContext { private static List<String> listOfServices = null; + protected static String internalCallBack; + /** * @return the way that {@link org.agorava.api.oauth.OAuthSession} and {@link org.agorava.api.storage @@ -102,4 +104,11 @@ public static List<String> getListOfServices() { listOfServices = new ArrayList<String>(getSocialRelated()); return listOfServices; } + + /** + * @return the relative url of the default page to return after an OAuth callback + */ + public static String getInternalCallBack() { + return internalCallBack; + } } diff --git a/agorava-core-api/src/main/java/org/agorava/api/oauth/OAuthConstants.java b/agorava-core-api/src/main/java/org/agorava/api/AgoravaConstants.java similarity index 81% rename from agorava-core-api/src/main/java/org/agorava/api/oauth/OAuthConstants.java rename to agorava-core-api/src/main/java/org/agorava/api/AgoravaConstants.java index 36f277a..eafbaa6 100644 --- a/agorava-core-api/src/main/java/org/agorava/api/oauth/OAuthConstants.java +++ b/agorava-core-api/src/main/java/org/agorava/api/AgoravaConstants.java @@ -14,15 +14,16 @@ * limitations under the License. */ -package org.agorava.api.oauth; +package org.agorava.api; + +import org.agorava.api.oauth.Token; /** - * This interface contains OAuth constants, used project-wide + * This interface contains OAuth and other Agorava constants * - * @author Pablo Fernandez * @author Antoine Sabot-Durand */ -public interface OAuthConstants { +public interface AgoravaConstants { /** * Time stamp field name in OAuth request */ @@ -126,9 +127,21 @@ public interface OAuthConstants { String REDIRECT_URI = "redirect_uri"; /** - * Returned code field name in OAuth request + * Return code field name in OAuth request */ String CODE = "code"; + /** + * default OAuth Callback relative url to send user when returning from OAuth service. It's used in {@link org.agorava + * .api.oauth.application.SimpleOAuthAppSettingsBuilder} + * to provide a default callback. + */ + String CALLBACK_URL = "callback"; + + /** + * parameter name to store internal callback in url + */ + String INTERN_CALLBACK_PARAM_NAME = "internalcallback"; + } diff --git a/agorava-core-api/src/main/java/org/agorava/api/oauth/Token.java b/agorava-core-api/src/main/java/org/agorava/api/oauth/Token.java index cf32583..4dc1c59 100644 --- a/agorava-core-api/src/main/java/org/agorava/api/oauth/Token.java +++ b/agorava-core-api/src/main/java/org/agorava/api/oauth/Token.java @@ -16,6 +16,7 @@ package org.agorava.api.oauth; +import org.agorava.api.AgoravaConstants; import org.agorava.api.service.Preconditions; import java.io.Serializable; @@ -69,7 +70,7 @@ public String toString() { * @return true if the token is empty (token = "", secret = "") */ public boolean isEmpty() { - return equals(OAuthConstants.EMPTY_TOKEN); + return equals(AgoravaConstants.EMPTY_TOKEN); } @Override diff --git a/agorava-core-api/src/main/java/org/agorava/api/oauth/application/SimpleOAuthAppSettingsBuilder.java b/agorava-core-api/src/main/java/org/agorava/api/oauth/application/SimpleOAuthAppSettingsBuilder.java index 2a0328c..6b0dd07 100644 --- a/agorava-core-api/src/main/java/org/agorava/api/oauth/application/SimpleOAuthAppSettingsBuilder.java +++ b/agorava-core-api/src/main/java/org/agorava/api/oauth/application/SimpleOAuthAppSettingsBuilder.java @@ -17,6 +17,7 @@ package org.agorava.api.oauth.application; import org.agorava.AgoravaContext; +import org.agorava.api.AgoravaConstants; import org.agorava.api.exception.AgoravaException; import java.lang.annotation.Annotation; @@ -35,7 +36,7 @@ public class SimpleOAuthAppSettingsBuilder implements OAuthAppSettingsBuilder { private String apiSecret; - private String callback = "oob"; + private String callback; private String scope = ""; @@ -77,7 +78,10 @@ public SimpleOAuthAppSettingsBuilder apiSecret(String apiSecret) { * {@inheritDoc} * This implementation add a check to callback. If it's not 'oob' and doesn't start with 'http://' * it'll try to get the path of the current application to dynamically create a return URL when - * connection on remote Media is over. + * connection on Oauth service is over. + * As some service build the Callback URL from domain name configured when the OAuth application is created (for security + * reasons), whe should make the distinction between relative URL that should be prefixed here (without a beginning "/") + * and relative url that will prefixed by remote service (with a beginning "/") * * @param callback a callback url or 'oob' if the application is not on the web * @return this builder @@ -100,6 +104,8 @@ public SimpleOAuthAppSettingsBuilder scope(String scope) { @Override public OAuthAppSettings build() { + if (callback == null) + callback(AgoravaConstants.CALLBACK_URL); return new OAuthAppSettings(name, apiKey, apiSecret, callback, scope, qualifier); } diff --git a/agorava-core-api/src/main/java/org/agorava/api/service/Preconditions.java b/agorava-core-api/src/main/java/org/agorava/api/service/Preconditions.java index 4f1364f..78efcda 100644 --- a/agorava-core-api/src/main/java/org/agorava/api/service/Preconditions.java +++ b/agorava-core-api/src/main/java/org/agorava/api/service/Preconditions.java @@ -16,7 +16,7 @@ package org.agorava.api.service; -import org.agorava.api.oauth.OAuthConstants; +import org.agorava.api.AgoravaConstants; import java.util.regex.Pattern; @@ -78,12 +78,12 @@ public static void checkValidUrl(String url, String errorMsg) { */ public static void checkValidOAuthCallback(String url, String errorMsg) { checkEmptyString(url, errorMsg); - if (url.toLowerCase(ENGLISH).compareToIgnoreCase(OAuthConstants.OUT_OF_BAND) != 0) { + if (url.toLowerCase(ENGLISH).compareToIgnoreCase(AgoravaConstants.OUT_OF_BAND) != 0) { check(isUrl(url), errorMsg); } } - private static boolean isUrl(String url) { + public static boolean isUrl(String url) { return URL_PATTERN.matcher(url).matches(); } diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java index 0a548de..896072c 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java @@ -17,6 +17,7 @@ package org.agorava.cdi.extensions; import org.agorava.AgoravaContext; +import org.agorava.api.AgoravaConstants; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.atinject.ProviderRelated; import org.agorava.api.exception.AgoravaException; @@ -336,6 +337,11 @@ public void endOfExtension(@Observes AfterDeploymentValidation adv, BeanManager new BeanResolverCdi(); producerScope = ConfigResolver.getPropertyValue("producerScope", ""); + internalCallBack = ConfigResolver.getPropertyValue(AgoravaConstants.INTERN_CALLBACK_PARAM_NAME); + if (internalCallBack == null) { + log.warning("No internal callback defined, it's defaulted to home page"); + internalCallBack = "/"; + } log.info("Agorava initialization complete"); } diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java index 6b44c8b..13bfeb4 100644 --- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java +++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java @@ -16,10 +16,10 @@ package org.agorava.oauth; +import org.agorava.api.AgoravaConstants; import org.agorava.api.atinject.GenericBean; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.oauth.OAuth; -import org.agorava.api.oauth.OAuthConstants; import org.agorava.api.oauth.OAuthRequest; import org.agorava.api.oauth.Token; import org.agorava.api.oauth.Verifier; @@ -65,14 +65,14 @@ public Token getRequestToken() { @Override public String getVerifierParamName() { - return OAuthConstants.VERIFIER; + return AgoravaConstants.VERIFIER; } @Override public String getAuthorizationUrl() { - Token req = getRequestToken(); - getSession().setRequestToken(req); - return getAuthorizationUrl(req); + Token token = getRequestToken(); + getSession().setRequestToken(token); + return getAuthorizationUrl(token); } public Token getRequestToken(RequestTuner tuner) { @@ -82,8 +82,8 @@ public Token getRequestToken(RequestTuner tuner) { OAuthRequest request = requestFactory(api.getRequestTokenVerb(), api.getRequestTokenEndpoint()); LOGGER.fine("setting oauth_callback to " + config.getCallback()); - request.addOAuthParameter(OAuthConstants.CALLBACK, config.getCallback()); - addOAuthParams(request, OAuthConstants.EMPTY_TOKEN); + request.addOAuthParameter(AgoravaConstants.CALLBACK, config.getCallback()); + addOAuthParams(request, AgoravaConstants.EMPTY_TOKEN); appendSignature(request); LOGGER.fine("sending request..."); @@ -97,13 +97,13 @@ public Token getRequestToken(RequestTuner tuner) { } private void addOAuthParams(OAuthRequest request, Token token) { - request.addOAuthParameter(OAuthConstants.TIMESTAMP, api.getTimestampService().getTimestampInSeconds()); - request.addOAuthParameter(OAuthConstants.NONCE, api.getTimestampService().getNonce()); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, config.getApiKey()); - request.addOAuthParameter(OAuthConstants.SIGN_METHOD, api.getSignatureService().getSignatureMethod()); - request.addOAuthParameter(OAuthConstants.VERSION, getVersion()); - if (config.hasScope()) request.addOAuthParameter(OAuthConstants.SCOPE, config.getScope()); - request.addOAuthParameter(OAuthConstants.SIGNATURE, getSignature(request, token)); + request.addOAuthParameter(AgoravaConstants.TIMESTAMP, api.getTimestampService().getTimestampInSeconds()); + request.addOAuthParameter(AgoravaConstants.NONCE, api.getTimestampService().getNonce()); + request.addOAuthParameter(AgoravaConstants.CONSUMER_KEY, config.getApiKey()); + request.addOAuthParameter(AgoravaConstants.SIGN_METHOD, api.getSignatureService().getSignatureMethod()); + request.addOAuthParameter(AgoravaConstants.VERSION, getVersion()); + if (config.hasScope()) request.addOAuthParameter(AgoravaConstants.SCOPE, config.getScope()); + request.addOAuthParameter(AgoravaConstants.SIGNATURE, getSignature(request, token)); LOGGER.fine("appended additional OAuth parameters: " + MapUtils.toString(request.getOauthParameters())); } @@ -122,8 +122,8 @@ public Token getAccessToken(Token requestToken, Verifier verifier) { public Token getAccessToken(Token requestToken, Verifier verifier, RequestTuner tuner) { LOGGER.fine("obtaining access token from " + api.getAccessTokenEndpoint()); OAuthRequest request = requestFactory(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); - request.addOAuthParameter(OAuthConstants.TOKEN, requestToken.getToken()); - request.addOAuthParameter(OAuthConstants.VERIFIER, verifier.getValue()); + request.addOAuthParameter(AgoravaConstants.TOKEN, requestToken.getToken()); + request.addOAuthParameter(AgoravaConstants.VERIFIER, verifier.getValue()); LOGGER.fine("setting token to: " + requestToken + " and verifier to: " + verifier); addOAuthParams(request, requestToken); @@ -141,7 +141,7 @@ public void signRequest(Token token, OAuthRequest request) { // Do not append the token if empty. This is for two legged OAuth calls. if (!token.isEmpty()) { - request.addOAuthParameter(OAuthConstants.TOKEN, token.getToken()); + request.addOAuthParameter(AgoravaConstants.TOKEN, token.getToken()); } LOGGER.fine("setting token to: " + token); addOAuthParams(request, token); @@ -178,7 +178,7 @@ private void appendSignature(OAuthRequest request) { LOGGER.fine("using Http HEADER signature"); String oauthHeader = api.getHeaderExtractor().extract(request); - request.addHeader(OAuthConstants.HEADER, oauthHeader); + request.addHeader(AgoravaConstants.HEADER, oauthHeader); break; case QUERY_STRING: LOGGER.fine("using Querystring signature"); diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java index b082ba7..7f24887 100644 --- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java +++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java @@ -16,10 +16,10 @@ package org.agorava.oauth; +import org.agorava.api.AgoravaConstants; import org.agorava.api.atinject.GenericBean; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.oauth.OAuth; -import org.agorava.api.oauth.OAuthConstants; import org.agorava.api.oauth.OAuthRequest; import org.agorava.api.oauth.Token; import org.agorava.api.oauth.Verifier; @@ -48,12 +48,12 @@ public class OAuth20FinalServiceImpl extends OAuth20ServiceImpl { @Override public Token getAccessToken(Token requestToken, Verifier verifier) { OAuthRequest request = new OAuthRequestImpl(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); - request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); - request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); - request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); - request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); + request.addBodyParameter(AgoravaConstants.CLIENT_ID, config.getApiKey()); + request.addBodyParameter(AgoravaConstants.CLIENT_SECRET, config.getApiSecret()); + request.addBodyParameter(AgoravaConstants.CODE, verifier.getValue()); + request.addBodyParameter(AgoravaConstants.REDIRECT_URI, config.getCallback()); request.addBodyParameter("grant_type", "authorization_code"); - if (config.hasScope()) request.addBodyParameter(OAuthConstants.SCOPE, config.getScope()); + if (config.hasScope()) request.addBodyParameter(AgoravaConstants.SCOPE, config.getScope()); Response response = request.send(); //todo:should check return code and launch ResponseException if it's not 200 return api.getAccessTokenExtractor().extract(response.getBody()); } diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java index e770365..025dfb5 100644 --- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java +++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java @@ -17,10 +17,10 @@ package org.agorava.oauth; +import org.agorava.api.AgoravaConstants; import org.agorava.api.atinject.GenericBean; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.oauth.OAuth; -import org.agorava.api.oauth.OAuthConstants; import org.agorava.api.oauth.OAuthRequest; import org.agorava.api.oauth.Token; import org.agorava.api.oauth.Verifier; @@ -45,11 +45,11 @@ public class OAuth20ServiceImpl extends OAuthServiceBase { public Token getAccessToken(Token requestToken, Verifier verifier) { OAuthAppSettings config = getTunedOAuthAppSettings(); OAuthRequest request = new OAuthRequestImpl(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); - request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); - request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); - request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue()); - request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); - if (config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope()); + request.addQuerystringParameter(AgoravaConstants.CLIENT_ID, config.getApiKey()); + request.addQuerystringParameter(AgoravaConstants.CLIENT_SECRET, config.getApiSecret()); + request.addQuerystringParameter(AgoravaConstants.CODE, verifier.getValue()); + request.addQuerystringParameter(AgoravaConstants.REDIRECT_URI, config.getCallback()); + if (config.hasScope()) request.addQuerystringParameter(AgoravaConstants.SCOPE, config.getScope()); Response response = request.send(); //todo:should check return code and launch ResponseException if it's not 200 return api.getAccessTokenExtractor().extract(response.getBody()); } @@ -73,13 +73,13 @@ public String getVersion() { * {@inheritDoc} */ public void signRequest(Token accessToken, OAuthRequest request) { - request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken()); + request.addQuerystringParameter(AgoravaConstants.ACCESS_TOKEN, accessToken.getToken()); } @Override public String getVerifierParamName() { - return OAuthConstants.CODE; + return AgoravaConstants.CODE; } @Override diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuthServiceBase.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuthServiceBase.java index 1bb4682..c6d2f62 100644 --- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuthServiceBase.java +++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuthServiceBase.java @@ -234,7 +234,7 @@ public Token getAccessToken(Token requestToken, String verifier) { protected OAuthAppSettings getTunedOAuthAppSettings() { AppSettingsTuner tuner = BeanResolver.getInstance().resolve(AppSettingsTuner.class, true); - return tuner == null ? this.config : tuner.tune(this.config); + return tuner == null ? config : tuner.tune(config); } } diff --git a/agorava-core-impl/src/main/java/org/agorava/rest/OAuthRequestImpl.java b/agorava-core-impl/src/main/java/org/agorava/rest/OAuthRequestImpl.java index c0c4b6b..e1db038 100644 --- a/agorava-core-impl/src/main/java/org/agorava/rest/OAuthRequestImpl.java +++ b/agorava-core-impl/src/main/java/org/agorava/rest/OAuthRequestImpl.java @@ -16,7 +16,7 @@ package org.agorava.rest; -import org.agorava.api.oauth.OAuthConstants; +import org.agorava.api.AgoravaConstants; import org.agorava.api.oauth.OAuthRequest; import org.agorava.api.rest.Verb; @@ -52,11 +52,11 @@ public void addOAuthParameter(String key, String value) { } private String checkKey(String key) { - if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) { + if (key.startsWith(OAUTH_PREFIX) || key.equals(AgoravaConstants.SCOPE)) { return key; } else { throw new IllegalArgumentException(String.format("OAuth parameters must either be '%s' or start with '%s'", - OAuthConstants.SCOPE, OAUTH_PREFIX)); + AgoravaConstants.SCOPE, OAUTH_PREFIX)); } } diff --git a/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java b/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java index ec341ba..a83c20b 100644 --- a/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java +++ b/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java @@ -16,12 +16,13 @@ package org.agorava.servlet; +import org.agorava.AgoravaContext; +import org.agorava.api.AgoravaConstants; import org.agorava.api.exception.AgoravaException; import org.agorava.api.service.OAuthLifeCycleService; import javax.inject.Inject; import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -37,22 +38,19 @@ public class OAuthCallbackServlet extends HttpServlet { OAuthLifeCycleService OAuthLifeCycleService; protected void renderResponse(HttpServletRequest req, HttpServletResponse resp) { - ServletOutputStream os = null; + + String internalCallBack = req.getParameter(AgoravaConstants.INTERN_CALLBACK_PARAM_NAME); + if (internalCallBack == null) + internalCallBack = AgoravaContext.getInternalCallBack(); + try { - os = resp.getOutputStream(); - os.println("<script type=\"text/javascript\">"); - os.println("function moveOn() {\n" + - " window.opener.location.reload();\n" + - " window.close();\n" + - " }\n" + - "moveOn();"); - os.println("</script>"); - os.flush(); - os.close(); + if (internalCallBack.startsWith("/")) + internalCallBack = req.getContextPath() + internalCallBack; + internalCallBack = resp.encodeRedirectURL(internalCallBack + "?" + req.getQueryString()); + resp.sendRedirect(internalCallBack); } catch (IOException e) { throw new AgoravaException(e); } - } @Override diff --git a/agorava-core-impl/src/test/java/org/agorava/core/mock/ObjectMother.java b/agorava-core-impl/src/test/java/org/agorava/core/mock/ObjectMother.java index f613ca9..5ee29a6 100644 --- a/agorava-core-impl/src/test/java/org/agorava/core/mock/ObjectMother.java +++ b/agorava-core-impl/src/test/java/org/agorava/core/mock/ObjectMother.java @@ -17,7 +17,7 @@ package org.agorava.core.mock; -import org.agorava.api.oauth.OAuthConstants; +import org.agorava.api.AgoravaConstants; import org.agorava.api.oauth.OAuthRequest; import org.agorava.api.rest.Verb; import org.agorava.rest.OAuthRequestImpl; @@ -26,10 +26,10 @@ public class ObjectMother { public static OAuthRequest createSampleOAuthRequest() { OAuthRequest request = new OAuthRequestImpl(Verb.GET, "http://example.com"); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456"); - request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&"); - request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback"); - request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature"); + request.addOAuthParameter(AgoravaConstants.TIMESTAMP, "123456"); + request.addOAuthParameter(AgoravaConstants.CONSUMER_KEY, "AS#$^*@&"); + request.addOAuthParameter(AgoravaConstants.CALLBACK, "http://example/callback"); + request.addOAuthParameter(AgoravaConstants.SIGNATURE, "OAuth-Signature"); return request; } } diff --git a/agorava-core-impl/src/test/java/org/agorava/rest/OAuthRequestTest.java b/agorava-core-impl/src/test/java/org/agorava/rest/OAuthRequestTest.java index 8a09d8f..a1a4c65 100644 --- a/agorava-core-impl/src/test/java/org/agorava/rest/OAuthRequestTest.java +++ b/agorava-core-impl/src/test/java/org/agorava/rest/OAuthRequestTest.java @@ -16,7 +16,7 @@ package org.agorava.rest; -import org.agorava.api.oauth.OAuthConstants; +import org.agorava.api.AgoravaConstants; import org.agorava.api.oauth.OAuthRequest; import org.agorava.api.rest.Verb; import org.junit.Before; @@ -35,10 +35,10 @@ public void setup() { @Test public void shouldAddOAuthParamters() { - request.addOAuthParameter(OAuthConstants.TOKEN, "token"); - request.addOAuthParameter(OAuthConstants.NONCE, "nonce"); - request.addOAuthParameter(OAuthConstants.TIMESTAMP, "ts"); - request.addOAuthParameter(OAuthConstants.SCOPE, "feeds"); + request.addOAuthParameter(AgoravaConstants.TOKEN, "token"); + request.addOAuthParameter(AgoravaConstants.NONCE, "nonce"); + request.addOAuthParameter(AgoravaConstants.TIMESTAMP, "ts"); + request.addOAuthParameter(AgoravaConstants.SCOPE, "feeds"); assertEquals(4, request.getOauthParameters().size()); }
780ca0263ac1b5a564fc4cfef6e6b7a3969689e5
Vala
json-glib-1.0: always include json-glib.h Fixes bug 605924.
c
https://github.com/GNOME/vala/
diff --git a/vapi/json-glib-1.0.vapi b/vapi/json-glib-1.0.vapi index 4d9cd55870..bc9d852f5c 100644 --- a/vapi/json-glib-1.0.vapi +++ b/vapi/json-glib-1.0.vapi @@ -129,7 +129,7 @@ namespace Json { public virtual signal void parse_end (); public virtual signal void parse_start (); } - [CCode (cheader_filename = "json-glib/json-gobject.h")] + [CCode (cheader_filename = "json-glib/json-glib.h,json-glib/json-gobject.h")] public interface Serializable { public bool default_deserialize_property (string property_name, GLib.Value value, GLib.ParamSpec pspec, Json.Node property_node); public unowned Json.Node default_serialize_property (string property_name, GLib.Value value, GLib.ParamSpec pspec); @@ -178,7 +178,7 @@ namespace Json { public static void boxed_register_serialize_func (GLib.Type gboxed_type, Json.NodeType node_type, Json.BoxedSerializeFunc serialize_func); [CCode (cheader_filename = "json-glib/json-glib.h")] public static unowned Json.Node boxed_serialize (GLib.Type gboxed_type, void* boxed); - [CCode (cheader_filename = "json-glib/json-gobject.h")] + [CCode (cheader_filename = "json-glib/json-glib.h,json-glib/json-gobject.h")] public static GLib.Object construct_gobject (GLib.Type gtype, string data, size_t length) throws GLib.Error; [CCode (cheader_filename = "json-glib/json-glib.h")] public static unowned GLib.Object gobject_deserialize (GLib.Type gtype, Json.Node node); @@ -188,6 +188,6 @@ namespace Json { public static unowned Json.Node gobject_serialize (GLib.Object gobject); [CCode (cheader_filename = "json-glib/json-glib.h")] public static string gobject_to_data (GLib.Object gobject, out size_t length); - [CCode (cheader_filename = "json-glib/json-gobject.h")] + [CCode (cheader_filename = "json-glib/json-glib.h,json-glib/json-gobject.h")] public static string serialize_gobject (GLib.Object gobject, out size_t length); } diff --git a/vapi/packages/json-glib-1.0/json-glib-1.0.metadata b/vapi/packages/json-glib-1.0/json-glib-1.0.metadata index fc327b10df..ac5145154c 100644 --- a/vapi/packages/json-glib-1.0/json-glib-1.0.metadata +++ b/vapi/packages/json-glib-1.0/json-glib-1.0.metadata @@ -1,12 +1,12 @@ -Json cheader_filename="json-glib/json-glib.h" -JsonSerializable cheader_filename="json-glib/json-gobject.h" +Json* cheader_filename="json-glib/json-glib.h" +JsonSerializable cheader_filename="json-glib/json-glib.h,json-glib/json-gobject.h" json_generator_to_data transfer_ownership="1" json_generator_to_data.length is_out="1" json_parser_has_assignment.variable_name is_out="1" json_serializable_deserialize_property.value is_out="1" json_serializable_serialize_property transfer_ownership="1" -json_construct_gobject cheader_filename="json-glib/json-gobject.h" transfer_ownership="1" -json_serialize_gobject cheader_filename="json-glib/json-gobject.h" transfer_ownership="1" +json_construct_gobject cheader_filename="json-glib/json-glib.h,json-glib/json-gobject.h" transfer_ownership="1" +json_serialize_gobject cheader_filename="json-glib/json-glib.h,json-glib/json-gobject.h" transfer_ownership="1" json_serialize_gobject.length is_out="1" json_array_add_array_element.value transfer_ownership="1" json_array_add_element.node transfer_ownership="1"
9ff594fefd42a9a3e0f3c8fc442910e7d4df6223
tapiji
Adds missing license headers and lifts epl-v10.html from project scope to repository scope According to the guide for legal documentation missing license headers have been added. Moreover, license files in project/plugin scope are only required if a non-standard about.html is used. Therefore, they have been lifted to the root directory. (cherry picked from commit b7a6b2bf441fd708704db1159c13cbce92600b4d)
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.core/epl-v10.html b/epl-v10.html similarity index 100% rename from org.eclipse.babel.tapiji.tools.core/epl-v10.html rename to epl-v10.html diff --git a/org.eclipse.babel.core.pdeutils/epl-v10.html b/org.eclipse.babel.core.pdeutils/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipse.babel.core.pdeutils/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.core.pdeutils/pom.xml b/org.eclipse.babel.core.pdeutils/pom.xml index 6b36761a..1bb48e94 100644 --- a/org.eclipse.babel.core.pdeutils/pom.xml +++ b/org.eclipse.babel.core.pdeutils/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.core/pom.xml b/org.eclipse.babel.core/pom.xml index 6d489db3..fa6b66ab 100644 --- a/org.eclipse.babel.core/pom.xml +++ b/org.eclipse.babel.core/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.editor.nls/pom.xml b/org.eclipse.babel.editor.nls/pom.xml index 944ae3fe..54fb8398 100644 --- a/org.eclipse.babel.editor.nls/pom.xml +++ b/org.eclipse.babel.editor.nls/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.editor/pom.xml b/org.eclipse.babel.editor/pom.xml index 5d18d7e8..3a087ae4 100644 --- a/org.eclipse.babel.editor/pom.xml +++ b/org.eclipse.babel.editor/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html b/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/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.core.ui/pom.xml b/org.eclipse.babel.tapiji.tools.core.ui/pom.xml index bdbd652f..bad9401e 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/pom.xml +++ b/org.eclipse.babel.tapiji.tools.core.ui/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.tapiji.tools.core/pom.xml b/org.eclipse.babel.tapiji.tools.core/pom.xml index f24f28fc..96ff5d17 100644 --- a/org.eclipse.babel.tapiji.tools.core/pom.xml +++ b/org.eclipse.babel.tapiji.tools.core/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.tapiji.tools.java.feature/epl-v10.html b/org.eclipse.babel.tapiji.tools.java.feature/epl-v10.html deleted file mode 100644 index ed4b1966..00000000 --- a/org.eclipse.babel.tapiji.tools.java.feature/epl-v10.html +++ /dev/null @@ -1,328 +0,0 @@ -<html xmlns:o="urn:schemas-microsoft-com:office:office" -xmlns:w="urn:schemas-microsoft-com:office:word" -xmlns="http://www.w3.org/TR/REC-html40"> - -<head> -<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> -<meta name=ProgId content=Word.Document> -<meta name=Generator content="Microsoft Word 9"> -<meta name=Originator content="Microsoft Word 9"> -<link rel=File-List -href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> -<title>Eclipse Public License - Version 1.0</title> -<!--[if gte mso 9]><xml> - <o:DocumentProperties> - <o:Revision>2</o:Revision> - <o:TotalTime>3</o:TotalTime> - <o:Created>2004-03-05T23:03:00Z</o:Created> - <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> - <o:Pages>4</o:Pages> - <o:Words>1626</o:Words> - <o:Characters>9270</o:Characters> - <o:Lines>77</o:Lines> - <o:Paragraphs>18</o:Paragraphs> - <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> - <o:Version>9.4402</o:Version> - </o:DocumentProperties> -</xml><![endif]--><!--[if gte mso 9]><xml> - <w:WordDocument> - <w:TrackRevisions/> - </w:WordDocument> -</xml><![endif]--> -<style> -<!-- - /* Font Definitions */ -@font-face - {font-family:Tahoma; - panose-1:2 11 6 4 3 5 4 4 2 4; - mso-font-charset:0; - mso-generic-font-family:swiss; - mso-font-pitch:variable; - mso-font-signature:553679495 -2147483648 8 0 66047 0;} - /* Style Definitions */ -p.MsoNormal, li.MsoNormal, div.MsoNormal - {mso-style-parent:""; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p - {margin-right:0in; - mso-margin-top-alt:auto; - mso-margin-bottom-alt:auto; - margin-left:0in; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p.BalloonText, li.BalloonText, div.BalloonText - {mso-style-name:"Balloon Text"; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:8.0pt; - font-family:Tahoma; - mso-fareast-font-family:"Times New Roman";} -@page Section1 - {size:8.5in 11.0in; - margin:1.0in 1.25in 1.0in 1.25in; - mso-header-margin:.5in; - mso-footer-margin:.5in; - mso-paper-source:0;} -div.Section1 - {page:Section1;} ---> -</style> -</head> - -<body lang=EN-US style='tab-interval:.5in'> - -<div class=Section1> - -<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> -</p> - -<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER -THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, -REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE -OF THIS AGREEMENT.</span> </p> - -<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> - -<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -in the case of the initial Contributor, the initial code and documentation -distributed under this Agreement, and<br clear=left> -b) in the case of each subsequent Contributor:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) -changes to the Program, and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -additions to the Program;</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where -such changes and/or additions to the Program originate from and are distributed -by that particular Contributor. A Contribution 'originates' from a Contributor -if it was added to the Program by such Contributor itself or anyone acting on -such Contributor's behalf. Contributions do not include additions to the -Program which: (i) are separate modules of software distributed in conjunction -with the Program under their own license agreement, and (ii) are not derivative -works of the Program. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or -entity that distributes the Program.</span> </p> - -<p><span style='font-size:10.0pt'>&quot;Licensed Patents &quot; mean patent -claims licensable by a Contributor which are necessarily infringed by the use -or sale of its Contribution alone or when combined with the Program. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions -distributed in accordance with this Agreement.</span> </p> - -<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who -receives the Program under this Agreement, including all Contributors.</span> </p> - -<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -Subject to the terms of this Agreement, each Contributor hereby grants Recipient -a non-exclusive, worldwide, royalty-free copyright license to<span -style='color:red'> </span>reproduce, prepare derivative works of, publicly -display, publicly perform, distribute and sublicense the Contribution of such -Contributor, if any, and such derivative works, in source code and object code -form.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -Subject to the terms of this Agreement, each Contributor hereby grants -Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free -patent license under Licensed Patents to make, use, sell, offer to sell, import -and otherwise transfer the Contribution of such Contributor, if any, in source -code and object code form. This patent license shall apply to the combination -of the Contribution and the Program if, at the time the Contribution is added -by the Contributor, such addition of the Contribution causes such combination -to be covered by the Licensed Patents. The patent license shall not apply to -any other combinations which include the Contribution. No hardware per se is -licensed hereunder. </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c) -Recipient understands that although each Contributor grants the licenses to its -Contributions set forth herein, no assurances are provided by any Contributor -that the Program does not infringe the patent or other intellectual property -rights of any other entity. Each Contributor disclaims any liability to Recipient -for claims brought by any other entity based on infringement of intellectual -property rights or otherwise. As a condition to exercising the rights and -licenses granted hereunder, each Recipient hereby assumes sole responsibility -to secure any other intellectual property rights needed, if any. For example, -if a third party patent license is required to allow Recipient to distribute -the Program, it is Recipient's responsibility to acquire that license before -distributing the Program.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d) -Each Contributor represents that to its knowledge it has sufficient copyright -rights in its Contribution, if any, to grant the copyright license set forth in -this Agreement. </span></p> - -<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> - -<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the -Program in object code form under its own license agreement, provided that:</span> -</p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it complies with the terms and conditions of this Agreement; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -its license agreement:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) -effectively disclaims on behalf of all Contributors all warranties and -conditions, express and implied, including warranties or conditions of title -and non-infringement, and implied warranties or conditions of merchantability -and fitness for a particular purpose; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -effectively excludes on behalf of all Contributors all liability for damages, -including direct, indirect, special, incidental and consequential damages, such -as lost profits; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) -states that any provisions which differ from this Agreement are offered by that -Contributor alone and not by any other party; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv) -states that source code for the Program is available from such Contributor, and -informs licensees how to obtain it in a reasonable manner on or through a -medium customarily used for software exchange.<span style='color:blue'> </span></span></p> - -<p><span style='font-size:10.0pt'>When the Program is made available in source -code form:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it must be made available under this Agreement; and </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a -copy of this Agreement must be included with each copy of the Program. </span></p> - -<p><span style='font-size:10.0pt'>Contributors may not remove or alter any -copyright notices contained within the Program. </span></p> - -<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the -originator of its Contribution, if any, in a manner that reasonably allows -subsequent Recipients to identify the originator of the Contribution. </span></p> - -<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> - -<p><span style='font-size:10.0pt'>Commercial distributors of software may -accept certain responsibilities with respect to end users, business partners -and the like. While this license is intended to facilitate the commercial use -of the Program, the Contributor who includes the Program in a commercial -product offering should do so in a manner which does not create potential -liability for other Contributors. Therefore, if a Contributor includes the -Program in a commercial product offering, such Contributor (&quot;Commercial -Contributor&quot;) hereby agrees to defend and indemnify every other -Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and -costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other -legal actions brought by a third party against the Indemnified Contributor to -the extent caused by the acts or omissions of such Commercial Contributor in -connection with its distribution of the Program in a commercial product -offering. The obligations in this section do not apply to any claims or Losses -relating to any actual or alleged intellectual property infringement. In order -to qualify, an Indemnified Contributor must: a) promptly notify the Commercial -Contributor in writing of such claim, and b) allow the Commercial Contributor -to control, and cooperate with the Commercial Contributor in, the defense and -any related settlement negotiations. The Indemnified Contributor may participate -in any such claim at its own expense.</span> </p> - -<p><span style='font-size:10.0pt'>For example, a Contributor might include the -Program in a commercial product offering, Product X. That Contributor is then a -Commercial Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance claims and -warranties are such Commercial Contributor's responsibility alone. Under this -section, the Commercial Contributor would have to defend claims against the -other Contributors related to those performance claims and warranties, and if a -court requires any other Contributor to pay any damages as a result, the -Commercial Contributor must pay those damages.</span> </p> - -<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> - -<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS -AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT -WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, -WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, -MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely -responsible for determining the appropriateness of using and distributing the -Program and assumes all risks associated with its exercise of rights under this -Agreement , including but not limited to the risks and costs of program errors, -compliance with applicable laws, damage to or loss of data, programs or -equipment, and unavailability or interruption of operations. </span></p> - -<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> - -<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS -AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY -OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF -THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGES.</span> </p> - -<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> - -<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid -or unenforceable under applicable law, it shall not affect the validity or -enforceability of the remainder of the terms of this Agreement, and without -further action by the parties hereto, such provision shall be reformed to the -minimum extent necessary to make such provision valid and enforceable.</span> </p> - -<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation -against any entity (including a cross-claim or counterclaim in a lawsuit) -alleging that the Program itself (excluding combinations of the Program with -other software or hardware) infringes such Recipient's patent(s), then such -Recipient's rights granted under Section 2(b) shall terminate as of the date -such litigation is filed. </span></p> - -<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement -shall terminate if it fails to comply with any of the material terms or -conditions of this Agreement and does not cure such failure in a reasonable -period of time after becoming aware of such noncompliance. If all Recipient's -rights under this Agreement terminate, Recipient agrees to cease use and -distribution of the Program as soon as reasonably practicable. However, -Recipient's obligations under this Agreement and any licenses granted by -Recipient relating to the Program shall continue and survive. </span></p> - -<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute -copies of this Agreement, but in order to avoid inconsistency the Agreement is -copyrighted and may only be modified in the following manner. The Agreement -Steward reserves the right to publish new versions (including revisions) of -this Agreement from time to time. No one other than the Agreement Steward has -the right to modify this Agreement. The Eclipse Foundation is the initial -Agreement Steward. The Eclipse Foundation may assign the responsibility to -serve as the Agreement Steward to a suitable separate entity. Each new version -of the Agreement will be given a distinguishing version number. The Program -(including Contributions) may always be distributed subject to the version of -the Agreement under which it was received. In addition, after a new version of -the Agreement is published, Contributor may elect to distribute the Program -(including its Contributions) under the new version. Except as expressly stated -in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to -the intellectual property of any Contributor under this Agreement, whether -expressly, by implication, estoppel or otherwise. All rights in the Program not -expressly granted under this Agreement are reserved.</span> </p> - -<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the -State of New York and the intellectual property laws of the United States of -America. No party to this Agreement will bring a legal action under this -Agreement more than one year after the cause of action arose. Each party waives -its rights to a jury trial in any resulting litigation.</span> </p> - -<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> - -</div> - -</body> - -</html> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java.feature/pom.xml b/org.eclipse.babel.tapiji.tools.java.feature/pom.xml index 0c1aa5bd..27d6cbe2 100644 --- a/org.eclipse.babel.tapiji.tools.java.feature/pom.xml +++ b/org.eclipse.babel.tapiji.tools.java.feature/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.tapiji.tools.java.ui/epl-v10.html b/org.eclipse.babel.tapiji.tools.java.ui/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipse.babel.tapiji.tools.java.ui/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.java.ui/pom.xml b/org.eclipse.babel.tapiji.tools.java.ui/pom.xml index fcff8ce9..93b7025a 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/pom.xml +++ b/org.eclipse.babel.tapiji.tools.java.ui/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.tapiji.tools.java/epl-v10.html b/org.eclipse.babel.tapiji.tools.java/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipse.babel.tapiji.tools.java/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.java/pom.xml b/org.eclipse.babel.tapiji.tools.java/pom.xml index 0d65d990..99f32572 100644 --- a/org.eclipse.babel.tapiji.tools.java/pom.xml +++ b/org.eclipse.babel.tapiji.tools.java/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/epl-v10.html b/org.eclipse.babel.tapiji.tools.rbmanager/epl-v10.html deleted file mode 100644 index 84ec2511..00000000 --- a/org.eclipse.babel.tapiji.tools.rbmanager/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.rbmanager/pom.xml b/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml index 40fba457..2779e0b2 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml +++ b/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/org.eclipse.babel.tapiji.tools.target/pom.xml b/org.eclipse.babel.tapiji.tools.target/pom.xml index fca2246f..b00e91ec 100644 --- a/org.eclipse.babel.tapiji.tools.target/pom.xml +++ b/org.eclipse.babel.tapiji.tools.target/pom.xml @@ -1,3 +1,18 @@ +<?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> diff --git a/pom.xml b/pom.xml index 601ac116..e5d188bb 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,18 @@ <?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 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> @@ -8,7 +22,7 @@ <version>0.0.2-SNAPSHOT</version> <packaging>pom</packaging> - <!-- tycho requires maven >= 3.0 --> + <!-- tycho requires maven >= 3.0 --> <prerequisites> <maven>3.0</maven> </prerequisites> @@ -17,7 +31,7 @@ <tycho-version>0.16.0</tycho-version> </properties> <repositories> - <!-- configure p2 repository to resolve against --> + <!-- configure p2 repository to resolve against --> <repository> <id>indigo</id> <layout>p2</layout> @@ -28,14 +42,14 @@ <build> <plugins> <plugin> - <!-- enable tycho build extension --> + <!-- enable tycho build extension --> <groupId>org.eclipse.tycho</groupId> <artifactId>tycho-maven-plugin</artifactId> <version>${tycho-version}</version> <extensions>true</extensions> </plugin> - <!-- enable source bundle generation --> + <!-- enable source bundle generation --> <plugin> <groupId>org.eclipse.tycho</groupId> <artifactId>tycho-source-plugin</artifactId> @@ -62,7 +76,7 @@ <version>0.0.2-SNAPSHOT</version> </artifact> </target> - <!-- configure the p2 target environments for multi-platform build --> + <!-- configure the p2 target environments for multi-platform build --> <environments> <environment> <os>linux</os>
8b9e5a2edd935dd40e6dc30c14829e208d7945f2
drools
[BZ-1092084] raise a compilation error when the- same attribute is defined twice on a rule--
a
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/compiler/lang/ParserHelper.java b/drools-compiler/src/main/java/org/drools/compiler/lang/ParserHelper.java index 69c80fa3646..a5c41bb374e 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/lang/ParserHelper.java +++ b/drools-compiler/src/main/java/org/drools/compiler/lang/ParserHelper.java @@ -801,6 +801,12 @@ void setEnd( DescrBuilder< ? , ? > db ) { NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz )) ) { popParaphrases(); } + + if (RuleDescrBuilder.class.isAssignableFrom(clazz)) { + RuleDescrBuilder ruleDescrBuilder = (RuleDescrBuilder)builder; + ruleDescrBuilder.end().getDescr().afterRuleAdded(ruleDescrBuilder.getDescr()); + } + setEnd( builder ); return (T) builder; } diff --git a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/PackageDescr.java b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/PackageDescr.java index 090cc979fe4..ed70694ad00 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/PackageDescr.java +++ b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/PackageDescr.java @@ -16,6 +16,10 @@ package org.drools.compiler.lang.descr; +import org.drools.core.rule.Namespaceable; +import org.kie.api.io.Resource; +import org.kie.internal.definition.KnowledgeDescr; + import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; @@ -27,10 +31,6 @@ import java.util.List; import java.util.Set; -import org.drools.core.rule.Namespaceable; -import org.kie.internal.definition.KnowledgeDescr; -import org.kie.api.io.Resource; - public class PackageDescr extends BaseDescr implements Namespaceable, @@ -199,6 +199,11 @@ public void addRule(final RuleDescr rule) { if (this.rules == Collections.EMPTY_LIST) { this.rules = new ArrayList<RuleDescr>(1); } + rule.setLoadOrder(rules.size()); + this.rules.add(rule); + } + + public void afterRuleAdded(RuleDescr rule) { for (final AttributeDescr at : attributes) { // check if rule overrides the attribute if (!rule.getAttributes().containsKey(at.getName())) { @@ -206,8 +211,6 @@ public void addRule(final RuleDescr rule) { rule.addAttribute(at); } } - rule.setLoadOrder(rules.size()); - this.rules.add(rule); } public List<RuleDescr> getRules() { diff --git a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/RuleDescr.java b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/RuleDescr.java index 9de6fce97f4..e9f0c901440 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/RuleDescr.java +++ b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/RuleDescr.java @@ -16,12 +16,16 @@ package org.drools.compiler.lang.descr; +import org.drools.core.rule.Dialectable; + import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; -import java.util.*; - -import org.drools.core.rule.Dialectable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; public class RuleDescr extends AnnotatedBaseDescr implements @@ -139,7 +143,11 @@ public Map<String, AttributeDescr> getAttributes() { public void addAttribute(final AttributeDescr attribute) { if ( attribute != null ) { - this.attributes.put( attribute.getName(), attribute ); + if (attributes.containsKey(attribute.getName())) { + addError("Duplicate attribute definition: " + attribute.getName()); + } else { + this.attributes.put( attribute.getName(), attribute ); + } } } @@ -165,15 +173,19 @@ public Map<String, Object> getNamedConsequences() { public void addNamedConsequences(String name, Object consequence) { if ( namedConsequence.containsKey(name) ) { - if (errors == null) { - errors = new ArrayList<String>(); - } - errors.add("Duplicate consequence name: " + name); + addError("Duplicate consequence name: " + name); } else { namedConsequence.put(name, consequence); } } + private void addError(String message) { + if (errors == null) { + errors = new ArrayList<String>(); + } + errors.add(message); + } + public void setConsequenceLocation(final int line, final int pattern) { this.consequenceLine = line; diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java index 42a3209b3d0..0667ed50e98 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java @@ -5662,4 +5662,15 @@ public void testEvalInSubnetwork() { assertEquals(1, list.size()); assertEquals(0, (int)list.get(0)); } + + @Test + public void testRedeclaringRuleAttribute() { + // BZ-1092084 + String str = "rule R salience 10 salience 100 when then end\n"; + + KieServices ks = KieServices.Factory.get(); + KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str ); + Results results = ks.newKieBuilder( kfs ).buildAll().getResults(); + assertEquals(1, results.getMessages().size()); + } } \ No newline at end of file diff --git a/drools-compiler/src/test/java/org/drools/compiler/lang/descr/PackageDescrTest.java b/drools-compiler/src/test/java/org/drools/compiler/lang/descr/PackageDescrTest.java index 5045640983e..9cd64b50001 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/lang/descr/PackageDescrTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/lang/descr/PackageDescrTest.java @@ -1,5 +1,10 @@ package org.drools.compiler.lang.descr; +import org.drools.compiler.Person; +import org.drools.compiler.lang.api.DescrFactory; +import org.drools.compiler.lang.api.PackageDescrBuilder; +import org.junit.Test; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -10,13 +15,6 @@ import java.util.List; import java.util.Map; -import org.drools.compiler.Person; -import org.drools.compiler.lang.api.DescrFactory; -import org.drools.compiler.lang.api.PackageDescrBuilder; -import org.drools.compiler.lang.descr.AttributeDescr; -import org.drools.compiler.lang.descr.PackageDescr; -import org.drools.compiler.lang.descr.RuleDescr; -import org.junit.Test; import static org.junit.Assert.*; public class PackageDescrTest { @@ -39,7 +37,8 @@ public void testAttributeOverriding() { List pkgAts = desc.getAttributes(); assertEquals("bar", ((AttributeDescr)pkgAts.get( 0 )).getValue()); assertEquals("default", ((AttributeDescr)pkgAts.get( 1 )).getValue()); - + + desc.afterRuleAdded( rule ); Map<String, AttributeDescr> ruleAts = rule.getAttributes(); assertEquals("overridden", ((AttributeDescr)ruleAts.get( "foo" )).getValue());
12c81054044c429dd2356ac036b722c06e0f9e55
camel
Fixed test on other boxes--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@904741 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java b/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java index 20ebb8e293c12..2311db04e3574 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java @@ -324,15 +324,13 @@ public void testWhenExchangeReceivedWithDelay() throws Exception { long start = System.currentTimeMillis(); template.sendBody("seda:cheese", "Hello Cheese"); long end = System.currentTimeMillis(); - assertTrue("Should be faster than: " + (end - start), (end - start) < 1500); - - assertEquals(false, notify.matches()); + assertTrue("Should be faster than: " + (end - start), (end - start) < 2000); // should be quick as its when received and NOT when done assertEquals(true, notify.matches(5, TimeUnit.SECONDS)); long end2 = System.currentTimeMillis(); - assertTrue("Should be faster than: " + (end2 - start), (end2 - start) < 1500); + assertTrue("Should be faster than: " + (end2 - start), (end2 - start) < 2000); } public void testWhenExchangeDoneWithDelay() throws Exception { @@ -343,7 +341,7 @@ public void testWhenExchangeDoneWithDelay() throws Exception { long start = System.currentTimeMillis(); template.sendBody("seda:cheese", "Hello Cheese"); long end = System.currentTimeMillis(); - assertTrue("Should be faster than: " + (end - start), (end - start) < 1500); + assertTrue("Should be faster than: " + (end - start), (end - start) < 2000); assertEquals(false, notify.matches());
c335b3a1762080f8cb5b2694985d93f17978474e
elasticsearch
Fix- AckClusterUpdateSettingsIT.testClusterUpdateSettingsAcknowledgement() after- changes in -14259--Closes -14278-
c
https://github.com/elastic/elasticsearch
diff --git a/core/src/test/java/org/elasticsearch/cluster/ack/AckClusterUpdateSettingsIT.java b/core/src/test/java/org/elasticsearch/cluster/ack/AckClusterUpdateSettingsIT.java index 12147ffb783b5..81de8b1a43c22 100644 --- a/core/src/test/java/org/elasticsearch/cluster/ack/AckClusterUpdateSettingsIT.java +++ b/core/src/test/java/org/elasticsearch/cluster/ack/AckClusterUpdateSettingsIT.java @@ -29,6 +29,7 @@ import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; +import org.elasticsearch.cluster.routing.allocation.decider.ConcurrentRebalanceAllocationDecider; import org.elasticsearch.cluster.routing.allocation.decider.ThrottlingAllocationDecider; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.discovery.DiscoverySettings; @@ -50,6 +51,7 @@ protected Settings nodeSettings(int nodeOrdinal) { //make sure that enough concurrent reroutes can happen at the same time //we have a minimum of 2 nodes, and a maximum of 10 shards, thus 5 should be enough .put(ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, 5) + .put(ConcurrentRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_CLUSTER_CONCURRENT_REBALANCE, 10) .build(); }
830df67181827218ed8525ac924b073cffe4536f
hbase
HADOOP-2398. Additional instrumentation for- NameNode and RPC server. Add support for accessing instrumentation statistics- via JMX. (Sanjay radia via dhruba)--git-svn-id: https://svn.apache.org/repos/asf/lucene/hadoop/trunk/src/contrib/hbase@611906 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hbase
diff --git a/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java b/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java index dd3f270fd4a0..6ddbd01215d8 100644 --- a/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java +++ b/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java @@ -400,7 +400,7 @@ public Server(Object instance, Configuration conf, String bindAddress, int port this.verbose = verbose; } - public Writable call(Writable param) throws IOException { + public Writable call(Writable param, long receiveTime) throws IOException { try { Invocation call = (Invocation)param; if (verbose) log("Call: " + call);
43052179c2d568930f98894dfd5ea30f2a1a2ad6
arquillian$arquillian-graphene
ARQGRA-170: static contexts merged and added support for multiple browsers
a
https://github.com/arquillian/arquillian-graphene
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/configuration/ResourceTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/configuration/ResourceTestCase.java similarity index 92% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/configuration/ResourceTestCase.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/configuration/ResourceTestCase.java index 366d88036..0f501c6c3 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/configuration/ResourceTestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/configuration/ResourceTestCase.java @@ -19,8 +19,9 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.configuration; +package org.jboss.arquillian.graphene.ftest.configuration; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Assert; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneIntegrationTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneHtmlUnitDriverIntegrationTestCase.java similarity index 72% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneIntegrationTestCase.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneHtmlUnitDriverIntegrationTestCase.java index be1b7dea2..a575242d4 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneIntegrationTestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneHtmlUnitDriverIntegrationTestCase.java @@ -16,27 +16,31 @@ */ package org.jboss.arquillian.graphene.ftest.drone; +import org.jboss.arquillian.drone.api.annotation.Default; import static org.junit.Assert.assertTrue; import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.Graphene; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; -import org.openqa.selenium.WebDriver; +import org.openqa.selenium.htmlunit.HtmlUnitDriver; /** * @author Lukas Fryc + * @author Jan Papousek */ @RunWith(Arquillian.class) -public class GrapheneDroneIntegrationTestCase { +public class GrapheneDroneHtmlUnitDriverIntegrationTestCase { @Drone - WebDriver browser; + HtmlUnitDriver browser; @Test public void created_instance_should_be_instance_of_requested_driver() { - assertTrue("browser must be WebDriver", browser instanceof WebDriver); + assertTrue("browser must be HtmlUnitDriver", browser instanceof HtmlUnitDriver); } @Test @@ -48,4 +52,9 @@ public void created_instance_should_be_instance_of_GrapheneProxyInstance() { public void created_instance_should_be_able_to_navigate_to_some_page() { browser.navigate().to("http://127.0.0.1:14444"); } + + @Test + public void context_instance_should_be_instance_of_GrapheneProxyInstance() { + assertTrue("context browser must be proxy", browser instanceof GrapheneProxyInstance); + } } \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneWebDriverIntegrationTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneWebDriverIntegrationTestCase.java new file mode 100644 index 000000000..75b3f6b12 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneWebDriverIntegrationTestCase.java @@ -0,0 +1,70 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.arquillian.graphene.ftest.drone; + +import org.jboss.arquillian.drone.api.annotation.Default; +import static org.junit.Assert.assertTrue; + +import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.Graphene; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; +import org.jboss.arquillian.junit.Arquillian; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openqa.selenium.WebDriver; + +/** + * @author Lukas Fryc + * @author Jan Papousek + */ +@RunWith(Arquillian.class) +public class GrapheneDroneWebDriverIntegrationTestCase { + + @Drone + WebDriver browser; + + @Test + public void created_instance_should_be_instance_of_requested_driver() { + assertTrue("browser must be WebDriver", browser instanceof WebDriver); + } + + @Test + public void created_instance_should_be_instance_of_GrapheneProxyInstance() { + assertTrue("browser must be proxy", browser instanceof GrapheneProxyInstance); + } + + @Test + public void created_instance_should_be_able_to_navigate_to_some_page() { + browser.navigate().to("http://127.0.0.1:14444"); + } + + @Test + public void context_instance_should_be_instance_of_requested_driver() { + assertTrue("context browser must be WebDriver", GrapheneContext.getContextFor(Default.class).getWebDriver() instanceof WebDriver); + } + + @Test + public void context_instance_should_be_instance_of_GrapheneProxyInstance() { + assertTrue("context browser must be proxy", browser instanceof GrapheneProxyInstance); + } + + @Test + public void context_instance_should_be_able_to_navigate_to_some_page() { + GrapheneContext.getContextFor(Default.class).getWebDriver().navigate().to("http://127.0.0.1:14444"); + } +} \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/AbstractTest.java similarity index 84% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractTest.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/AbstractTest.java index ced5996c5..06eefaefc 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractTest.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/AbstractTest.java @@ -1,9 +1,9 @@ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import java.net.URL; import org.jboss.arquillian.drone.api.annotation.Drone; -import org.jboss.arquillian.graphene.enricher.page.AbstractPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.AbstractPage; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.openqa.selenium.WebDriver; @@ -17,16 +17,16 @@ public abstract class AbstractTest<T extends AbstractPage, E> { @Page protected E anotherPageWithGenericType; - + @Drone protected WebDriver selenium; - + public void loadPage() { URL page = this.getClass().getClassLoader() .getResource("org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html"); selenium.get(page.toExternalForm()); } - - + + } diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/MoreSpecificAbstractTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/MoreSpecificAbstractTest.java similarity index 57% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/MoreSpecificAbstractTest.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/MoreSpecificAbstractTest.java index da7eb8c4f..42d07543d 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/MoreSpecificAbstractTest.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/MoreSpecificAbstractTest.java @@ -1,6 +1,6 @@ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; -import org.jboss.arquillian.graphene.enricher.page.AbstractPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.AbstractPage; /** * @author <a href="mailto:[email protected]">Juraj Huska</a> diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java similarity index 79% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java index 200be2794..470318a94 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import java.net.URL; import junit.framework.Assert; @@ -54,29 +54,33 @@ public void loadPage(WebDriver browser) { @Test public void testDronePageNotNull() { - Assert.assertNotNull(page.browser); + Assert.assertNotNull(page.getBrowser()); } @Test public void testDronePageFragmentNotNull() { - Assert.assertNotNull(pageFragment.browser); + Assert.assertNotNull(pageFragment.getBrowser()); } @Test public void testDronePageTitle() { - loadPage(page.browser); - Assert.assertEquals("Sample Page", page.browser.getTitle()); + loadPage(page.getBrowser()); + Assert.assertEquals("Sample Page", page.getBrowser().getTitle()); } @Test public void testDronePageFragmentTitle() { - loadPage(pageFragment.browser); - Assert.assertEquals("Sample Page", pageFragment.browser.getTitle()); + loadPage(pageFragment.getBrowser()); + Assert.assertEquals("Sample Page", pageFragment.getBrowser().getTitle()); } public static class DronePage { @Drone private WebDriver browser; + + public WebDriver getBrowser() { + return browser; + } } public static class DronePageFragment { @@ -87,6 +91,14 @@ public static class DronePageFragment { @FindBy(tagName="span") private WebElement span; + public WebDriver getBrowser() { + return browser; + } + + public WebElement getSpan() { + return span; + } + } } \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestEnrichingContainerElement.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestEnrichingContainerElement.java similarity index 82% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestEnrichingContainerElement.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestEnrichingContainerElement.java index d7de4599d..9210299ef 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestEnrichingContainerElement.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestEnrichingContainerElement.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; @@ -27,8 +27,8 @@ import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.enricher.findby.FindBy; -import org.jboss.arquillian.graphene.enricher.page.fragment.Panel; -import org.jboss.arquillian.graphene.enricher.page.fragment.TabPanel; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.Panel; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.TabPanel; import org.jboss.arquillian.junit.Arquillian; import org.junit.Before; import org.junit.Test; @@ -59,16 +59,20 @@ public void loadPage() { public void testTabPanelSwitching() { Panel tab3 = tabPanel.switchTo(2); ContentOfTab content = tab3.getContent(ContentOfTab.class); - assertEquals("The tab panel was not switched to third tab correctly!", "Content of the tab 3", content.text.getText()); - + assertEquals("The tab panel was not switched to third tab correctly!", "Content of the tab 3", content.getText().getText()); + Panel tab1 = tabPanel.switchTo(0); content = tab1.getContent(ContentOfTab.class); - assertEquals("The tab panel was not switched to first tab correctly!", "Content of the tab 1", content.text.getText()); + assertEquals("The tab panel was not switched to first tab correctly!", "Content of the tab 1", content.getText().getText()); } - private static class ContentOfTab { + public static class ContentOfTab { @FindBy(className = "tab-text") - public WebElement text; + private WebElement text; + + public WebElement getText() { + return text; + } } } diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestFindByLongLocatingMethod.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestFindByLongLocatingMethod.java similarity index 98% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestFindByLongLocatingMethod.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestFindByLongLocatingMethod.java index 7d31ed79b..a6e152a6b 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestFindByLongLocatingMethod.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestFindByLongLocatingMethod.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestHandlingOfStaleElements.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestHandlingOfStaleElements.java similarity index 90% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestHandlingOfStaleElements.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestHandlingOfStaleElements.java index dc9a8cbec..aa6880e11 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestHandlingOfStaleElements.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestHandlingOfStaleElements.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.fail; @@ -113,24 +113,24 @@ public void testListOfElements() throws Exception { @Test public void testPageFragment() throws Exception { - pageFragment.root.isDisplayed(); + pageFragment.getRoot().isDisplayed(); pageFragment.makeStale(); - pageFragment.root.isDisplayed(); + pageFragment.getRoot().isDisplayed(); } @Test public void testPageFragmentWithStaleRoot() { - rootPageFragment.inStale.isDisplayed(); + rootPageFragment.getInStale().isDisplayed(); pageFragment.makeStale(); - rootPageFragment.inStale.isDisplayed(); + rootPageFragment.getInStale().isDisplayed(); } @Test public void testListOfPageFragments() throws Exception { StaleElementPageFragment pf = pageFragments.get(0); - pf.root.isDisplayed(); + pf.getRoot().isDisplayed(); pf.makeStale(); - pf.root.isDisplayed(); + pf.getRoot().isDisplayed(); } public static class StaleElementPageFragment { @@ -138,8 +138,6 @@ public static class StaleElementPageFragment { @Root private WebElement root; - @FindBy(className = "stale") - private WebElement stale; @FindBy(className = "make-stale") private WebElement makeStale; @@ -147,6 +145,10 @@ public void makeStale() { makeStale.click(); } + public WebElement getRoot() { + return root; + } + } public static class StaleRootPageFragment { @@ -154,6 +156,9 @@ public static class StaleRootPageFragment { @FindBy(className = "in-stale") private WebElement inStale; + public WebElement getInStale() { + return inStale; + } } } diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeEmptyFindBy.java similarity index 79% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeEmptyFindBy.java index 9c9409e79..5ab17d3b8 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeEmptyFindBy.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -28,7 +28,6 @@ import java.util.List; import org.jboss.arquillian.drone.api.annotation.Drone; -import org.jboss.arquillian.graphene.enricher.findby.FindBy; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.jboss.arquillian.junit.Arquillian; import org.junit.Before; @@ -36,6 +35,7 @@ import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.Select; /** @@ -91,24 +91,42 @@ public void testSelectById() { @Test public void testSeleniumFindBy() { - checkPageFragmentById(pageObjectWithSeleniumFindBys.spanFragment); - checkSelectById(pageObjectWithSeleniumFindBys.selectElement); - checkWebElementById(pageObjectWithSeleniumFindBys.divWebElement); - checkWebElementByName(pageObjectWithSeleniumFindBys.nameOfInputElement); + checkPageFragmentById(pageObjectWithSeleniumFindBys.getSpanFragment()); + checkSelectById(pageObjectWithSeleniumFindBys.getSelectElement()); + checkWebElementById(pageObjectWithSeleniumFindBys.getDivWebElement()); + checkWebElementByName(pageObjectWithSeleniumFindBys.getNameOfInputElement()); } public class PageObject { @org.openqa.selenium.support.FindBy - public WebElement divWebElement; + private WebElement divWebElement; @org.openqa.selenium.support.FindBy - public SpanFragment spanFragment; + private SpanFragment spanFragment; @org.openqa.selenium.support.FindBy - public Select selectElement; + private Select selectElement; @org.openqa.selenium.support.FindBy - public WebElement nameOfInputElement; + private WebElement nameOfInputElement; + + public WebElement getDivWebElement() { + return divWebElement; + } + + public WebElement getNameOfInputElement() { + return nameOfInputElement; + } + + public Select getSelectElement() { + return selectElement; + } + + public SpanFragment getSpanFragment() { + return spanFragment; + } + + } public class SpanFragment { diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeFindBys.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeFindBys.java similarity index 98% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeFindBys.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeFindBys.java index c5824e9f8..70c9684bc 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeFindBys.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeFindBys.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeNestedPageFragments.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeNestedPageFragments.java similarity index 97% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeNestedPageFragments.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeNestedPageFragments.java index cb2f0cc47..e080912da 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeNestedPageFragments.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeNestedPageFragments.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertNotNull; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects1.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects1.java similarity index 84% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects1.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects1.java index c18600b9d..54ec0d3b1 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects1.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects1.java @@ -1,9 +1,9 @@ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; -import org.jboss.arquillian.graphene.enricher.page.TestPage; -import org.jboss.arquillian.graphene.enricher.page.TestPage2; +import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage2; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects2.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects2.java similarity index 84% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects2.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects2.java index edbb6bedb..6459f6012 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects2.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects2.java @@ -1,9 +1,9 @@ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; -import org.jboss.arquillian.graphene.enricher.page.TestPage; -import org.jboss.arquillian.graphene.enricher.page.TestPage2; +import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage2; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects3.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects3.java similarity index 93% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects3.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects3.java index 996b52eb6..2bab3421c 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects3.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects3.java @@ -19,12 +19,12 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; -import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub; -import org.jboss.arquillian.graphene.enricher.page.TestPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects4.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects4.java similarity index 93% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects4.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects4.java index 120a9a208..96b7c59ab 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects4.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects4.java @@ -19,10 +19,10 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; -import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub; -import org.jboss.arquillian.graphene.enricher.page.TestPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.jboss.arquillian.junit.Arquillian; import static org.junit.Assert.assertEquals; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingNestedPageObjects.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingNestedPageObjects.java similarity index 97% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingNestedPageObjects.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingNestedPageObjects.java index 1648bf9b2..9ab0117bf 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingNestedPageObjects.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingNestedPageObjects.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertNotNull; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingPageFragments.java similarity index 91% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingPageFragments.java index a35255793..ae5f56496 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingPageFragments.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -29,16 +29,15 @@ import java.util.List; import org.jboss.arquillian.drone.api.annotation.Drone; -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub; -import org.jboss.arquillian.graphene.enricher.page.EmbeddedPage; -import org.jboss.arquillian.graphene.enricher.page.TestPage; -import org.jboss.arquillian.graphene.enricher.page.fragment.PageFragmentWithEmbeddedAnotherPageFragmentStub; +import org.jboss.arquillian.graphene.Graphene; +import org.jboss.arquillian.graphene.ftest.enricher.page.EmbeddedPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.PageFragmentWithEmbeddedAnotherPageFragmentStub; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; -import org.openqa.selenium.HasInputDevices; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; @@ -139,8 +138,7 @@ public void testInitializeListOfWebElementsInjectedToPageObject() { public void testSupportForAdvancedActions() { loadPage(); - WebDriver driver = GrapheneContext.getProxyForInterfaces(HasInputDevices.class); - Actions builder = new Actions(driver); + Actions builder = new Actions(selenium); // following tests usage of Actions with injected plain WebElement builder.click(input); diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentList.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageFragmentList.java similarity index 98% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentList.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageFragmentList.java index f075d1920..a66ab0241 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentList.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageFragmentList.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import java.net.URL; import java.util.List; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestSamplePageFragment.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestSamplePageFragment.java similarity index 98% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestSamplePageFragment.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestSamplePageFragment.java index 72b89e7a2..298c5a88e 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestSamplePageFragment.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestSamplePageFragment.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import java.net.URL; import junit.framework.Assert; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementWrapper.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestWebElementWrapper.java similarity index 98% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementWrapper.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestWebElementWrapper.java index cd99ff77a..2861ffe57 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementWrapper.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestWebElementWrapper.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher; +package org.jboss.arquillian.graphene.ftest.enricher; import java.net.URL; import junit.framework.Assert; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/AbstractPage.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/AbstractPage.java similarity index 84% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/AbstractPage.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/AbstractPage.java index 2d21e86c4..c171e2aa7 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/AbstractPage.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/AbstractPage.java @@ -1,4 +1,4 @@ -package org.jboss.arquillian.graphene.enricher.page; +package org.jboss.arquillian.graphene.ftest.enricher.page; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -7,7 +7,7 @@ public class AbstractPage { @FindBy(xpath = "//input") private WebElement input; - + public WebElement getInput() { return input; } diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/EmbeddedPage.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/EmbeddedPage.java similarity index 86% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/EmbeddedPage.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/EmbeddedPage.java index 69524ccf0..03b9b13fd 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/EmbeddedPage.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/EmbeddedPage.java @@ -1,4 +1,4 @@ -package org.jboss.arquillian.graphene.enricher.page; +package org.jboss.arquillian.graphene.ftest.enricher.page; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -6,7 +6,7 @@ public class EmbeddedPage { public static final String EXPECTED_TEXT_OF_EMBEDDED_ELEM = "This is embedded element"; - + @FindBy(id="embeddedElement") private WebElement embeddedElement; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage.java similarity index 94% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage.java index 10bef196a..4760b18ef 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage.java @@ -19,11 +19,11 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher.page; +package org.jboss.arquillian.graphene.ftest.enricher.page; import java.util.List; -import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage2.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage2.java similarity index 89% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage2.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage2.java index 4817060d7..24e08e84c 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage2.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage2.java @@ -1,6 +1,6 @@ -package org.jboss.arquillian.graphene.enricher.page; +package org.jboss.arquillian.graphene.ftest.enricher.page; -import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub; +import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/AbstractPageFragmentStub.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/AbstractPageFragmentStub.java new file mode 100644 index 000000000..6483d550e --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/AbstractPageFragmentStub.java @@ -0,0 +1,179 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.ftest.enricher.page.fragment; + +import java.util.List; + +import org.jboss.arquillian.graphene.spi.annotations.Root; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; + +/** + * + * @author <a href="mailto:[email protected]">Juraj Huska</a> + * + */ +public class AbstractPageFragmentStub { + + @Root + private WebElement root; + + @FindBy(className = "classNameRef") + private WebElement locatorRefByClassName; + + @FindBy(name = "nameRef") + private WebElement locatorRefByName; + + @FindBy(id = "idRef") + private WebElement locatorRefById; + + @FindBy(tagName = "tagNameRef") + private WebElement locatorRefByTagName; + + @FindBy(linkText = "linkTextRef") + private WebElement locatorRefByLinkText; + + @FindBy(partialLinkText = "partiaLinkTextRef") + private WebElement locatorRefByPartialLinkText; + + @FindBy(xpath = "//div[@class='refByXpath']") + private WebElement locatorRefByXPath; + + @FindBy(css = "cssSelectorRef") + private WebElement locatorRefByCssSelector; + + @FindBy(className="spans") + private List<WebElement> spansInPageFragment; + + public String invokeMethodOnRoot() { + return root.getText(); + } + + public String invokeMethodOnElementRefByClass() { + return this.locatorRefByClassName.getText(); + } + + public String invokeMethodOnElementRefById() { + return this.locatorRefById.getText(); + } + + public String invokeMethodOnElementRefByCSS() { + return this.locatorRefByCssSelector.getText(); + } + + public String invokeMethodOnElementRefByName() { + return this.locatorRefByName.getText(); + } + + public String invokeMethodOnElementRefByTagName() { + return locatorRefByTagName.getAttribute("id"); + } + + public String invokeMethodOnElementRefByXpath() { + return this.locatorRefByXPath.getText(); + } + + public String invokeMethodOnElementRefByLinkText() { + return this.locatorRefByLinkText.getText(); + } + + public String invokeMethodOnElementRefByPartialLinkText() { + return this.locatorRefByPartialLinkText.getText(); + } + + public WebElement getRootProxy() { + return this.root; + } + + public WebElement getLocatorRefByClassName() { + return locatorRefByClassName; + } + + public void setLocatorRefByClassName(WebElement locatorRefByClassName) { + this.locatorRefByClassName = locatorRefByClassName; + } + + public WebElement getLocatorRefByName() { + return locatorRefByName; + } + + public void setLocatorRefByName(WebElement locatorRefByName) { + this.locatorRefByName = locatorRefByName; + } + + public WebElement getLocatorRefById() { + return locatorRefById; + } + + public void setLocatorRefById(WebElement locatorRefById) { + this.locatorRefById = locatorRefById; + } + + public WebElement getLocatorRefByTagName() { + return locatorRefByTagName; + } + + public void setLocatorRefByTagName(WebElement locatorRefByTagName) { + this.locatorRefByTagName = locatorRefByTagName; + } + + public WebElement getLocatorRefByLinkText() { + return locatorRefByLinkText; + } + + public void setLocatorRefByLinkText(WebElement locatorRefByLinkText) { + this.locatorRefByLinkText = locatorRefByLinkText; + } + + public WebElement getLocatorRefByPartialLinkText() { + return locatorRefByPartialLinkText; + } + + public void setLocatorRefByPartialLinkText(WebElement locatorRefByPartialLinkText) { + this.locatorRefByPartialLinkText = locatorRefByPartialLinkText; + } + + public WebElement getLocatorRefByXPath() { + return locatorRefByXPath; + } + + public void setLocatorRefByXPath(WebElement locatorRefByXPath) { + this.locatorRefByXPath = locatorRefByXPath; + } + + public WebElement getLocatorRefByCssSelector() { + return locatorRefByCssSelector; + } + + public void setLocatorRefByCssSelector(WebElement locatorRefByCssSelector) { + this.locatorRefByCssSelector = locatorRefByCssSelector; + } + + public List<WebElement> getSpansInPageFragment() { + return spansInPageFragment; + } + + public void setSpans(List<WebElement> divs) { + this.spansInPageFragment = divs; + } + +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java similarity index 92% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java index 3069bddeb..9c4364359 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java @@ -19,9 +19,8 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher.page.fragment; +package org.jboss.arquillian.graphene.ftest.enricher.page.fragment; -import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub; import org.jboss.arquillian.graphene.spi.annotations.Root; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/Panel.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/Panel.java similarity index 95% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/Panel.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/Panel.java index 7cf2fb168..456979235 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/Panel.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/Panel.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher.page.fragment; +package org.jboss.arquillian.graphene.ftest.enricher.page.fragment; import org.jboss.arquillian.graphene.component.object.api.switchable.ComponentContainer; import org.jboss.arquillian.graphene.enricher.PageFragmentEnricher; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/TabPanel.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/TabPanel.java similarity index 97% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/TabPanel.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/TabPanel.java index e672b5db2..d2e6243e6 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/TabPanel.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/TabPanel.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.enricher.page.fragment; +package org.jboss.arquillian.graphene.ftest.enricher.page.fragment; import static org.jboss.arquillian.graphene.Graphene.guardAjax; import static org.jboss.arquillian.graphene.Graphene.guardHttp; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java index dbdfff847..13f581c5a 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java @@ -30,7 +30,6 @@ import java.net.URL; import org.jboss.arquillian.drone.api.annotation.Drone; -import org.jboss.arquillian.graphene.context.GrapheneContext; import org.jboss.arquillian.graphene.guard.RequestGuardException; import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; @@ -152,9 +151,9 @@ public static interface Activity { public void perform() throws Exception; } - public static class XhrAndRelocationActivity implements Activity { + public class XhrAndRelocationActivity implements Activity { + @Override public void perform() throws Exception { - WebDriver browser = GrapheneContext.getProxy(); browser.findElement(By.id("xhr")).click(); String url = browser.getCurrentUrl().replace("sample1", "sample2"); Thread.sleep(200); diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java index d6e05732a..deacdcdab 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java @@ -25,8 +25,10 @@ import static org.junit.Assert.assertEquals; import java.net.URL; +import org.jboss.arquillian.drone.api.annotation.Default; import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.guard.RequestGuard; import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory; import org.jboss.arquillian.graphene.page.RequestType; @@ -62,7 +64,7 @@ public void loadPage() { @Test public void testXhr() throws InterruptedException { - RequestGuard guard = JSInterfaceFactory.create(RequestGuard.class); + RequestGuard guard = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), RequestGuard.class); assertEquals(RequestType.HTTP, guard.getRequestType()); guard.clearRequestDone(); assertEquals(RequestType.NONE, guard.getRequestType()); @@ -73,7 +75,7 @@ public void testXhr() throws InterruptedException { @Test public void testHttp() { - RequestGuard guard = JSInterfaceFactory.create(RequestGuard.class); + RequestGuard guard = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), RequestGuard.class); assertEquals(RequestType.HTTP, guard.getRequestType()); guard.clearRequestDone(); assertEquals(RequestType.NONE, guard.getRequestType()); diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java index fa5a46a41..ae06df593 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java @@ -3,7 +3,7 @@ import org.jboss.arquillian.core.api.annotation.Observes; import org.jboss.arquillian.core.spi.EventContext; import org.jboss.arquillian.core.spi.LoadableExtension; -import org.jboss.arquillian.graphene.context.GrapheneContext; +import org.jboss.arquillian.drone.api.annotation.Default; import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.jboss.arquillian.graphene.proxy.Interceptor; import org.jboss.arquillian.graphene.proxy.InvocationContext; @@ -24,7 +24,7 @@ public void register_interceptor(@Observes EventContext<Test> ctx) { try { Test event = ctx.getEvent(); if (event.getTestClass().getJavaClass() == TestInterceptorRegistration.class) { - WebDriver browser = GrapheneContext.getProxy(); + WebDriver browser = org.jboss.arquillian.graphene.GrapheneContext.getContextFor(Default.class).getWebDriver(); ((GrapheneProxyInstance) browser).registerInterceptor(new Interceptor() { @Override diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/issues/ARQGRA269TestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/issues/ARQGRA269TestCase.java similarity index 98% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/issues/ARQGRA269TestCase.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/issues/ARQGRA269TestCase.java index f9e3822a5..6d1245b32 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/issues/ARQGRA269TestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/issues/ARQGRA269TestCase.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.issues; +package org.jboss.arquillian.graphene.ftest.issues; import java.net.URL; import junit.framework.Assert; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java index ec779cbbe..bc565069c 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java @@ -25,11 +25,14 @@ import java.util.List; import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.Graphene; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.javascript.Dependency; import org.jboss.arquillian.graphene.javascript.InstallableJavaScript; import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory; import org.jboss.arquillian.graphene.javascript.JavaScript; import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; @@ -47,6 +50,9 @@ public class JavaScriptPageExtensionTestCase { @Drone private WebDriver browser; + @ArquillianResource + private GrapheneContext context; + public void loadPage() { URL page = this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/javascript/sample.html"); browser.navigate().to(page); @@ -55,7 +61,7 @@ public void loadPage() { @Test public void testWithoutSources() { loadPage(); - Document document = JSInterfaceFactory.create(Document.class); + Document document = JSInterfaceFactory.create(context, Document.class); List<WebElement> elements = document.getElementsByTagName("html"); Assert.assertNotNull(elements); Assert.assertEquals(1, elements.size()); @@ -65,27 +71,27 @@ public void testWithoutSources() { public void testWithSources() { loadPage(); - HelloWorld helloWorld = JSInterfaceFactory.create(HelloWorld.class); + HelloWorld helloWorld = JSInterfaceFactory.create(context, HelloWorld.class); Assert.assertEquals("Hello World!", helloWorld.hello()); } @Test public void testWithInterfaceDependencies() { loadPage(); - HelloWorld2 helloWorld = JSInterfaceFactory.create(HelloWorld2.class); + HelloWorld2 helloWorld = JSInterfaceFactory.create(context, HelloWorld2.class); Assert.assertEquals("Hello World!", helloWorld.hello()); } @Test(expected=IllegalArgumentException.class) public void testWithoutSourceAndWithInterfaceDependencies() { loadPage(); - JSInterfaceFactory.create(Document2.class).getTitle(); + JSInterfaceFactory.create(context, Document2.class).getTitle(); } @Test public void testAbstractClass() { loadPage(); - Document3 document = JSInterfaceFactory.create(Document3.class); + Document3 document = JSInterfaceFactory.create(context, Document3.class); Assert.assertEquals(browser.findElement(By.tagName("h1")), document.getHeader()); } diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java index 09a004724..b8945b013 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java @@ -22,9 +22,12 @@ import java.util.List; import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.Graphene; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory; import org.jboss.arquillian.graphene.javascript.JavaScript; import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; @@ -38,12 +41,15 @@ public class TestCustomJSInterface { @Drone WebDriver browser; - + + @ArquillianResource + private GrapheneContext context; + @Test public void test() { browser.navigate().to("http://127.0.0.1:4444"); - - Document document = JSInterfaceFactory.create(Document.class); + + Document document = JSInterfaceFactory.create(context, Document.class); List<WebElement> elements = document.getElementsByTagName("html"); assertNotNull(elements); assertEquals(1, elements.size()); @@ -51,9 +57,9 @@ public void test() { @JavaScript("document") public static interface Document { - + String getTitle(); - + List<WebElement> getElementsByTagName(String tagName); } } \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java index 371a2a1e0..b9810a2d9 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java @@ -32,11 +32,13 @@ import junit.framework.Assert; import org.jboss.arquillian.drone.api.annotation.Drone; -import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext; +import org.jboss.arquillian.graphene.Graphene; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry; import org.jboss.arquillian.graphene.spi.javascript.JavaScript; import org.jboss.arquillian.graphene.spi.page.PageExtension; import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -51,6 +53,9 @@ public class PageExtensionTestCase { @Drone private WebDriver browser; + @ArquillianResource + private GrapheneContext context; + public void loadPage() { URL page = this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/page/extension/sample.html"); browser.get(page.toString()); @@ -65,10 +70,10 @@ public void testCorrectInstallation() { when(pageExtensionMock.getInstallationDetectionScript()).thenReturn(JavaScript.fromString("return (typeof Document.Graphene != 'undefined');")); when(pageExtensionMock.getRequired()).thenReturn(Collections.EMPTY_LIST); // registry - PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy(); + PageExtensionRegistry registry = context.getPageExtensionRegistry(); registry.register(pageExtensionMock); // test - GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install(); + context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install(); } @Test(expected=IllegalStateException.class) @@ -80,10 +85,10 @@ public void testIncorrectInstallation() { when(pageExtensionMock.getInstallationDetectionScript()).thenReturn(JavaScript.fromString("return (typeof Graphene != 'undefined');")); when(pageExtensionMock.getRequired()).thenReturn(Collections.EMPTY_LIST); // registry - PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy(); + PageExtensionRegistry registry = context.getPageExtensionRegistry(); registry.register(pageExtensionMock); // test - GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install(); + context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install(); } @Test @@ -97,13 +102,13 @@ public void testInstallationWithRequirements() { requirements.add(SimplePageExtension.class.getName()); when(pageExtensionMock.getRequired()).thenReturn(requirements); // registry - PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy(); + PageExtensionRegistry registry = context.getPageExtensionRegistry(); registry.register(new SimplePageExtension()); registry.register(pageExtensionMock); // test - GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install(); - Assert.assertTrue(GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(SimplePageExtension.class.getName()).isInstalled()); - Assert.assertTrue(GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).isInstalled()); + context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install(); + Assert.assertTrue(context.getPageExtensionInstallatorProvider().installator(SimplePageExtension.class.getName()).isInstalled()); + Assert.assertTrue(context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).isInstalled()); } @Test(expected=IllegalStateException.class) @@ -119,13 +124,13 @@ public void testInstallationWithCyclicRequirements() { requirements.add(CyclicPageExtension2.class.getName()); when(pageExtensionMock.getRequired()).thenReturn(requirements); // registry - PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy(); + PageExtensionRegistry registry = context.getPageExtensionRegistry(); registry.register(new SimplePageExtension()); registry.register(pageExtensionMock); registry.register(new CyclicPageExtension1()); registry.register(new CyclicPageExtension2()); // test - GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install(); + context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install(); } private static class SimplePageExtension implements PageExtension { diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/AbstractParallelTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/AbstractParallelTest.java new file mode 100644 index 000000000..48a0ffcae --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/AbstractParallelTest.java @@ -0,0 +1,64 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.ftest.parallel; + +import java.util.List; +import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.javascript.JavaScript; +import org.jboss.arquillian.junit.Arquillian; +import org.junit.runner.RunWith; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import qualifier.Browser1; +import qualifier.Browser2; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +@RunWith(Arquillian.class) +public abstract class AbstractParallelTest { + + @Browser1 + @Drone + protected WebDriver browser1; + + @Browser2 + @Drone + protected WebDriver browser2; + + @Drone + protected WebDriver browserDefault; + + public void loadPage() { + browser1.get(this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/parallel/one.html").toString()); + browser2.get(this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/parallel/two.html").toString()); + browserDefault.get(this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/parallel/default.html").toString()); + } + + @JavaScript("document") + public static interface Document { + + List<WebElement> getElementsByTagName(String tagName); + + } + +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestGraphene.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestGraphene.java new file mode 100644 index 000000000..0fd5429eb --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestGraphene.java @@ -0,0 +1,142 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.ftest.parallel; + +import org.jboss.arquillian.graphene.Graphene; +import org.jboss.arquillian.graphene.spi.annotations.Page; +import org.junit.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import qualifier.Browser1; +import qualifier.Browser2; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +public class TestGraphene extends AbstractParallelTest { + + @Browser1 + @FindBy(tagName="h1") + private WebElement header1; + + @Browser2 + @FindBy(tagName="h1") + private WebElement header2; + + @FindBy(tagName="h1") + private WebElement headerDefault; + + @Page + @Browser1 + private SimplePage page1; + + @Page + @Browser2 + private SimplePage page2; + + @Page + private SimplePage pageDefault; + + + @Test + public void testWaitWithElements() { + loadPage(); + + Graphene.waitGui() + .until() + .element(header1) + .text() + .equalTo("Page 1"); + + Graphene.waitGui() + .until() + .element(header2) + .text() + .equalTo("Page 2"); + + Graphene.waitGui() + .until() + .element(headerDefault) + .text() + .equalTo("Page Default"); + } + + @Test + public void testWaitWithBys() { + loadPage(); + + Graphene.waitGui(browser1) + .until() + .element(By.tagName("h1")) + .text() + .equalTo("Page 1"); + + Graphene.waitGui(browser2) + .until() + .element(By.tagName("h1")) + .text() + .equalTo("Page 2"); + + Graphene.waitGui(browserDefault) + .until() + .element(By.tagName("h1")) + .text() + .equalTo("Page Default"); + } + + @Test + public void testGuardHttp() { + loadPage(); + + Graphene.guardHttp(page1).http(); + Graphene.guardHttp(page2).http(); + Graphene.guardHttp(pageDefault).http(); + } + + @Test + public void testGuardXhr() { + loadPage(); + + Graphene.guardXhr(page1).xhr(); + Graphene.guardXhr(page2).xhr(); + Graphene.guardXhr(pageDefault).xhr(); + } + + public static class SimplePage { + + @FindBy + private WebElement http; + + @FindBy + private WebElement xhr; + + public void http() { + http.click(); + } + + public void xhr() { + xhr.click(); + } + } + +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestInterceptors.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestInterceptors.java new file mode 100644 index 000000000..1e86343c4 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestInterceptors.java @@ -0,0 +1,90 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.ftest.parallel; + +import java.util.concurrent.atomic.AtomicInteger; +import junit.framework.Assert; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; +import org.jboss.arquillian.graphene.proxy.Interceptor; +import org.jboss.arquillian.graphene.proxy.InvocationContext; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.junit.Before; +import org.junit.Test; +import qualifier.Browser1; +import qualifier.Browser2; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +public class TestInterceptors extends AbstractParallelTest { + + @Browser1 + @ArquillianResource + private GrapheneContext context1; + + @Browser2 + @ArquillianResource + private GrapheneContext context2; + + @ArquillianResource + private GrapheneContext contextDefault; + + private AtomicInteger counter1 = new AtomicInteger(); + private AtomicInteger counter2 = new AtomicInteger(); + private AtomicInteger counterDefault = new AtomicInteger(); + + @Before + public void resetCounters() { + this.counter1.set(0); + this.counter2.set(0); + this.counterDefault.set(0); + } + + @Test + public void testContextVsDrone() { + loadPage(); + + ((GrapheneProxyInstance) browser1).registerInterceptor(createInterceptor(counter1)); + ((GrapheneProxyInstance) browser2).registerInterceptor(createInterceptor(counter2)); + ((GrapheneProxyInstance) browserDefault).registerInterceptor(createInterceptor(counterDefault)); + + context1.getWebDriver().getTitle(); + context2.getWebDriver().getTitle(); + contextDefault.getWebDriver().getTitle(); + + Assert.assertEquals(1, counter1.get()); + Assert.assertEquals(1, counter2.get()); + Assert.assertEquals(1, counterDefault.get()); + } + + protected Interceptor createInterceptor(final AtomicInteger counter) { + return new Interceptor() { + @Override + public Object intercept(InvocationContext context) throws Throwable { + counter.incrementAndGet(); + return context.invoke(); + } + }; + } + +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageFragments.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageFragments.java new file mode 100644 index 000000000..1cd9bf5f8 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageFragments.java @@ -0,0 +1,178 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.ftest.parallel; + +import junit.framework.Assert; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.javascript.JavaScript; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import qualifier.Browser1; +import qualifier.Browser2; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +@RunWith(Arquillian.class) +public class TestPageFragments extends AbstractParallelTest { + + @Browser1 + @FindBy(tagName="body") + private PageFragment pageFragment1; + + @Browser2 + @FindBy(tagName="body") + private PageFragment pageFragment2; + + @FindBy(tagName="body") + private PageFragment pageFragmentDefault; + + @Test + public void testNotNull() { + Assert.assertNotNull(pageFragment1); + Assert.assertNotNull(pageFragment2); + Assert.assertNotNull(pageFragmentDefault); + } + + @Test + public void testHeadersViaAttributes() { + loadPage(); + + Assert.assertNotNull(pageFragment1.header); + Assert.assertNotNull(pageFragment1.header); + Assert.assertNotNull(pageFragmentDefault.header); + + Assert.assertEquals("Page 1", pageFragment1.header.getText().trim()); + Assert.assertEquals("Page 2", pageFragment2.header.getText().trim()); + Assert.assertEquals("Page Default", pageFragmentDefault.header.getText().trim()); + } + + @Test + public void testHeadersViaMethod() { + loadPage(); + + Assert.assertNotNull(pageFragment1.header()); + Assert.assertNotNull(pageFragment2.header()); + Assert.assertNotNull(pageFragmentDefault.header()); + + Assert.assertEquals("Page 1", pageFragment1.header().getText().trim()); + Assert.assertEquals("Page 2", pageFragment2.header().getText().trim()); + Assert.assertEquals("Page Default", pageFragmentDefault.header().getText().trim()); + } + + @Test + public void testDroneInPageFragments() { + loadPage(); + + String url1 = browser1.getCurrentUrl(); + String url2 = browser2.getCurrentUrl(); + String urlDefault = browserDefault.getCurrentUrl(); + + Assert.assertNotNull(pageFragment1.browser()); + Assert.assertNotNull(pageFragment2.browser()); + Assert.assertNotNull(pageFragmentDefault.browser()); + + Assert.assertEquals(url1, pageFragment1.getCurrentURL()); + Assert.assertEquals(url2, pageFragment2.getCurrentURL()); + Assert.assertEquals(urlDefault, pageFragmentDefault.getCurrentURL()); + } + + @Test + public void testJavaScriptInterfaceInPageFragments() { + loadPage(); + Assert.assertEquals("Page 1", pageFragment1.getHeaderTextViaJavaScriptInterface().trim()); + Assert.assertEquals("Page 2", pageFragment2.getHeaderTextViaJavaScriptInterface().trim()); + Assert.assertEquals("Page Default", pageFragmentDefault.getHeaderTextViaJavaScriptInterface().trim()); + } + + @Test + public void testJavaScriptExecutorInPageFragments() { + loadPage(); + Assert.assertEquals("Page 1", pageFragment1.getTitleViaJavaScriptExecutor().trim()); + Assert.assertEquals("Page 2", pageFragment2.getTitleViaJavaScriptExecutor().trim()); + Assert.assertEquals("Page Default", pageFragmentDefault.getTitleViaJavaScriptExecutor().trim()); + } + + @Test + public void testJavaScriptExecutorInvocation() { + loadPage(); + } + + @Test + public void testGrapheneContextQualifier() { + Assert.assertEquals(Browser1.class, pageFragment1.getQualifier()); + Assert.assertEquals(Browser2.class, pageFragment2.getQualifier()); + Assert.assertEquals(Default.class, pageFragmentDefault.getQualifier()); + } + + public static class PageFragment { + + @JavaScript + private Document document; + + @Drone + private WebDriver browser; + + @FindBy(tagName="h1") + private WebElement header; + + @ArquillianResource + private JavascriptExecutor javascriptExecutor; + + @ArquillianResource + private GrapheneContext context; + + public String getCurrentURL() { + return browser.getCurrentUrl(); + } + + public String getHeaderTextViaJavaScriptInterface() { + return document.getElementsByTagName("h1").get(0).getText().trim(); + } + + public Class<?> getQualifier() { + return context.getQualifier(); + } + + public String getTitleViaJavaScriptExecutor() { + return (String) javascriptExecutor.executeScript("return document.title"); + } + + public WebElement header() { + return header; + } + + public WebDriver browser() { + return browser; + } + + } + +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageObjects.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageObjects.java new file mode 100644 index 000000000..d7a73cd87 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageObjects.java @@ -0,0 +1,174 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.ftest.parallel; + +import junit.framework.Assert; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.javascript.JavaScript; +import org.jboss.arquillian.graphene.spi.annotations.Page; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import qualifier.Browser1; +import qualifier.Browser2; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +@RunWith(Arquillian.class) +public class TestPageObjects extends AbstractParallelTest { + + @Page + @Browser1 + private SimplePage page1; + + @Page + @Browser2 + private SimplePage page2; + + @Page + private SimplePage pageDefault; + + @Test + public void testNotNull() { + Assert.assertNotNull(page1); + Assert.assertNotNull(page2); + Assert.assertNotNull(pageDefault); + } + + @Test + public void testHeadersViaAttributes() { + loadPage(); + + Assert.assertNotNull(page1.header); + Assert.assertNotNull(page2.header); + Assert.assertNotNull(pageDefault.header); + + Assert.assertEquals("Page 1", page1.header.getText().trim()); + Assert.assertEquals("Page 2", page2.header.getText().trim()); + Assert.assertEquals("Page Default", pageDefault.header.getText().trim()); + } + + @Test + public void testHeadersViaMethod() { + loadPage(); + + Assert.assertNotNull(page1.header()); + Assert.assertNotNull(page2.header()); + Assert.assertNotNull(pageDefault.header()); + + Assert.assertEquals("Page 1", page1.header().getText().trim()); + Assert.assertEquals("Page 2", page2.header().getText().trim()); + Assert.assertEquals("Page Default", pageDefault.header().getText().trim()); + } + + @Test + public void testDroneInPageObjects() { + loadPage(); + + String url1 = browser1.getCurrentUrl(); + String url2 = browser2.getCurrentUrl(); + String urlDefault = browserDefault.getCurrentUrl(); + + Assert.assertNotNull(page1.browser()); + Assert.assertNotNull(page2.browser()); + Assert.assertNotNull(pageDefault.browser()); + + Assert.assertEquals(url1, page1.getCurrentURL()); + Assert.assertEquals(url2, page2.getCurrentURL()); + Assert.assertEquals(urlDefault, pageDefault.getCurrentURL()); + } + + @Test + public void testJavaScriptInterfaceInPageObjects() { + loadPage(); + Assert.assertEquals("Page 1", page1.getHeaderTextViaJavaScriptInterface().trim()); + Assert.assertEquals("Page 2", page2.getHeaderTextViaJavaScriptInterface().trim()); + Assert.assertEquals("Page Default", pageDefault.getHeaderTextViaJavaScriptInterface().trim()); + } + + @Test + public void testJavaScriptExecutorInPageObjects() { + loadPage(); + + Assert.assertEquals("Page 1", page1.getTitleViaJavaScriptExecutor().trim()); + Assert.assertEquals("Page 2", page2.getTitleViaJavaScriptExecutor().trim()); + Assert.assertEquals("Page Default", pageDefault.getTitleViaJavaScriptExecutor().trim()); + } + + @Test + public void testGrapheneContextQualifier() { + Assert.assertEquals(Browser1.class, page1.getQualifier()); + Assert.assertEquals(Browser2.class, page2.getQualifier()); + Assert.assertEquals(Default.class, pageDefault.getQualifier()); + } + + public static class SimplePage { + + @FindBy(tagName="h1") + private WebElement header; + + @JavaScript + private Document document; + + @ArquillianResource + private JavascriptExecutor javascriptExecutor; + + @ArquillianResource + private GrapheneContext context; + + @Drone + private WebDriver browser; + + public String getCurrentURL() { + return browser.getCurrentUrl(); + } + + public String getTitleViaJavaScriptExecutor() { + return (String) javascriptExecutor.executeScript("return document.title"); + } + + public String getHeaderTextViaJavaScriptInterface() { + return document.getElementsByTagName("h1").get(0).getText().trim(); + } + + public Class<?> getQualifier() { + return context.getQualifier(); + } + + public WebElement header() { + return header; + } + + public WebDriver browser() { + return browser; + } + } + +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestTestClass.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestTestClass.java new file mode 100644 index 000000000..06ac92c37 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestTestClass.java @@ -0,0 +1,142 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.ftest.parallel; + +import junit.framework.Assert; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.javascript.JavaScript; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebElement; +import qualifier.Browser1; +import qualifier.Browser2; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +@RunWith(Arquillian.class) +public class TestTestClass extends AbstractParallelTest { + + @Browser1 + @JavaScript + private Document document1; + + @Browser2 + @JavaScript + private Document document2; + + @JavaScript + private Document documentDefault; + + @Browser1 + @ArquillianResource + private JavascriptExecutor javaScriptExecutor1; + + @Browser2 + @ArquillianResource + private JavascriptExecutor javaScriptExecutor2; + + @ArquillianResource + private JavascriptExecutor javaScriptExecutorDefault; + + @Browser1 + @ArquillianResource + private GrapheneContext context1; + + @Browser2 + @ArquillianResource + private GrapheneContext context2; + + @ArquillianResource + private GrapheneContext contextDefault; + + @Test + public void testJavaScriptNotNull() { + Assert.assertNotNull(document1); + Assert.assertNotNull(document2); + Assert.assertNotNull(documentDefault); + } + + @Test + public void testDroneNotNull() { + Assert.assertNotNull(browser1); + Assert.assertNotNull(browser2); + Assert.assertNotNull(browserDefault); + } + + @Test + public void testArquillianResourcesNotNull() { + Assert.assertNotNull(javaScriptExecutor1); + Assert.assertNotNull(javaScriptExecutor2); + Assert.assertNotNull(javaScriptExecutorDefault); + } + + @Test + public void testJavaScriptInterfaceInvocation() { + loadPage(); + Assert.assertEquals(1, document1.getElementsByTagName("h1").size()); + Assert.assertEquals(1, document2.getElementsByTagName("h1").size()); + Assert.assertEquals(1, documentDefault.getElementsByTagName("h1").size()); + Assert.assertEquals("Page 1", document1.getElementsByTagName("h1").get(0).getText()); + Assert.assertEquals("Page 2", document2.getElementsByTagName("h1").get(0).getText()); + Assert.assertEquals("Page Default", documentDefault.getElementsByTagName("h1").get(0).getText()); + } + + @Test + public void testJavaScriptExecutorInvocation() { + loadPage(); + + String title1 = (String) javaScriptExecutor1.executeScript("return document.title"); + String title2 = (String) javaScriptExecutor2.executeScript("return document.title"); + String titleDefault = (String) javaScriptExecutorDefault.executeScript("return document.title"); + + Assert.assertEquals("Page 1", title1); + Assert.assertEquals("Page 2", title2); + Assert.assertEquals("Page Default", titleDefault); + } + + @Test + public void testOpenPage() { + loadPage(); + WebElement header1 = browser1.findElement(By.tagName("h1")); + WebElement header2 = browser2.findElement(By.tagName("h1")); + WebElement headerDefault = browserDefault.findElement(By.tagName("h1")); + Assert.assertNotNull(header1); + Assert.assertNotNull(header2); + Assert.assertNotNull(headerDefault); + Assert.assertEquals("Page 1", header1.getText().trim()); + Assert.assertEquals("Page 2", header2.getText().trim()); + Assert.assertEquals("Page Default", headerDefault.getText().trim()); + } + + @Test + public void testGrapheneContextQualifier() { + Assert.assertEquals(Browser1.class, context1.getQualifier()); + Assert.assertEquals(Browser2.class, context2.getQualifier()); + Assert.assertEquals(Default.class, contextDefault.getQualifier()); + } +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/webdriver/FindElementTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/webdriver/FindElementTestCase.java similarity index 99% rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/webdriver/FindElementTestCase.java rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/webdriver/FindElementTestCase.java index 25cb725fc..ace21e4e9 100644 --- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/webdriver/FindElementTestCase.java +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/webdriver/FindElementTestCase.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.webdriver; +package org.jboss.arquillian.graphene.ftest.webdriver; import java.net.URL; import org.jboss.arquillian.drone.api.annotation.Drone; diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser1.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser1.java new file mode 100644 index 000000000..30e54e10a --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser1.java @@ -0,0 +1,35 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package qualifier; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.jboss.arquillian.drone.api.annotation.Qualifier; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.PARAMETER }) +@Qualifier +public @interface Browser1 { + +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser2.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser2.java new file mode 100644 index 000000000..dc43f8b89 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser2.java @@ -0,0 +1,34 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package qualifier; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.jboss.arquillian.drone.api.annotation.Qualifier; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.PARAMETER }) +@Qualifier +public @interface Browser2 { +} diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/default.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/default.html new file mode 100644 index 000000000..01663a6ac --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/default.html @@ -0,0 +1,41 @@ +<html> + <head> + <title>Page Default</title> + <script> + var XMLHttpArray = [ + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject("Msxml2.XMLHTTP")}, + function() {return new ActiveXObject("Msxml2.XMLHTTP")}, + function() {return new ActiveXObject("Microsoft.XMLHTTP")} + ]; + function createXMLHTTPObject(){ + var xmlhttp = false; + for(var i=0; i<XMLHttpArray.length; i++){ + try{ + xmlhttp = XMLHttpArray[i](); + }catch(e){ + continue; + } + break; + } + return xmlhttp; + } + function MakeRequst(){ + var xmlhttp = createXMLHTTPObject(); + xmlhttp.onreadystatechange = function() { + if(this.readyState == 4) { + callback(); + } + } + xmlhttp.open("get", "ourside.html", true); + xmlhttp.send(); + return true; + } + </script> + </head> + <body> + <h1>Page Default</h1> + <a href="outside.html" id="http">HTTP request</a><br/> + <a href="#" id="xhr" onclick="MakeRequst()">XHR request</a> + </body> +</html> \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/one.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/one.html new file mode 100644 index 000000000..c4708b6b1 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/one.html @@ -0,0 +1,41 @@ +<html> + <head> + <title>Page 1</title> + <script> + var XMLHttpArray = [ + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject("Msxml2.XMLHTTP")}, + function() {return new ActiveXObject("Msxml2.XMLHTTP")}, + function() {return new ActiveXObject("Microsoft.XMLHTTP")} + ]; + function createXMLHTTPObject(){ + var xmlhttp = false; + for(var i=0; i<XMLHttpArray.length; i++){ + try{ + xmlhttp = XMLHttpArray[i](); + }catch(e){ + continue; + } + break; + } + return xmlhttp; + } + function MakeRequst(){ + var xmlhttp = createXMLHTTPObject(); + xmlhttp.onreadystatechange = function() { + if(this.readyState == 4) { + callback(); + } + } + xmlhttp.open("get", "ourside.html", true); + xmlhttp.send(); + return true; + } + </script> + </head> + <body> + <h1>Page 1</h1> + <a href="outside.html" id="http">HTTP request</a><br/> + <a href="#" id="xhr" onclick="MakeRequst()">XHR request</a> + </body> +</html> \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/outside.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/outside.html new file mode 100644 index 000000000..e69de29bb diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/two.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/two.html new file mode 100644 index 000000000..e3ab0378f --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/two.html @@ -0,0 +1,41 @@ +<html> + <head> + <title>Page 2</title> + <script> + var XMLHttpArray = [ + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject("Msxml2.XMLHTTP")}, + function() {return new ActiveXObject("Msxml2.XMLHTTP")}, + function() {return new ActiveXObject("Microsoft.XMLHTTP")} + ]; + function createXMLHTTPObject(){ + var xmlhttp = false; + for(var i=0; i<XMLHttpArray.length; i++){ + try{ + xmlhttp = XMLHttpArray[i](); + }catch(e){ + continue; + } + break; + } + return xmlhttp; + } + function MakeRequst(){ + var xmlhttp = createXMLHTTPObject(); + xmlhttp.onreadystatechange = function() { + if(this.readyState == 4) { + callback(); + } + } + xmlhttp.open("get", "ourside.html", true); + xmlhttp.send(); + return true; + } + </script> + </head> + <body> + <h1>Page 2</h1> + <a href="outside.html" id="http">HTTP request</a><br/> + <a href="#" id="xhr" onclick="MakeRequst()">XHR request</a> + </body> +</html> \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-impl/pom.xml b/graphene-webdriver/graphene-webdriver-impl/pom.xml index 9e6b5872e..0e55e7cb2 100644 --- a/graphene-webdriver/graphene-webdriver-impl/pom.xml +++ b/graphene-webdriver/graphene-webdriver-impl/pom.xml @@ -37,6 +37,11 @@ <artifactId>selenium-support</artifactId> <scope>provided</scope> </dependency> + <!-- Arquillian Drone --> + <dependency> + <groupId>org.jboss.arquillian.extension</groupId> + <artifactId>arquillian-drone-impl</artifactId> + </dependency> <!-- Runtime Dependencies --> <dependency> @@ -76,7 +81,7 @@ <groupId>org.jboss.arquillian.config</groupId> <artifactId>arquillian-config-api</artifactId> </dependency> - + <dependency> <groupId>org.jboss.arquillian.core</groupId> <artifactId>arquillian-core-impl-base</artifactId> diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserActions.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserActions.java new file mode 100644 index 000000000..a83647dc0 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserActions.java @@ -0,0 +1,95 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; + +/** + * This class provides a way to perform actions dependent on browser context. + * + * @author <a href="mailto:[email protected]">Jan Papousek</a> + * @see BrowserLocal + */ +public class BrowserActions { + + Map<BrowserLocal, Object> browserLocals = new HashMap<BrowserLocal, Object>(); + + private final String name; + + private static ThreadLocal<BrowserActions> currentBrowserActions = new ThreadLocal<BrowserActions>(); + private static ThreadLocal<BrowserActions> lastBrowserActions = new ThreadLocal<BrowserActions>(); + + public BrowserActions(String name) { + this.name = name; + } + + /** + * Performs the given action in a context associated to this browser actions. + * + * @param <T> return type of the given action + * @param action action to be invoked in the context + * @return value returned by the given action + * @throws Exception + */ + public <T> T performAction(Callable<T> action) throws Exception { + if (currentBrowserActions.get() != null && currentBrowserActions.get() != this) { + throw new IllegalStateException("There is an browser interleaving of " + currentBrowserActions().getName() + " and " + this.getName() + "."); + } + currentBrowserActions.set(this); + lastBrowserActions.set(this); + try { + return action.call(); + } finally { + currentBrowserActions.set(null); + } + } + + /** + * @return browser actions associated to the current browser context. + * @throws IllegalStateException if there is no active browser context available + */ + public static BrowserActions currentBrowserActions() { + BrowserActions browserActions = currentBrowserActions.get(); + if (browserActions == null) { + throw new IllegalStateException("There are no active browser actions available."); + } + return browserActions; + } + + /** + * Get the browser actions associated to the last active browser context. + * @return the last active browser context of null, if it is not available + */ + public static BrowserActions lastBrowserActions() { + return lastBrowserActions.get(); + } + + /** + * @return name of the browser context + */ + public String getName() { + return name; + } + +} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserLocal.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserLocal.java new file mode 100644 index 000000000..c065e1943 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserLocal.java @@ -0,0 +1,136 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene; + +/** + * This class provides browser-local variables. These variables differ from + * their normal counterparts in that each browser context that accesses one (via its + * <tt>get</tt> or <tt>set</tt> method) has its own, independently initialized + * copy of the variable. <tt>BrowserLocal</tt> instances are typically private + * static fields in classes that wish to associate state with a browser context. + * + * @author <a href="mailto:[email protected]">Jan Papousek</a> + * @see ThreadLocal + * @see BrowserActions + */ +public class BrowserLocal<T> { + + /** + * Returns the value in the current browser context's copy of this + * browser-local variable. If the variable has no value for the + * current browser context, it is first initialized to the value returned + * by an invocation of the {@link #initialValue} method. + * + * @return the current browser context's value of this browser-local + * @throws IllegalStateException if there is no active browser context + */ + public T get() { + BrowserActions browser = BrowserActions.currentBrowserActions(); + T result = (T) browser.browserLocals.get(this); + if (result == null) { + T init = initialValue(); + if (init != null) { + browser.browserLocals.put(this, init); + return init; + } + } + return result; + } + + /** + * Returns the value in the last browser context's copy of this + * browser-local variable. If the variable has no value for the + * last browser context, it is first initialized to the value returned + * by an invocation of the {@link #initialValue} method. + * + * <p>If the last browser context is not available, null is returned. + * + * @return the last browser context's value of this browser-local + */ + public T getLast() { + BrowserActions browser = BrowserActions.lastBrowserActions(); + if (browser == null) { + return null; + } + T result = (T) browser.browserLocals.get(this); + if (result == null) { + T init = initialValue(); + if (init != null) { + browser.browserLocals.put(this, init); + return init; + } + } + return result; + } + + /** + * Returns the current browser context's "initial value" for this + * browser-local variable. This method will be invoked the first + * time a browser context accesses the variable with the {@link #get} + * method, unless the browser context previously invoked the {@link #set} + * method, in which case the <tt>initialValue</tt> method will not + * be invoked for the browser context. Normally, this method is invoked at + * most once per browser context, but it may be invoked again in case of + * subsequent invocations of {@link #remove} followed by {@link #get}. + * + * <p>This implementation simply returns <tt>null</tt>; if the + * programmer desires browser-local variables to have an initial + * value other than <tt>null</tt>, <tt>BrowserLocal</tt> must be + * subclassed, and this method overridden. Typically, an + * anonymous inner class will be used. + * + * @return the initial value for this browser-local + */ + protected T initialValue() { + return null; + } + + /** + * Removes the current browser context's value for this browser-local + * variable. If this browser-local variable is subsequently + * {@linkplain #get read} by the current browser context, its value will be + * reinitialized by invoking its {@link #initialValue} method, + * unless its value is {@linkplain #set set} by the current browser context + * in the interim. This may result in multiple invocations of the + * <tt>initialValue</tt> method in the current browser context. + * + * @throws IllegalStateException if there is no active browser context + */ + public void remove() { + BrowserActions.currentBrowserActions().browserLocals.remove(this); + } + + /** + * Sets the current browser context's copy of this browser-local variable + * to the specified value. Most subclasses will have no need to + * override this method, relying solely on the {@link #initialValue} + * method to set the values of browser-locals. + * + * @param value the value to be stored in the current browser context's copy of + * this browser-local. + * @throws IllegalStateException if there is no active browser context + */ + public void set(T value) { + BrowserActions.currentBrowserActions().browserLocals.put(this, value); + } + +} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java index 0c279dc70..3537c50c1 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java @@ -26,12 +26,14 @@ import org.jboss.arquillian.graphene.condition.attribute.ElementAttributeConditionFactory; import org.jboss.arquillian.graphene.condition.element.WebElementConditionFactory; import org.jboss.arquillian.graphene.condition.locator.ElementLocatorConditionFactory; -import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; -import org.jboss.arquillian.graphene.context.GrapheneContext; import org.jboss.arquillian.graphene.enricher.PageFragmentEnricher; +import org.jboss.arquillian.graphene.guard.RequestGuard; import org.jboss.arquillian.graphene.guard.RequestGuardFactory; +import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory; import org.jboss.arquillian.graphene.page.RequestType; +import org.jboss.arquillian.graphene.page.document.Document; +import org.jboss.arquillian.graphene.proxy.GrapheneProxy; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.jboss.arquillian.graphene.wait.WebDriverWait; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; @@ -120,7 +122,7 @@ public static ElementConditionFactory element(By locator) { * @return the guarded object */ public static <T> T guardHttp(T target) { - return RequestGuardFactory.guard(target, RequestType.HTTP, true); + return getRequestGuardFactoryFor(target).guard(target, RequestType.HTTP, true); } /** @@ -133,7 +135,7 @@ public static <T> T guardHttp(T target) { * @return the guarded object */ public static <T> T guardNoRequest(T target) { - return RequestGuardFactory.guard(target, RequestType.NONE, true); + return getRequestGuardFactoryFor(target).guard(target, RequestType.NONE, true); } /** @@ -149,7 +151,7 @@ public static <T> T guardNoRequest(T target) { */ @Deprecated public static <T> T guardXhr(T target) { - return RequestGuardFactory.guard(target, RequestType.XHR, true); + return guardAjax(target); } /** @@ -162,43 +164,60 @@ public static <T> T guardXhr(T target) { * @return the guarded object */ public static <T> T guardAjax(T target) { - return RequestGuardFactory.guard(target, RequestType.XHR, true); + return getRequestGuardFactoryFor(target).guard(target, RequestType.XHR, true); } public static <T> T waitForHttp(T target) { - return RequestGuardFactory.guard(target, RequestType.HTTP, false); + return getRequestGuardFactoryFor(target).guard(target, RequestType.HTTP, false); } public static WebDriverWait<Void> waitAjax() { - return waitAjax(GrapheneContext.getProxy()); + return waitAjax(context().getWebDriver()); } public static WebDriverWait<Void> waitAjax(WebDriver driver) { - return new WebDriverWait<Void>(null, driver, getConfiguration().getWaitAjaxInterval()); + return new WebDriverWait<Void>(null, driver, ((GrapheneProxyInstance) driver).getContext().getConfiguration().getWaitAjaxInterval()); } public static WebDriverWait<Void> waitGui() { - return waitGui(GrapheneContext.getProxy()); + return waitGui(context().getWebDriver()); } public static WebDriverWait<Void> waitGui(WebDriver driver) { - return new WebDriverWait<Void>(null, driver, getConfiguration().getWaitGuiInterval()); + return new WebDriverWait<Void>(null, driver, ((GrapheneProxyInstance) driver).getContext().getConfiguration().getWaitGuiInterval()); } public static WebDriverWait<Void> waitModel() { - return waitModel(GrapheneContext.getProxy()); + return waitModel(context().getWebDriver()); } public static WebDriverWait<Void> waitModel(WebDriver driver) { - return new WebDriverWait<Void>(null, driver, getConfiguration().getWaitModelInterval()); + return new WebDriverWait<Void>(null, driver, ((GrapheneProxyInstance) driver).getContext().getConfiguration().getWaitModelInterval()); } public static <T> T createPageFragment(Class<T> clazz, WebElement root) { return PageFragmentEnricher.createPageFragment(clazz, root); } - private static GrapheneConfiguration getConfiguration() { - return GrapheneConfigurationContext.getProxy(); + private static RequestGuardFactory getRequestGuardFactoryFor(Object target) { + GrapheneContext context; + if (GrapheneProxy.isProxyInstance(target)) { + context = ((GrapheneProxyInstance) target).getContext(); + } else { + context = context(); + } + return new RequestGuardFactory( + JSInterfaceFactory.create(context, RequestGuard.class), + JSInterfaceFactory.create(context, Document.class), + context); } -} + private static GrapheneContext context() { + GrapheneContext context = GrapheneContext.lastContext(); + if (context == null) { + throw new IllegalStateException("The last used Graphene context is not available."); + } + return context; + } + +} \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneContext.java new file mode 100644 index 000000000..da2787e1f --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneContext.java @@ -0,0 +1,307 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; +import org.jboss.arquillian.graphene.enricher.SearchContextInterceptor; +import org.jboss.arquillian.graphene.enricher.StaleElementInterceptor; +import org.jboss.arquillian.graphene.page.extension.PageExtensionInstallatorProvider; +import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry; +import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl; +import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider; +import org.jboss.arquillian.graphene.proxy.GrapheneProxy; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyUtil; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +public class GrapheneContext { + + private final GrapheneConfiguration configuration; + private final WebDriver webDriver; + private final Class<?> qualifier; + /** + * This field contains a reference to the context associated to the current + * active browser actions. {@link LazyContext} instance is placed here. + */ + private static final BrowserLocal<GrapheneContext> CURRENT_CONTEXT = new BrowserLocal<GrapheneContext>(); + /** + * This field contains a map qualifier => real contexts. Real context is + * an instance of {@link GrapheneContext} holding current {@link WebDriver}, + * qualifier and {@link GrapheneConfiguration}. Contexts from this field are + * used by lazy contexts. + */ + private static ThreadLocal<Map<Class<?>, GrapheneContext>> ALL_CONTEXTS = new ThreadLocal<Map<Class<?>, GrapheneContext>>() { + @Override + protected Map<Class<?>, GrapheneContext> initialValue() { + return new HashMap<Class<?>, GrapheneContext>(); + } + }; + /** + * This field contains a map qualifier => lazy context. Lazy context uses + * {@link #ALL_CONTEXTS} field for its method invocation and is able to create + * a proxy for {@link WebDriver}. + */ + private static ThreadLocal<Map<Class<?>, LazyContext>> LAZY_CONTEXTS = new ThreadLocal<Map<Class<?>, LazyContext>>() { + @Override + protected Map<Class<?>, LazyContext> initialValue() { + return new HashMap<Class<?>, LazyContext>(); + } + }; + + private GrapheneContext(GrapheneConfiguration configuration, WebDriver webDriver, Class<?> qualifier) { + this.configuration = configuration; + this.webDriver = webDriver; + this.qualifier = qualifier; + } + + public BrowserActions getBrowserActions() { + return null; + } + + public GrapheneConfiguration getConfiguration() { + return configuration; + } + + public PageExtensionInstallatorProvider getPageExtensionInstallatorProvider() { + return null; + } + + public PageExtensionRegistry getPageExtensionRegistry() { + return null; + } + + /** + * If the {@link WebDriver} instance is not available yet, the returned + * proxy just implements {@link WebDriver} interface. If the {@link WebDriver} + * instance is available, its class is used to create a proxy, so the proxy extends it. + * + * @param interfaces interfaces which should be implemented by the returned {@link WebDriver} + * @return proxy for the {@link WebDriver} held in the context + */ + public WebDriver getWebDriver(Class<?>... interfaces) { + return webDriver; + } + + /** + * @return qualifier identifying the context. + */ + public Class<?> getQualifier() { + return qualifier; + } + + // static methods + static GrapheneContext lastContext() { + return CURRENT_CONTEXT.getLast(); + } + + /** + * Get context associated to the given qualifier. If the {@link Default} + * qualifier is given, the returned context tries to resolves the active context before + * each method invocation. If the active context is available, the returned context + * behaves like the active one. + */ + public static GrapheneContext getContextFor(Class<?> qualifier) { + if (qualifier == null) { + throw new IllegalArgumentException("The parameter 'qualifer' is null."); + } + LazyContext context = (LazyContext) LAZY_CONTEXTS.get().get(qualifier); + if (context == null) { + try { + context = new LazyContext(qualifier, new BrowserActions(qualifier.getName())); + context.handler = GrapheneProxyHandler.forFuture(context, context.getFutureTarget()); + GrapheneProxyInstance proxy = (GrapheneProxyInstance) context.getWebDriver(); + proxy.registerInterceptor(new SearchContextInterceptor()); + proxy.registerInterceptor(new StaleElementInterceptor()); + context.installatorProvider = new RemotePageExtensionInstallatorProvider(context.registry, (JavascriptExecutor) context.getWebDriver(JavascriptExecutor.class)); + final GrapheneContext finalContext = context; + context.getBrowserActions().performAction(new Callable<Void>() { + @Override + public Void call() throws Exception { + CURRENT_CONTEXT.set(finalContext); + return null; + } + }); + LAZY_CONTEXTS.get().put(qualifier, context); + } catch (Exception e) { + throw new IllegalStateException("Can't create a lazy context for " + qualifier.getName() + " qualifier.", e); + } + } + return context; + } + + /** + * Creates a new context for the given webdriver, configuration and qualifier. + * <strong>When you create the context, you are responsible to invoke {@link #removeContextFor(java.lang.Class) } + * after the context is no longer valid.</strong> + * + * @return created context + * @see #getContextFor(java.lang.Class) + * @see #removeContextFor(java.lang.Class) + */ + public static GrapheneContext setContextFor(GrapheneConfiguration configuration, WebDriver driver, Class<?> qualifier) { + GrapheneContext grapheneContext = new GrapheneContext(configuration, driver, qualifier); + ALL_CONTEXTS.get().put(qualifier, grapheneContext); + return getContextFor(qualifier); + } + + /** + * Removes the context associated to the given qualifier. + * @param qualifier + * @see #setContextFor(org.jboss.arquillian.graphene.configuration.GrapheneConfiguration, org.openqa.selenium.WebDriver, java.lang.Class) + */ + public static void removeContextFor(Class<?> qualifier) { + final GrapheneContext context = LAZY_CONTEXTS.get().get(qualifier); + if (context != null) { + try { + ((LazyContext) context).getBrowserActions().performAction(new Callable<Void>() { + @Override + public Void call() throws Exception { + CURRENT_CONTEXT.remove(); + return null; + } + }); + } catch (Exception ignored) { + } + LAZY_CONTEXTS.get().remove(qualifier); + } + ALL_CONTEXTS.get().remove(qualifier); + } + + private static class LazyContext extends GrapheneContext { + + private final Class<?> qualifier; + private final PageExtensionRegistry registry; + private final BrowserActions browserActions; + private PageExtensionInstallatorProvider installatorProvider; + private GrapheneProxyHandler handler; + + public LazyContext(Class<?> qualifier, BrowserActions browserActions) { + super(null, null, null); + this.qualifier = qualifier; + this.browserActions = browserActions; + this.registry = new PageExtensionRegistryImpl(); + } + + @Override + public BrowserActions getBrowserActions() { + LazyContext context = LAZY_CONTEXTS.get().get(getQualifier()); + if (context == null) { + return browserActions; + } else { + return context.browserActions; + } + } + + @Override + public GrapheneConfiguration getConfiguration() { + return getContext(true).getConfiguration(); + } + + @Override + public PageExtensionInstallatorProvider getPageExtensionInstallatorProvider() { + LazyContext context = LAZY_CONTEXTS.get().get(getQualifier()); + if (context == null) { + return installatorProvider; + } else { + return context.installatorProvider; + } + } + + @Override + public PageExtensionRegistry getPageExtensionRegistry() { + LazyContext context = LAZY_CONTEXTS.get().get(getQualifier()); + if (context == null) { + return registry; + } else { + return context.registry; + } + } + + @Override + public Class<?> getQualifier() { + if (Default.class.equals(qualifier)) { + GrapheneContext context = getContext(false); + if (context == null) { + return qualifier; + } if (context instanceof LazyContext) { + return ((LazyContext) context).qualifier; + } else { + return context.getQualifier(); + } + } else { + return qualifier; + } + } + + @Override + public WebDriver getWebDriver(Class<?>... interfaces) { + GrapheneContext context = getContext(false); + if (context == null) { + return GrapheneProxy.getProxyForHandler(handler, WebDriver.class, interfaces); + } else if (GrapheneProxyUtil.isProxy(context.getWebDriver())) { + Class<?> superclass = context.getWebDriver().getClass().getSuperclass(); + if (superclass != null && !GrapheneProxyUtil.isProxy(superclass) && WebDriver.class.isAssignableFrom(superclass)) { + return GrapheneProxy.getProxyForHandler(handler, context.getWebDriver().getClass().getSuperclass(), interfaces); + } else { + return GrapheneProxy.getProxyForHandler(handler, WebDriver.class, interfaces); + } + } else { + return GrapheneProxy.getProxyForHandler(handler, context.getWebDriver().getClass(), interfaces); + } + } + + protected GrapheneContext getContext(boolean exception) { + GrapheneContext context = null; + if (qualifier.equals(Default.class)) { + try { + context = CURRENT_CONTEXT.get(); + } catch (Exception ignored) { + } + } + if (context == null || context.equals(this)) { + context = ALL_CONTEXTS.get().get(qualifier); + } + if (context == null && exception) { + throw new IllegalStateException("There is no context available for qualifier " + qualifier.getName() + ". Available contexts are " + ALL_CONTEXTS.get().keySet() + "."); + } + return context; + } + + protected GrapheneProxy.FutureTarget getFutureTarget() { + return new GrapheneProxy.FutureTarget() { + @Override + public Object getTarget() { + return getContext(true).getWebDriver(); + } + }; + } + } +} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java index fb3de9d5c..8d31ffdbc 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java @@ -25,15 +25,16 @@ import org.jboss.arquillian.drone.spi.Enhancer; import org.jboss.arquillian.graphene.configuration.GrapheneConfigurationResourceProvider; import org.jboss.arquillian.graphene.configuration.GrapheneConfigurator; +import org.jboss.arquillian.graphene.enricher.GrapheneContextProvider; import org.jboss.arquillian.graphene.enricher.GrapheneEnricher; import org.jboss.arquillian.graphene.enricher.JavaScriptEnricher; import org.jboss.arquillian.graphene.enricher.PageFragmentEnricher; import org.jboss.arquillian.graphene.enricher.PageObjectEnricher; import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider; +import org.jboss.arquillian.graphene.enricher.FieldAccessValidatorEnricher; import org.jboss.arquillian.graphene.enricher.WebElementEnricher; import org.jboss.arquillian.graphene.enricher.WebElementWrapperEnricher; import org.jboss.arquillian.graphene.integration.GrapheneEnhancer; -import org.jboss.arquillian.graphene.page.extension.GraphenePageExtensionRegistrar; import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher; import org.jboss.arquillian.test.spi.TestEnricher; import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; @@ -54,11 +55,11 @@ public void register(ExtensionBuilder builder) { builder.service(SearchContextTestEnricher.class, PageFragmentEnricher.class); builder.service(SearchContextTestEnricher.class, PageObjectEnricher.class); builder.service(SearchContextTestEnricher.class, WebElementWrapperEnricher.class); + builder.service(SearchContextTestEnricher.class, FieldAccessValidatorEnricher.class); /** Javascript enrichment */ - builder.service(TestEnricher.class, JavaScriptEnricher.class); - /** Page Extensions */ - builder.observer(GraphenePageExtensionRegistrar.class); + builder.service(SearchContextTestEnricher.class, JavaScriptEnricher.class); /* Resource Providers */ + builder.service(ResourceProvider.class, GrapheneContextProvider.class); builder.service(ResourceProvider.class, GrapheneConfigurationResourceProvider.class); SeleniumResourceProvider.registerAllProviders(builder); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java index 6795a8ac5..2a60ac8af 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java @@ -44,8 +44,8 @@ public class GrapheneConfiguration implements DroneConfiguration<GrapheneConfigu private String defaultElementLocatingStrategy = How.ID_OR_NAME.toString().toLowerCase(); - public String getDefaultElementLocatingStrategy() { - return defaultElementLocatingStrategy; + public How getDefaultElementLocatingStrategy() { + return How.valueOf(defaultElementLocatingStrategy.toUpperCase()); } public long getWaitAjaxInterval() { diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java index 0098e776e..7bf2652c8 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java @@ -28,10 +28,9 @@ import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.arquillian.core.api.annotation.Observes; import org.jboss.arquillian.drone.api.annotation.Default; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; import org.jboss.arquillian.graphene.spi.configuration.GrapheneConfigured; import org.jboss.arquillian.graphene.spi.configuration.GrapheneUnconfigured; -import org.jboss.arquillian.test.spi.annotation.SuiteScoped; +import org.jboss.arquillian.test.spi.annotation.ClassScoped; import org.jboss.arquillian.test.spi.event.suite.AfterClass; import org.jboss.arquillian.test.spi.event.suite.BeforeClass; @@ -42,7 +41,7 @@ public class GrapheneConfigurator { @Inject - @SuiteScoped + @ClassScoped private InstanceProducer<GrapheneConfiguration> configuration; @Inject @@ -57,12 +56,10 @@ public void configureGraphene(@Observes(precedence=100) BeforeClass event, Arqui c.configure(descriptor, Default.class).validate(); this.configuration.set(c); this.configuredEvent.fire(new GrapheneConfigured()); - GrapheneConfigurationContext.set(c); } // configuration has to be dropped after the drone factory destroy the webdriver public void unconfigureGraphene(@Observes(precedence=-100) AfterClass event) { - GrapheneConfigurationContext.reset(); unconfiguredEvent.fire(new GrapheneUnconfigured()); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneConfigurationContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneConfigurationContext.java deleted file mode 100644 index 6102949e5..000000000 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneConfigurationContext.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.arquillian.graphene.context; - -import org.jboss.arquillian.graphene.proxy.GrapheneProxy; -import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; -import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget; - -/** - * <p> - * Class for keeping thread local context of {@link GrapheneConfiguration}. - * </p> - * - * <p> - * Provides {@link #getProxy()} method for accessing that context in model of your tests. - * </p> - * - * <p> - * Proxy specifically handles the situations when no context is set - in this situation, runtime exception with - * NullPointerException cause is thrown. - * </p> - * - * @author <a href="mailto:[email protected]">Jan Papousek</a> - */ -public class GrapheneConfigurationContext { - - private static final ThreadLocal<GrapheneConfiguration> REFERENCE = new ThreadLocal<GrapheneConfiguration>(); - - /** - * Returns the context of configuration for current thread - * - * @return the context of configuration for current thread - * @throws NullPointerException when context is null - */ - static GrapheneConfiguration get() { - GrapheneConfiguration configuration = REFERENCE.get(); - if (configuration == null) { - throw new NullPointerException("configuration is null - it needs to be setup before starting to use it"); - } - return configuration; - } - - /** - * Returns the instance of proxy to thread local context of configuration - * - * @return the instance of proxy to thread local context of configuration - */ - public static GrapheneConfiguration getProxy() { - return GrapheneProxy.getProxyForFutureTarget(TARGET, GrapheneConfiguration.class); - } - - /** - * Returns true if the context is initialized - * - * @return true if the context is initialized - */ - public static boolean isInitialized() { - return REFERENCE.get() != null; - } - - /** - * Resets the WebDriver context for current thread - */ - public static void reset() { - REFERENCE.set(null); - } - - /** - * Sets the configuration context for current thread - * - * @param configuration the configuration instance - * @throws IllegalArgumentException when provided configuration instance is null - */ - public static void set(GrapheneConfiguration configuration) { - if (configuration == null) { - throw new IllegalArgumentException("configuration instance can't be null"); - } - if (GrapheneProxy.isProxyInstance(configuration)) { - throw new IllegalArgumentException("instance of the proxy can't be set to the configuration"); - } - REFERENCE.set(configuration); - } - - private static FutureTarget TARGET = new FutureTarget() { - @Override - public Object getTarget() { - return get(); - } - }; - -} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneContext.java deleted file mode 100644 index a57654a77..000000000 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneContext.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * JBoss, Home of Professional Open Source - * Copyright 2011, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.arquillian.graphene.context; - -import org.jboss.arquillian.graphene.enricher.SearchContextInterceptor; -import org.jboss.arquillian.graphene.enricher.StaleElementInterceptor; -import org.jboss.arquillian.graphene.proxy.GrapheneProxy; -import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget; -import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; -import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler; -import org.jboss.arquillian.graphene.proxy.GrapheneProxyUtil; -import org.openqa.selenium.HasInputDevices; -import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.WebDriver; - -/** - * <p> - * Class for keeping thread local context of {@link WebDriver}. - * </p> - * - * <p> - * Provides {@link #getProxy()} method for accessing that context in model of your tests. - * </p> - * - * <p> - * Proxy specifically handles the situations when no context is set - in this situation, runtime exception with - * NullPointerException cause is thrown. - * </p> - * - * @author Lukas Fryc - */ -public final class GrapheneContext { - - /** - * The thread local context of WebDriver - */ - private static final ThreadLocal<WebDriver> REFERENCE = new ThreadLocal<WebDriver>(); - - /** - * The thread local context of {@link GrapheneProxyHandler} - */ - private static final ThreadLocal<GrapheneProxyHandler> HANDLER = new ThreadLocal<GrapheneProxyHandler>() { - protected GrapheneProxyHandler initialValue() { - return GrapheneProxyHandler.forFuture(TARGET); - }; - }; - - private GrapheneContext() { - } - - private static FutureTarget TARGET = new FutureTarget() { - public Object getTarget() { - return get(); - } - }; - - /** - * Sets the WebDriver context for current thread - * - * @param driver the WebDriver instance - * @throws IllegalArgumentException when provided WebDriver instance is null - */ - public static void set(WebDriver driver) { - if (driver == null) { - throw new IllegalArgumentException("context instance can't be null"); - } - if (GrapheneProxy.isProxyInstance(driver)) { - throw new IllegalArgumentException("instance of the proxy can't be set to the context"); - } - - REFERENCE.set(driver); - } - - /** - * Resets the WebDriver context for current thread - */ - public static void reset() { - REFERENCE.set(null); - HANDLER.get().resetInterceptors(); - } - - /** - * Returns the context of WebDriver for current thread - * - * @return the context of WebDriver for current thread - * @throws NullPointerException when context is null - */ - static WebDriver get() { - WebDriver driver = REFERENCE.get(); - if (driver == null) { - throw new NullPointerException("context is null - it needs to be setup before starting to use it"); - } - return driver; - } - - /** - * Returns true if the context is initialized - * - * @return true if the context is initialized - */ - public static boolean isInitialized() { - return REFERENCE.get() != null; - } - - /** - * Returns the instance of proxy to thread local context of WebDriver - * - * @return the instance of proxy to thread local context of WebDriver - */ - public static WebDriver getProxy() { - WebDriver webdriver = GrapheneProxy.getProxyForHandler(HANDLER.get(), null, WebDriver.class, JavascriptExecutor.class, HasInputDevices.class); - GrapheneProxyInstance proxy = (GrapheneProxyInstance) webdriver; - proxy.registerInterceptor(new SearchContextInterceptor()); - proxy.registerInterceptor(new StaleElementInterceptor()); - return webdriver; - } - - /** - * Returns the proxy for current thread local context of WebDriver which implements all interfaces as the current instance - * in the context. - * - * @return the instance of proxy to thread local context of WebDriver - */ - public static WebDriver getAugmentedProxy() { - WebDriver currentDriver = REFERENCE.get(); - Class<?>[] interfaces = GrapheneProxyUtil.getInterfaces(currentDriver.getClass()); - WebDriver augmentedProxy = GrapheneContext.getProxyForInterfaces(interfaces); - return augmentedProxy; - } - - /** - * Returns the instance of proxy to thread local context of WebDriver, the proxy handles the same interfaces which - * implements provided class. - * - * @return the instance of proxy to thread local context of WebDriver - */ - public static <T extends WebDriver> T getProxyForDriver(Class<T> webDriverImplClass, Class<?>... additionalInterfaces) { - T webdriver = GrapheneProxy.<T>getProxyForHandler(HANDLER.get(), webDriverImplClass, additionalInterfaces); - GrapheneProxyInstance proxy = (GrapheneProxyInstance) webdriver; - proxy.registerInterceptor(new SearchContextInterceptor()); - proxy.registerInterceptor(new StaleElementInterceptor()); - return webdriver; - } - - /** - * Returns the instance of proxy to thread local context of WebDriver, the proxy handles all the interfaces provided as - * parameter. - * - * @return the instance of proxy to thread local context of WebDriver - */ - - public static <T> T getProxyForInterfaces(Class<?>... interfaces) { - Class<?>[] interfacesIncludingWebdriver = GrapheneProxyUtil.concatClasses(interfaces, WebDriver.class); - T webdriver = GrapheneProxy.<T>getProxyForHandler(HANDLER.get(), null, interfacesIncludingWebdriver); - GrapheneProxyInstance proxy = (GrapheneProxyInstance) webdriver; - proxy.registerInterceptor(new SearchContextInterceptor()); - proxy.registerInterceptor(new StaleElementInterceptor()); - return webdriver; - } - - /** - * Returns true when the current context is the instance of provided class. - * - * @param clazz the class used to check current context - * @return true when the current context is the instance of provided class; false otherwise. - */ - public static boolean holdsInstanceOf(Class<?> clazz) { - return clazz.isAssignableFrom(get().getClass()); - } -} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GraphenePageExtensionsContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GraphenePageExtensionsContext.java deleted file mode 100644 index e92abebdb..000000000 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GraphenePageExtensionsContext.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.arquillian.graphene.context; - -import org.jboss.arquillian.graphene.proxy.GrapheneProxy; -import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget; -import org.jboss.arquillian.graphene.page.extension.PageExtensionInstallatorProvider; -import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry; - -/** - * @author <a href="mailto:[email protected]">Jan Papousek</a> - */ -public class GraphenePageExtensionsContext { - - private static final ThreadLocal<PageExtensionRegistry> REGISTRY_REFERENCE = new ThreadLocal<PageExtensionRegistry>(); - private static final ThreadLocal<PageExtensionInstallatorProvider> INSTALLATOR_PROVIDER_REFERENCE = new ThreadLocal<PageExtensionInstallatorProvider>(); - - public static PageExtensionRegistry getRegistryProxy() { - return GrapheneProxy.getProxyForFutureTarget(REGISTRY_TARGET, PageExtensionRegistry.class); - } - - public static PageExtensionInstallatorProvider getInstallatorProviderProxy() { - return GrapheneProxy.getProxyForFutureTarget(INSTALLATOR_PROVIDER_TARGET, PageExtensionInstallatorProvider.class); - } - - /** - * Returns true if the context is initialized - * - * @return true if the context is initialized - */ - public static boolean isInitialized() { - return REGISTRY_REFERENCE.get() != null && INSTALLATOR_PROVIDER_REFERENCE != null; - } - - /** - * Resets the WebDriver context for current thread - */ - public static void reset() { - REGISTRY_REFERENCE.set(null); - INSTALLATOR_PROVIDER_REFERENCE.set(null); - } - - - public static void setInstallatorProvider(PageExtensionInstallatorProvider installatorProvider) { - if (installatorProvider == null) { - throw new IllegalArgumentException("context instance can't be null"); - } - if (GrapheneProxy.isProxyInstance(installatorProvider)) { - throw new IllegalArgumentException("instance of the proxy can't be set to the context"); - } - INSTALLATOR_PROVIDER_REFERENCE.set(installatorProvider); - } - - public static void setRegistry(PageExtensionRegistry registry) { - if (registry == null) { - throw new IllegalArgumentException("context instance can't be null"); - } - if (GrapheneProxy.isProxyInstance(registry)) { - throw new IllegalArgumentException("instance of the proxy can't be set to the context"); - } - REGISTRY_REFERENCE.set(registry); - } - - static PageExtensionInstallatorProvider getInstallatorProvider() { - PageExtensionInstallatorProvider installatorProvider = INSTALLATOR_PROVIDER_REFERENCE.get(); - if (installatorProvider == null) { - throw new NullPointerException("context is null - it needs to be setup before starting to use it"); - } - return installatorProvider; - } - - static PageExtensionRegistry getRegistry() { - PageExtensionRegistry registry = REGISTRY_REFERENCE.get(); - if (registry == null) { - throw new NullPointerException("context is null - it needs to be setup before starting to use it"); - } - return registry; - } - - private static FutureTarget INSTALLATOR_PROVIDER_TARGET = new FutureTarget() { - @Override - public Object getTarget() { - return getInstallatorProvider(); - } - }; - - private static FutureTarget REGISTRY_TARGET = new FutureTarget() { - @Override - public Object getTarget() { - return getRegistry(); - } - }; - -} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java index 720d3695d..5157e2fd3 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java @@ -1,23 +1,24 @@ /** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. + * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and + * individual contributors by the * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. + * @authors tag. See the copyright.txt in the distribution for a full listing of + * individual contributors. * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * This is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + * This software is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this software; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF + * site: http://www.fsf.org. */ package org.jboss.arquillian.graphene.enricher; @@ -28,13 +29,12 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; -import java.util.Arrays; - import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.arquillian.core.spi.ServiceLoader; import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException; import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher; +import org.jboss.arquillian.test.spi.TestClass; import org.jboss.arquillian.test.spi.TestEnricher; import org.openqa.selenium.SearchContext; @@ -50,18 +50,18 @@ public abstract class AbstractSearchContextEnricher implements SearchContextTest * Constant containing new line separator dependent on the environment. */ protected static final String NEW_LINE = System.getProperty("line.separator"); - @Inject private static Instance<ServiceLoader> serviceLoader; /** - * Performs further enrichment on the given instance with the given search context. That means all instances - * {@link TestEnricher} and {@link SearchContextTestEnricher} are invoked. + * Performs further enrichment on the given instance with the given search + * context. That means all instances {@link TestEnricher} and + * {@link SearchContextTestEnricher} are invoked. * * @param searchContext * @param target */ - protected static final void enrichRecursively(SearchContext searchContext, Object target) { + protected static void enrichRecursively(SearchContext searchContext, Object target) { for (TestEnricher enricher : serviceLoader.get().all(TestEnricher.class)) { if (!enricher.getClass().equals(GrapheneEnricher.class)) { enricher.enrich(target); @@ -73,9 +73,10 @@ protected static final void enrichRecursively(SearchContext searchContext, Objec } /** - * It loads a real type of a field defined by parametric type. It searches in declaring class and super class. E. g. if a - * field is declared as 'A fieldName', It tries to find type parameter called 'A' in super class declaration and its - * evaluation in the class declaring the given field. + * It loads a real type of a field defined by parametric type. It searches + * in declaring class and super class. E. g. if a field is declared as 'A + * fieldName', It tries to find type parameter called 'A' in super class + * declaration and its evaluation in the class declaring the given field. * * @param field * @param testCase @@ -91,7 +92,7 @@ protected final Class<?> getActualType(Field field, Object testCase) { // the type parameter has the same index as the actual type String fieldParameterTypeName = field.getGenericType().toString(); - int index = Arrays.asList(superClassTypeParameters).indexOf(fieldParameterTypeName); + int index; for (index = 0; index < superClassTypeParameters.length; index++) { String superClassTypeParameterName = superClassTypeParameters[index].getName(); if (fieldParameterTypeName.equals(superClassTypeParameterName)) { @@ -103,7 +104,8 @@ protected final Class<?> getActualType(Field field, Object testCase) { } /** - * It loads the concrete type of list items. E.g. for List<String>, String is returned. + * It loads the concrete type of list items. E.g. for List<String>, String + * is returned. * * @param listField * @return @@ -124,8 +126,8 @@ protected final Class<?> getListType(Field listField) throws ClassNotFoundExcept * @throws SecurityException * @throws NoSuchMethodException */ - protected static final <T> T instantiate(Class<T> clazz, Object... args) throws NoSuchMethodException, SecurityException, InstantiationException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException { + protected static <T> T instantiate(Class<T> clazz, Object... args) throws NoSuchMethodException, SecurityException, InstantiationException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<?> outerClass = clazz.getDeclaringClass(); // load constructor and rea; arguments @@ -135,7 +137,7 @@ protected static final <T> T instantiate(Class<T> clazz, Object... args) throws if (outerClass == null || Modifier.isStatic(clazz.getModifiers())) { argTypes = new Class<?>[args.length]; realArgs = args; - for (int i=0; i<args.length; i++) { + for (int i = 0; i < args.length; i++) { argTypes[i] = args[i].getClass(); } } else { @@ -143,9 +145,9 @@ protected static final <T> T instantiate(Class<T> clazz, Object... args) throws realArgs = new Object[args.length + 1]; argTypes[0] = outerClass; realArgs[0] = instantiate(outerClass); - for (int i=0; i<args.length; i++) { - argTypes[i+1] = args[i].getClass(); - realArgs[i+1] = args[i]; + for (int i = 0; i < args.length; i++) { + argTypes[i + 1] = args[i].getClass(); + realArgs[i + 1] = args[i]; } } Constructor<T> construtor; @@ -162,7 +164,7 @@ protected static final <T> T instantiate(Class<T> clazz, Object... args) throws return construtor.newInstance(realArgs); } - protected static final void setValue(Field field, Object target, Object value) { + protected static void setValue(Field field, Object target, Object value) { boolean accessible = field.isAccessible(); if (!accessible) { @@ -172,7 +174,7 @@ protected static final void setValue(Field field, Object target, Object value) { field.set(target, value); } catch (Exception ex) { throw new GrapheneTestEnricherException("During enriching of " + NEW_LINE + target.getClass() + NEW_LINE - + " the field " + NEW_LINE + field + " was not able to be set! Check the cause!", ex); + + " the field " + NEW_LINE + field + " was not able to be set! Check the cause!", ex); } if (!accessible) { field.setAccessible(false); diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java new file mode 100644 index 000000000..772b3c35a --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java @@ -0,0 +1,61 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.enricher; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.List; +import java.util.logging.Logger; +import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher; +import org.openqa.selenium.SearchContext; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +public class FieldAccessValidatorEnricher implements SearchContextTestEnricher { + + private static final Logger LOGGER = Logger.getLogger(FieldAccessValidatorEnricher.class.getName()); + + @Override + public void enrich(SearchContext searchContext, Object target) { + List<Field> fields = ReflectionHelper.getFields(target.getClass()); + for (Field field : fields) { + checkFieldValidity(searchContext, target, field); + } + + } + + protected void checkFieldValidity(final SearchContext searchContext, final Object target, final Field field) { + if (!Modifier.isStatic(field.getModifiers()) || !Modifier.isFinal(field.getModifiers())) { + // public field + if (searchContext != null && field.isAccessible() || Modifier.isPublic(field.getModifiers())) { + final String message = "Public field '" + field.getName() + "' found in " + target.getClass().getName() + ". Direct access to fields outside of the declaring class is not allowed."; + LOGGER.warning(message); + } + // package friendly field + if (searchContext != null && !field.getName().startsWith("this$") && !Modifier.isPrivate(field.getModifiers()) && !Modifier.isProtected(field.getModifiers())) { + final String message = "Package-friendly field '" + field.getName() + "' found in " + target.getClass().getName() + ". Direct access to fields outside of the declaring class is not allowed."; + LOGGER.warning(message); + } + } + } +} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneContextProvider.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneContextProvider.java new file mode 100644 index 000000000..5964c6939 --- /dev/null +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneContextProvider.java @@ -0,0 +1,44 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.arquillian.graphene.enricher; + +import java.lang.annotation.Annotation; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; + +/** + * @author <a href="mailto:[email protected]">Jan Papousek</a> + */ +public class GrapheneContextProvider implements ResourceProvider { + + @Override + public boolean canProvide(Class<?> type) { + return type.equals(GrapheneContext.class); + } + + @Override + public Object lookup(ArquillianResource resource, Annotation... qualifiers) { + return GrapheneContext.getContextFor(ReflectionHelper.getQualifier(qualifiers)); + } + +} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java index d50293d28..80b0506ae 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java @@ -26,9 +26,7 @@ import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.arquillian.core.spi.ServiceLoader; -import org.jboss.arquillian.graphene.context.GrapheneContext; import org.jboss.arquillian.test.spi.TestEnricher; -import org.openqa.selenium.WebDriver; /** * Graphene enricher calls all {@link SearchContextTestEnricher} instances to start @@ -44,9 +42,8 @@ public class GrapheneEnricher implements TestEnricher { @Override public void enrich(Object o) { - final WebDriver driver = GrapheneContext.getProxy(); for (SearchContextTestEnricher enricher: serviceLoader.get().all(SearchContextTestEnricher.class)) { - enricher.enrich(driver, o); + enricher.enrich(null, o); } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java index e27c195ea..7585486c2 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java @@ -1,61 +1,56 @@ /** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. + * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and + * individual contributors by the * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. + * @authors tag. See the copyright.txt in the distribution for a full listing of + * individual contributors. * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * This is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + * This software is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this software; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF + * site: http://www.fsf.org. */ package org.jboss.arquillian.graphene.enricher; import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.util.Collection; -import org.jboss.arquillian.graphene.context.GrapheneContext; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory; import org.jboss.arquillian.graphene.javascript.JavaScript; -import org.jboss.arquillian.test.spi.TestEnricher; -import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.WebDriver; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; +import org.openqa.selenium.SearchContext; /** * @author <a href="mailto:[email protected]">Jan Papousek</a> */ -public class JavaScriptEnricher implements TestEnricher { +public class JavaScriptEnricher extends AbstractSearchContextEnricher { @Override - public void enrich(Object o) { - Collection<Field> fields = ReflectionHelper.getFieldsWithAnnotation(o.getClass(), JavaScript.class); - for (Field field: fields) { + public void enrich(final SearchContext searchContext, Object target) { + Collection<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), JavaScript.class); + for (Field field : fields) { + GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext(); + if (grapheneContext == null) { + grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations())); + } if (!field.isAccessible()) { field.setAccessible(true); } try { - field.set(o, JSInterfaceFactory.create( - (WebDriver) GrapheneContext.getProxyForInterfaces(JavascriptExecutor.class), - field.getType())); + field.set(target, JSInterfaceFactory.create(grapheneContext, field.getType())); } catch (Exception e) { - throw new IllegalStateException("Can't inject value to the field '" + field.getName() + "' declared in class '" + field.getDeclaringClass().getName() +"'"); + throw new IllegalStateException("Can't inject value to the field '" + field.getName() + "' declared in class '" + field.getDeclaringClass().getName() + "'"); } } } - - @Override - public Object[] resolve(Method method) { - return new Object[method.getParameterTypes().length]; - } - } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java index b2bd344bf..778f78af9 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java @@ -1,23 +1,24 @@ /** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. + * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and + * individual contributors by the * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. + * @authors tag. See the copyright.txt in the distribution for a full listing of + * individual contributors. * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * This is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + * This software is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this software; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF + * site: http://www.fsf.org. */ package org.jboss.arquillian.graphene.enricher; @@ -25,14 +26,17 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; - import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.annotation.Inject; -import org.jboss.arquillian.core.spi.ServiceLoader; + +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import org.jboss.arquillian.graphene.enricher.exception.PageFragmentInitializationException; import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities; import org.jboss.arquillian.graphene.proxy.GrapheneProxy; import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.jboss.arquillian.graphene.spi.annotations.Root; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; @@ -40,29 +44,45 @@ import org.openqa.selenium.support.FindBy; /** - * Enricher injecting page fragments ({@link FindBy} annotation is used) to the fields of the given object. + * Enricher injecting page fragments ({@link FindBy} annotation is used) to the + * fields of the given object. * * @author <a href="mailto:[email protected]">Juraj Huska</a> * @author <a href="mailto:[email protected]">Jan Papousek</a> */ public class PageFragmentEnricher extends AbstractSearchContextEnricher { - @SuppressWarnings("unused") @Inject - private Instance<ServiceLoader> serviceLoader; + private Instance<GrapheneConfiguration> configuration; + + public PageFragmentEnricher() { + } + + // because of testing + public PageFragmentEnricher(Instance<GrapheneConfiguration> configuration) { + this.configuration = configuration; + } @Override - public void enrich(SearchContext searchContext, Object target) { + public void enrich(final SearchContext searchContext, Object target) { List<Field> fields = FindByUtilities.getListOfFieldsAnnotatedWithFindBys(target); for (Field field : fields) { + GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext(); + final SearchContext localSearchContext; + if (grapheneContext == null) { + grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations())); + localSearchContext = grapheneContext.getWebDriver(SearchContext.class); + } else { + localSearchContext = searchContext; + } // Page fragment if (isPageFragmentClass(field.getType())) { - setupPageFragment(searchContext, target, field); + setupPageFragment(localSearchContext, target, field); // List<Page fragment> } else { try { if (field.getType().isAssignableFrom(List.class) && isPageFragmentClass(getListType(field))) { - setupPageFragmentList(searchContext, target, field); + setupPageFragmentList(localSearchContext, target, field); } } catch (ClassNotFoundException e) { throw new PageFragmentInitializationException(e.getMessage(), e); @@ -90,7 +110,8 @@ protected final boolean isPageFragmentClass(Class<?> clazz) { } protected final <T> List<T> createPageFragmentList(final Class<T> clazz, final SearchContext searchContext, final By rootBy) { - List<T> result = GrapheneProxy.getProxyForFutureTarget(new FutureTarget() { + GrapheneContext grapheneContext = ((GrapheneProxyInstance) searchContext).getContext(); + List<T> result = GrapheneProxy.getProxyForFutureTarget(grapheneContext, new FutureTarget() { @Override public Object getTarget() { List<WebElement> elements = searchContext.findElements(rootBy); @@ -100,13 +121,13 @@ public Object getTarget() { } return fragments; } - }, List.class); return result; } - public static final <T> T createPageFragment(Class<T> clazz, WebElement root) { + public static <T> T createPageFragment(Class<T> clazz, WebElement root) { try { + GrapheneContext grapheneContext = ((GrapheneProxyInstance) root).getContext(); T pageFragment = instantiate(clazz); List<Field> roots = ReflectionHelper.getFieldsWithAnnotation(clazz, Root.class); if (roots.size() > 1) { @@ -118,7 +139,9 @@ public static final <T> T createPageFragment(Class<T> clazz, WebElement root) { setValue(roots.get(0), pageFragment, root); } enrichRecursively(root, pageFragment); - return pageFragment; + T proxy = GrapheneProxy.getProxyForHandler(GrapheneProxyHandler.forTarget(grapheneContext, pageFragment), clazz); + enrichRecursively(root, proxy); // because of possibility of direct access to attributes from test class + return proxy; } catch (NoSuchMethodException ex) { throw new PageFragmentInitializationException(" Check whether declared Page Fragment has no argument constructor!", ex); @@ -135,15 +158,17 @@ public static final <T> T createPageFragment(Class<T> clazz, WebElement root) { protected final void setupPageFragmentList(SearchContext searchContext, Object target, Field field) throws ClassNotFoundException { + GrapheneContext grapheneContext = ((GrapheneProxyInstance) searchContext).getContext(); //the by retrieved in this way is never null, by default it is ByIdOrName using field name - By rootBy = FindByUtilities.getCorrectBy(field); + By rootBy = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy()); List<?> pageFragments = createPageFragmentList(getListType(field), searchContext, rootBy); setValue(field, target, pageFragments); } protected final void setupPageFragment(SearchContext searchContext, Object target, Field field) { + GrapheneContext grapheneContext = ((GrapheneProxyInstance) searchContext).getContext(); //the by retrieved in this way is never null, by default it is ByIdOrName using field name - By rootBy = FindByUtilities.getCorrectBy(field); + By rootBy = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy()); WebElement root = WebElementUtils.findElementLazily(rootBy, searchContext); Object pageFragment = createPageFragment(field.getType(), root); setValue(field, target, pageFragment); diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java index a22cb3104..dc79b2048 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java @@ -1,23 +1,24 @@ /** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. + * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and + * individual contributors by the * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. + * @authors tag. See the copyright.txt in the distribution for a full listing of + * individual contributors. * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * This is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + * This software is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this software; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF + * site: http://www.fsf.org. */ package org.jboss.arquillian.graphene.enricher; @@ -25,10 +26,11 @@ import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.List; -import org.jboss.arquillian.core.api.Instance; -import org.jboss.arquillian.core.api.annotation.Inject; -import org.jboss.arquillian.core.spi.ServiceLoader; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.enricher.exception.PageObjectInitializationException; +import org.jboss.arquillian.graphene.proxy.GrapheneProxy; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.jboss.arquillian.graphene.spi.annotations.Page; import org.openqa.selenium.SearchContext; @@ -40,15 +42,19 @@ */ public class PageObjectEnricher extends AbstractSearchContextEnricher { - @SuppressWarnings("unused") - @Inject - private Instance<ServiceLoader> serviceLoader; - @Override - public void enrich(SearchContext searchContext, Object target) { + public void enrich(final SearchContext searchContext, Object target) { String errorMsgBegin = ""; List<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), Page.class); for (Field field : fields) { + GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext(); + final SearchContext localSearchContext; + if (grapheneContext == null) { + grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations())); + localSearchContext = grapheneContext.getWebDriver(SearchContext.class); + } else { + localSearchContext = searchContext; + } try { Type type = field.getGenericType(); Class<?> declaredClass; @@ -62,11 +68,9 @@ public void enrich(SearchContext searchContext, Object target) { } errorMsgBegin = "Can not instantiate Page Object " + NEW_LINE + declaredClass + NEW_LINE - + " declared in: " + NEW_LINE + target.getClass().getName() + NEW_LINE; + + " declared in: " + NEW_LINE + target.getClass().getName() + NEW_LINE; - Object page = instantiate(declaredClass); - - enrichRecursively(searchContext, page); + Object page = setupPage(grapheneContext, localSearchContext, declaredClass); setValue(field, target, page); } catch (NoSuchMethodException ex) { @@ -84,4 +88,12 @@ public void enrich(SearchContext searchContext, Object target) { } } + + protected <P> P setupPage(GrapheneContext context, SearchContext searchContext, Class<?> pageClass) throws Exception{ + P page = (P) instantiate(pageClass); + P proxy = GrapheneProxy.getProxyForHandler(GrapheneProxyHandler.forTarget(context, page), pageClass); + enrichRecursively(searchContext, page); + enrichRecursively(searchContext, proxy); // because of possibility of direct access to attributes from test class + return proxy; + } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java index 3e9e71565..60d3c3dcf 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java @@ -27,6 +27,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.drone.api.annotation.Qualifier; /** * SecurityActions @@ -179,6 +181,23 @@ public static boolean isClassPresent(String name) { } } + public static List<Field> getFields(final Class<?> source) { + return AccessController.doPrivileged(new PrivilegedAction<List<Field>>() { + @Override + public List<Field> run() { + List<Field> foundFields = new ArrayList<Field>(); + Class<?> nextSource = source; + while (nextSource != Object.class) { + for (Field field : nextSource.getDeclaredFields()) { + foundFields.add(field); + } + nextSource = nextSource.getSuperclass(); + } + return foundFields; + } + }); + } + public static List<Field> getFieldsWithAnnotation(final Class<?> source, final Class<? extends Annotation> annotationClass) { List<Field> declaredAccessableFields = AccessController.doPrivileged(new PrivilegedAction<List<Field>>() { @Override @@ -221,6 +240,31 @@ public List<Method> run() { return declaredAccessableMethods; } + // method from Drone, SecurityActions + public static Class<?> getQualifier(Annotation[] annotations) { + + if (annotations == null) { + return Default.class; + } + + List<Class<? extends Annotation>> candidates = new ArrayList<Class<? extends Annotation>>(); + + for (Annotation a : annotations) { + if (a.annotationType().isAnnotationPresent(Qualifier.class)) { + candidates.add(a.annotationType()); + } + } + + if (candidates.isEmpty()) { + return Default.class; + } else if (candidates.size() == 1) { + return candidates.get(0); + } + + throw new IllegalStateException("Unable to determine Qualifier, multiple (" + candidates.size() + + ") Qualifier annotations were present"); + } + // -------------------------------------------------------------------------------|| // Inner Classes ----------------------------------------------------------------|| // -------------------------------------------------------------------------------|| diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java index 2ca80f1e4..e63a2c28d 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java @@ -22,10 +22,12 @@ package org.jboss.arquillian.graphene.enricher; import java.lang.reflect.Method; +import org.jboss.arquillian.graphene.proxy.GrapheneProxy; import org.jboss.arquillian.graphene.proxy.Interceptor; import org.jboss.arquillian.graphene.proxy.InvocationContext; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; +import org.openqa.selenium.WebDriver; /** * @author <a href="mailto:[email protected]">Jan Papousek</a> @@ -33,11 +35,17 @@ public class SearchContextInterceptor implements Interceptor { @Override - public Object intercept(InvocationContext context) throws Throwable { + public Object intercept(final InvocationContext context) throws Throwable { + GrapheneProxy.FutureTarget future = new GrapheneProxy.FutureTarget() { + @Override + public Object getTarget() { + return context.getProxy(); + } + }; if (methodsEqual(context.getMethod(), SearchContext.class.getDeclaredMethod("findElement", By.class))) { - return WebElementUtils.findElement((By) context.getArguments()[0], context); + return WebElementUtils.findElement(context.getGrapheneContext(), (By) context.getArguments()[0], future); } else if (methodsEqual(context.getMethod(), SearchContext.class.getDeclaredMethod("findElements", By.class))) { - return WebElementUtils.findElementsLazily((By) context.getArguments()[0], context); + return WebElementUtils.findElementsLazily(context.getGrapheneContext(), (By) context.getArguments()[0], future); } else { return context.invoke(); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java index 3239802f5..a5587b2d4 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java @@ -1,17 +1,12 @@ package org.jboss.arquillian.graphene.enricher; import java.lang.annotation.Annotation; -import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.jboss.arquillian.core.spi.LoadableExtension.ExtensionBuilder; -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.proxy.GrapheneProxy; -import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; -import org.jboss.arquillian.graphene.proxy.Interceptor; -import org.jboss.arquillian.graphene.proxy.InvocationContext; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; import org.openqa.selenium.Capabilities; @@ -133,11 +128,12 @@ public boolean canProvide(Class<?> type) { return type == this.returnType; } - protected <BASE> BASE base() { - return GrapheneContext.getProxyForInterfaces(mediatorType); + protected <BASE> BASE base(Annotation[] annotations) { + WebDriver webdriver = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(annotations)).getWebDriver(mediatorType); + return (BASE) webdriver; } - protected Class<?> getTypeArgument(int i) { + protected final Class<?> getTypeArgument(int i) { ParameterizedType superType = (ParameterizedType) getClass().getGenericSuperclass(); Type[] typeArguments = superType.getActualTypeArguments(); return (Class<?>) typeArguments[i]; @@ -152,7 +148,7 @@ private static class DirectProvider<T> extends SeleniumResourceProvider<T> { @Override public T lookup(ArquillianResource resource, Annotation... qualifiers) { - return base(); + return base(qualifiers); } } @@ -170,38 +166,8 @@ public IndirectProvider() { @Override public Object lookup(ArquillianResource resource, Annotation... qualifiers) { - final M base = base(); - - // this interceptor is created just to create future target of invocation - Interceptor interceptor = new Interceptor() { - - @Override - public Object intercept(final InvocationContext context) throws Throwable { - final Method method = context.getMethod(); - if (method.getDeclaringClass() == mediatorType) { - return GrapheneProxy.getProxyForFutureTarget(new FutureTarget() { - public Object getTarget() { - try { - M unwrappedBase = ((GrapheneProxyInstance) base).unwrap(); - return method.invoke(unwrappedBase, context.getArguments()); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - }, method.getReturnType()); - } else { - throw new IllegalStateException("You cannot invoke method " + method + " on the " + mediatorType); - } - } - }; - - ((GrapheneProxyInstance) base).registerInterceptor(interceptor); - - Object futureTargetProxy = invoke(base); - - ((GrapheneProxyInstance) base).unregisterInterceptor(interceptor); - - return futureTargetProxy; + final M base = base(qualifiers); + return invoke(base); } public abstract T invoke(M mediator); diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java index 13b608f2e..61910f0cc 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java @@ -10,7 +10,6 @@ import org.openqa.selenium.WebDriver; import com.google.common.base.Predicate; -import java.util.concurrent.TimeUnit; import org.openqa.selenium.TimeoutException; public class StaleElementInterceptor implements Interceptor { @@ -21,7 +20,7 @@ public Object intercept(final InvocationContext context) throws Throwable { final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); final AtomicReference<Throwable> staleness = new AtomicReference<Throwable>(); try { - waitGui().until(new Predicate<WebDriver>() { + waitGui(context.getGrapheneContext().getWebDriver()).until(new Predicate<WebDriver>() { @Override public boolean apply(WebDriver driver) { try { diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java index 2413b4173..2e57ce5bb 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java @@ -23,8 +23,13 @@ import java.lang.reflect.Field; import java.util.List; +import org.jboss.arquillian.core.api.Instance; +import org.jboss.arquillian.core.api.annotation.Inject; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; @@ -35,21 +40,40 @@ */ public class WebElementEnricher extends AbstractSearchContextEnricher { + @Inject + private Instance<GrapheneConfiguration> configuration; + + public WebElementEnricher() { + } + + // because of testing + public WebElementEnricher(Instance<GrapheneConfiguration> configuration) { + this.configuration = configuration; + } + @Override - public void enrich(SearchContext searchContext, Object target) { + public void enrich(final SearchContext searchContext, Object target) { try { List<Field> fields = FindByUtilities.getListOfFieldsAnnotatedWithFindBys(target); for (Field field : fields) { + GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext(); + final SearchContext localSearchContext; + if (grapheneContext == null) { + grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations())); + localSearchContext = grapheneContext.getWebDriver(SearchContext.class); + } else { + localSearchContext = searchContext; + } //by should never by null, by default it is ByIdOrName using field name - By by = FindByUtilities.getCorrectBy(field); + By by = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy()); // WebElement if (field.getType().isAssignableFrom(WebElement.class)) { - WebElement element = WebElementUtils.findElementLazily(by, searchContext); + WebElement element = WebElementUtils.findElementLazily(by, localSearchContext); setValue(field, target, element); // List<WebElement> } else if (field.getType().isAssignableFrom(List.class) && getListType(field).isAssignableFrom(WebElement.class)) { - List<WebElement> elements = WebElementUtils.findElementsLazily(by, searchContext); + List<WebElement> elements = WebElementUtils.findElementsLazily(by, localSearchContext); setValue(field, target, elements); } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java index e84410296..5a0c71c87 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java @@ -25,6 +25,8 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.enricher.findby.ByJQuery; import org.jboss.arquillian.graphene.intercept.InterceptorBuilder; import org.jboss.arquillian.graphene.proxy.GrapheneProxy; @@ -49,11 +51,11 @@ public final class WebElementUtils { private WebElementUtils() { } - public static WebElement findElement(final By by, final GrapheneProxy.FutureTarget searchContextFuture) { + public static WebElement findElement(GrapheneContext context, final By by, final GrapheneProxy.FutureTarget searchContextFuture) { // Here the web element has to be found to ensure that SearchContext throws // NoSuchElementException if there is no element with the given By locator. dropProxyAndFindElement(by, (SearchContext) searchContextFuture.getTarget()); - return findElement(new GrapheneProxy.FutureTarget() { + return findElement(context, new GrapheneProxy.FutureTarget() { @Override public Object getTarget() { return dropProxyAndFindElement(by, (SearchContext) searchContextFuture.getTarget()); @@ -61,8 +63,8 @@ public Object getTarget() { }); } - public static List<WebElement> findElementsLazily(final By by, final GrapheneProxy.FutureTarget searchContextFuture) { - return GrapheneProxy.getProxyForFutureTarget(new GrapheneProxy.FutureTarget() { + public static List<WebElement> findElementsLazily(final GrapheneContext context, final By by, final GrapheneProxy.FutureTarget searchContextFuture) { + return GrapheneProxy.getProxyForFutureTarget(context, new GrapheneProxy.FutureTarget() { @Override public Object getTarget() { List<WebElement> result = new ArrayList<WebElement>(); @@ -71,15 +73,15 @@ public Object getTarget() { LOGGER.log(Level.WARNING, EMPTY_FIND_BY_WARNING); } for (int i = 0; i < elements.size(); i++) { - result.add(findElementLazily(by, searchContextFuture, i)); + result.add(findElementLazily(context, by, searchContextFuture, i)); } return result; } }, List.class); } - public static WebElement findElementLazily(final By by, final GrapheneProxy.FutureTarget searchContextFuture, final int indexInList) { - return findElement(new GrapheneProxy.FutureTarget() { + public static WebElement findElementLazily(GrapheneContext context, final By by, final GrapheneProxy.FutureTarget searchContextFuture, final int indexInList) { + return findElement(context, new GrapheneProxy.FutureTarget() { @Override public Object getTarget() { return dropProxyAndFindElements(by, (SearchContext) searchContextFuture.getTarget()).get(indexInList); @@ -88,7 +90,7 @@ public Object getTarget() { } public static WebElement findElementLazily(final By by, final SearchContext searchContext, final int indexInList) { - return findElement(new GrapheneProxy.FutureTarget() { + return findElement(getContext(searchContext), new GrapheneProxy.FutureTarget() { @Override public Object getTarget() { return dropProxyAndFindElements(by, searchContext).get(indexInList); @@ -97,7 +99,7 @@ public Object getTarget() { } public static WebElement findElementLazily(final By by, final SearchContext searchContext) { - return findElement(new GrapheneProxy.FutureTarget() { + return findElement(getContext(searchContext), new GrapheneProxy.FutureTarget() { @Override public Object getTarget() { try { @@ -111,7 +113,7 @@ public Object getTarget() { } public static List<WebElement> findElementsLazily(final By by, final SearchContext searchContext) { - return findElementsLazily(by, new GrapheneProxy.FutureTarget() { + return findElementsLazily(getContext(searchContext), by, new GrapheneProxy.FutureTarget() { @Override public Object getTarget() { return searchContext; @@ -119,8 +121,8 @@ public Object getTarget() { }); } - protected static WebElement findElement(final GrapheneProxy.FutureTarget target) { - final WebElement element = GrapheneProxy.getProxyForFutureTarget(target, WebElement.class, Locatable.class, + protected static WebElement findElement(GrapheneContext context, final GrapheneProxy.FutureTarget target) { + final WebElement element = GrapheneProxy.getProxyForFutureTarget(context, target, WebElement.class, Locatable.class, WrapsElement.class); final GrapheneProxyInstance elementProxy = (GrapheneProxyInstance) element; @@ -135,7 +137,12 @@ protected static WebElement findElement(final GrapheneProxy.FutureTarget target) protected static WebElement dropProxyAndFindElement(By by, SearchContext searchContext) { if (searchContext instanceof GrapheneProxyInstance) { - return ((SearchContext) ((GrapheneProxyInstance) searchContext).unwrap()).findElement(by); + if (by instanceof ByJQuery) { + return by.findElement(searchContext); + } else { + SearchContext unwrapped = (SearchContext) ((GrapheneProxyInstance) searchContext).unwrap(); + return unwrapped.findElement(by); + } } else { return searchContext.findElement(by); } @@ -143,10 +150,21 @@ protected static WebElement dropProxyAndFindElement(By by, SearchContext searchC protected static List<WebElement> dropProxyAndFindElements(By by, SearchContext searchContext) { if (searchContext instanceof GrapheneProxyInstance) { - return ((SearchContext) ((GrapheneProxyInstance) searchContext).unwrap()).findElements(by); + if (by instanceof ByJQuery) { + return by.findElements(searchContext); + } else { + return ((SearchContext) ((GrapheneProxyInstance) searchContext).unwrap()).findElements(by); + } } else { return searchContext.findElements(by); } } + protected static GrapheneContext getContext(Object object) { + if (!GrapheneProxy.isProxyInstance(object)) { + throw new IllegalArgumentException("The parameter [object] has to be instance of " + GrapheneProxyInstance.class.getName() + ", but it is not. The given object is " + object + "."); + } + return ((GrapheneProxyInstance) object).getContext(); + } + } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java index a5b81a982..490ab10b4 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java @@ -7,9 +7,14 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.List; +import org.jboss.arquillian.core.api.Instance; +import org.jboss.arquillian.core.api.annotation.Inject; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException; import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities; import org.jboss.arquillian.graphene.proxy.GrapheneProxy; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; @@ -19,21 +24,40 @@ */ public class WebElementWrapperEnricher extends AbstractSearchContextEnricher { + @Inject + private Instance<GrapheneConfiguration> configuration; + + public WebElementWrapperEnricher() { + } + + // because of testing + public WebElementWrapperEnricher(Instance<GrapheneConfiguration> configuration) { + this.configuration = configuration; + } + @Override public void enrich(final SearchContext searchContext, Object target) { List<Field> fields = FindByUtilities.getListOfFieldsAnnotatedWithFindBys(target); for (Field field: fields) { final Field finalField = field; if (isValidClass(field.getType())) { - final By rootBy = FindByUtilities.getCorrectBy(field); + final SearchContext localSearchContext; + GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext(); + if (grapheneContext == null) { + grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations())); + localSearchContext = grapheneContext.getWebDriver(SearchContext.class); + } else { + localSearchContext = searchContext; + } + final By rootBy = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy()); try { - Object component = GrapheneProxy.getProxyForFutureTarget(new GrapheneProxy.FutureTarget() { + Object component = GrapheneProxy.getProxyForFutureTarget(grapheneContext, new GrapheneProxy.FutureTarget() { @Override public Object getTarget() { try { - return instantiate(finalField.getType(), WebElementUtils.findElementLazily(rootBy, searchContext)); + return instantiate(finalField.getType(), WebElementUtils.findElementLazily(rootBy, localSearchContext)); } catch (Exception e) { - throw new IllegalStateException("Can't instantiate the " + finalField.getType()); + throw new IllegalStateException("Can't instantiate the " + finalField.getType(), e); } } }, field.getType()); diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java index 7d1daa217..36dd74999 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java @@ -15,16 +15,16 @@ */ /** * <p> - * Utility class originally copied from WebDriver. It main purpose is to retrieve correct - * <code>By</code> instance according to the field on which <code>@FindBy</code> or <code>@FinfBys</code> annotation is.</p> - * + * Utility class originally copied from WebDriver. It main purpose is to retrieve correct + * <code>By</code> instance according to the field on which <code>@FindBy</code> or <code>@FinfBys</code> annotation is.</p> + * * <p>The differences are: * <ul> * <li>this class supports also Graphene <code>@FindBy</code> with JQuery locators support</li> * <li>it is able to return default locating strategy according to the <code>GrapheneConfiguration</code></li> * </ul> * </p> - * + * * <p>Altered by <a href="mailto:[email protected]">Juraj Huska</a></p>. */ package org.jboss.arquillian.graphene.enricher.findby; @@ -32,8 +32,6 @@ import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; - -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; import org.openqa.selenium.By; import org.openqa.selenium.support.ByIdOrName; import org.openqa.selenium.support.CacheLookup; @@ -43,10 +41,12 @@ public class Annotations { - private Field field; + private final Field field; + private final org.jboss.arquillian.graphene.enricher.findby.How defaultElementLocatingStrategy; - public Annotations(Field field) { + public Annotations(Field field, org.jboss.arquillian.graphene.enricher.findby.How defaultElementLocatingStrategy) { this.field = field; + this.defaultElementLocatingStrategy = defaultElementLocatingStrategy; } public boolean isLookupCached() { @@ -65,7 +65,7 @@ public By buildBy() { ans = buildByFromGrapheneFindBys(grapheneFindBys); } - org.openqa.selenium.support.FindBys webDriverFindBys = + org.openqa.selenium.support.FindBys webDriverFindBys = field.getAnnotation(org.openqa.selenium.support.FindBys.class); if (ans == null && webDriverFindBys != null) { ans = buildByFromWebDriverFindBys(webDriverFindBys); @@ -117,11 +117,8 @@ private By checkAndProcessEmptyFindBy() { } protected By buildByFromDefault() { - org.jboss.arquillian.graphene.enricher.findby.How how = org.jboss.arquillian.graphene.enricher.findby.How - .valueOf(GrapheneConfigurationContext.getProxy().getDefaultElementLocatingStrategy().toUpperCase()); - String using = field.getName(); - return getByFromGrapheneHow(how, using); + return getByFromGrapheneHow(defaultElementLocatingStrategy, using); } protected By buildByFromGrapheneFindBys(FindBys grapheneFindBys) { diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java index 621f4a0c6..4c7c9052d 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java @@ -23,7 +23,9 @@ import java.util.List; import org.jboss.arquillian.core.spi.Validate; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.SearchContext; @@ -37,7 +39,6 @@ public class ByJQuery extends By { private final String jquerySelector; - private final JQuerySearchContext jQuerySearchContext = JSInterfaceFactory.create(JQuerySearchContext.class); public ByJQuery(String jquerySelector) { Validate.notNull(jquerySelector, "Cannot find elements when jquerySelector is null!"); @@ -55,6 +56,8 @@ public String toString() { @Override public List<WebElement> findElements(SearchContext context) { + GrapheneContext grapheneContext = ((GrapheneProxyInstance) context).getContext(); + JQuerySearchContext jQuerySearchContext = JSInterfaceFactory.create(grapheneContext, JQuerySearchContext.class); List<WebElement> elements; try { // the element is referenced from parent web element diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java index 96d3ab29c..0987610f3 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java @@ -34,13 +34,13 @@ */ public class FindByUtilities { - public static By getCorrectBy(Field field) { - Annotations annotations = new Annotations(field); + public static By getCorrectBy(Field field, How defaultElementLocatingStrategy) { + Annotations annotations = new Annotations(field, defaultElementLocatingStrategy); By by = annotations.buildBy(); - + return by; } - + public static List<Field> getListOfFieldsAnnotatedWithFindBys(Object target) { List<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), FindBy.class); fields.addAll(ReflectionHelper.getFieldsWithAnnotation(target.getClass(), org.jboss.arquillian.graphene.enricher.findby.FindBy.class)); diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java index cb9b43866..34359a1fd 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java @@ -25,8 +25,6 @@ import java.util.concurrent.TimeUnit; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; -import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory; import org.jboss.arquillian.graphene.page.RequestState; import org.jboss.arquillian.graphene.page.RequestType; import org.jboss.arquillian.graphene.page.document.Document; @@ -40,22 +38,30 @@ import com.google.common.base.Function; import com.google.common.base.Predicate; +import org.jboss.arquillian.graphene.GrapheneContext; /** * @author <a href="mailto:[email protected]">Jan Papousek</a> */ public class RequestGuardFactory { - private static RequestGuard guard = JSInterfaceFactory.create(RequestGuard.class); - private static Document document = JSInterfaceFactory.create(Document.class); - - private static DocumentReady documentReady = new DocumentReady(); - private static RequestIsDone requestIsDone = new RequestIsDone(); - private static RequestChange requestChange = new RequestChange(); - - private static FluentWait<WebDriver, Void> waitGuard = waitAjax() - .withTimeout(GrapheneConfigurationContext.getProxy().getWaitGuardInterval(), TimeUnit.SECONDS) - .pollingEvery(Math.min(GrapheneConfigurationContext.getProxy().getWaitGuardInterval() * 100, 200), TimeUnit.MILLISECONDS); + private final RequestGuard guard; + private final Document document; + private final FluentWait<WebDriver, Void> waitGuard; + private final GrapheneContext context; + private final DocumentReady documentReady = new DocumentReady(); + private final RequestIsDone requestIsDone = new RequestIsDone(); + private final RequestChange requestChange = new RequestChange(); + + + public RequestGuardFactory(RequestGuard guard, Document document, GrapheneContext context) { + this.guard = guard; + this.document = document; + this.context = context; + this.waitGuard = waitAjax() + .withTimeout(context.getConfiguration().getWaitGuardInterval(), TimeUnit.SECONDS) + .pollingEvery(Math.min(context.getConfiguration().getWaitGuardInterval() * 100, 200), TimeUnit.MILLISECONDS); + } /** * Returns the guarded object checking whether the request of the given type is done during each method invocation. If the @@ -67,7 +73,7 @@ public class RequestGuardFactory { * @param strict indicates that the expected request type can be interleaved by another type * @return the guarded object */ - public static <T> T guard(T target, final RequestType requestExpected, final boolean strict) { + public <T> T guard(T target, final RequestType requestExpected, final boolean strict) { if (requestExpected == null) { throw new IllegalArgumentException("The paremeter [requestExpected] is null."); } @@ -78,7 +84,7 @@ public static <T> T guard(T target, final RequestType requestExpected, final boo if (GrapheneProxy.isProxyInstance(target)) { proxy = (GrapheneProxyInstance) ((GrapheneProxyInstance) target).copy(); } else { - proxy = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(target); + proxy = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(context, target); } proxy.registerInterceptor(new Interceptor() { @Override @@ -140,27 +146,30 @@ private void waitForRequestFinished() { return (T) proxy; } - private static class DocumentReady implements Predicate<WebDriver> { + private class DocumentReady implements Predicate<WebDriver> { + @Override public boolean apply(WebDriver driver) { return "complete".equals(document.getReadyState()); } } - private static class RequestIsDone implements Predicate<WebDriver> { + private class RequestIsDone implements Predicate<WebDriver> { + @Override public boolean apply(WebDriver driver) { RequestState state = guard.getRequestState(); return RequestState.DONE.equals(state); } } - private static class RequestChange implements Function<WebDriver, RequestType> { + private class RequestChange implements Function<WebDriver, RequestType> { + @Override public RequestType apply(WebDriver driver) { RequestType type = guard.getRequestType(); return (RequestType.NONE.equals(type)) ? null : type; } } - private static class RequestTypeDone implements Function<WebDriver, RequestType> { + private class RequestTypeDone implements Function<WebDriver, RequestType> { private RequestType requestExpected; @@ -168,6 +177,7 @@ public RequestTypeDone(RequestType requestExpected) { this.requestExpected = requestExpected; } + @Override public RequestType apply(WebDriver driver) { RequestType type = guard.getRequestType(); if (!requestExpected.equals(type)) { @@ -176,4 +186,4 @@ public RequestType apply(WebDriver driver) { return type; } } -} +} \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java index 9d24a0649..523c12bfc 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java @@ -1,11 +1,33 @@ +/** + * JBoss, Home of Professional Open Source + * Copyright 2012, Red Hat, Inc. and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ package org.jboss.arquillian.graphene.integration; import java.lang.annotation.Annotation; - +import org.jboss.arquillian.core.api.Instance; +import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.drone.spi.Enhancer; -import org.jboss.arquillian.drone.webdriver.spi.DroneAugmented; -import org.jboss.arquillian.graphene.context.GrapheneContext; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.jboss.arquillian.graphene.proxy.GrapheneProxyUtil; import org.openqa.selenium.WebDriver; @@ -17,6 +39,9 @@ */ public class GrapheneEnhancer implements Enhancer<WebDriver> { + @Inject + private Instance<GrapheneConfiguration> configuration; + @Override public int getPrecedence() { return -100; @@ -31,34 +56,23 @@ public boolean canEnhance(Class<?> type, Class<? extends Annotation> qualifier) * Wraps the {@link WebDriver} instance provided by {@link Drone} in a proxy and sets the driver into context */ @Override - @SuppressWarnings("unchecked") public WebDriver enhance(WebDriver driver, Class<? extends Annotation> qualifier) { - GrapheneContext.set(driver); - - Class<? extends WebDriver> baseDriverClass = driver.getClass(); - if (driver instanceof DroneAugmented) { - baseDriverClass = (Class<? extends WebDriver>)((DroneAugmented) driver).getWrapped().getClass(); - } - + GrapheneContext grapheneContext = GrapheneContext.setContextFor(configuration.get(), driver, qualifier); Class<?>[] interfaces = GrapheneProxyUtil.getInterfaces(driver.getClass()); - - WebDriver proxy = GrapheneContext.getProxyForDriver(baseDriverClass, interfaces); - - return proxy; + return grapheneContext.getWebDriver(interfaces); } /** * Unwraps the proxy */ @Override - public WebDriver deenhance(WebDriver instance, Class<? extends Annotation> qualifier) { - if (instance instanceof GrapheneProxyInstance) { - instance = ((GrapheneProxyInstance) instance).unwrap(); + public WebDriver deenhance(WebDriver enhancedDriver, Class<? extends Annotation> qualifier) { + if (enhancedDriver instanceof GrapheneProxyInstance) { + WebDriver driver = ((GrapheneProxyInstance) enhancedDriver).unwrap(); + GrapheneContext.removeContextFor(qualifier); + return driver; } - - GrapheneContext.reset(); - - return instance; + return enhancedDriver; } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java index 9ca8ecfef..cc1799c9d 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java @@ -10,6 +10,7 @@ import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.proxy.Interceptor; import org.jboss.arquillian.graphene.proxy.InvocationContext; @@ -91,6 +92,11 @@ public Object getTarget() { return originalContext.getTarget(); } + @Override + public Object getProxy() { + return originalContext.getProxy(); + } + @Override public Method getMethod() { return originalContext.getMethod(); @@ -100,6 +106,11 @@ public Method getMethod() { public Object[] getArguments() { return originalContext.getArguments(); } + + @Override + public GrapheneContext getGrapheneContext() { + return originalContext.getGrapheneContext(); + } }); } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java index a06505571..bdfbda10d 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java @@ -21,22 +21,19 @@ */ package org.jboss.arquillian.graphene.javascript; +import com.google.common.io.Resources; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.Arrays; +import java.util.logging.Level; import java.util.logging.Logger; - -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext; +import org.jboss.arquillian.drone.api.annotation.Default; import org.jboss.arquillian.graphene.page.extension.JavaScriptPageExtension; +import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry; +import org.jboss.arquillian.graphene.GrapheneContext; import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.WebDriver; - -import com.google.common.io.Resources; -import java.util.logging.Level; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; /** * This resolver uses page extension mechanism to install needed JavaScript @@ -61,29 +58,21 @@ public class DefaultExecutionResolver implements ExecutionResolver { } } - private JavascriptExecutor browser = GrapheneContext.getProxyForInterfaces(JavascriptExecutor.class); - @Override - public Object execute(WebDriver driver, JSCall call) { - if (driver == null) { - throw new IllegalArgumentException("Driver can't be null."); - } - if (!(driver instanceof JavascriptExecutor)) { - throw new IllegalArgumentException("The executor can be used only for drivers implementing " + JavascriptExecutor.class.getName()); - } + public Object execute(GrapheneContext context, JSCall call) { // check name JSTarget target = call.getTarget(); if (target.getName() == null) { throw new IllegalStateException("Can't use " + this.getClass() + " for " + target.getInterface() + ", because the @JavaScript annotation doesn't define non empty value()"); } // register page extension - registerExtension(target); + registerExtension(context.getPageExtensionRegistry(), target); // try to execute javascript, if fails install the extension - final long LIMIT = GrapheneConfigurationContext.getProxy().getJavascriptInstallationLimit(); + final long LIMIT = context.getConfiguration().getJavascriptInstallationLimit(); for (long i=1; i<=5; i++) { try { // execute javascript - Object returnValue = executeScriptForCall(call); + Object returnValue = executeScriptForCall((JavascriptExecutor) context.getWebDriver(JavascriptExecutor.class), call); Object castedResult = castResult(call, returnValue); return castedResult; } catch (RuntimeException e) { @@ -93,9 +82,8 @@ public Object execute(WebDriver driver, JSCall call) { // try to install the extension } else { try { - GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(target.getName()).install(); - } catch (RuntimeException ex) { - LOGGER.log(Level.WARNING, "Installation of page extension for " + call.getTarget().getInterface().getName() + " javascript interface failed.", ex); + context.getPageExtensionInstallatorProvider().installator(target.getName()).install(); + } catch (RuntimeException ignored) { } } } @@ -140,10 +128,10 @@ protected Object castStringToEnum(Class<?> returnType, Object returnValue) { } } - protected Object executeScriptForCall(JSCall call) { + protected Object executeScriptForCall(JavascriptExecutor executor, JSCall call) { String script = resolveScriptToExecute(call); Object[] arguments = castArguments(call.getArguments()); - Object returnValue = JavaScriptUtils.execute(browser, script, arguments); + Object returnValue = JavaScriptUtils.execute(executor, script, arguments); if (returnValue instanceof String && ((String) returnValue).startsWith("GRAPHENE ERROR: ")) { throw new IllegalStateException("exception thrown when executing method '" + call.getMethod().getName() + "': " + ((String) returnValue).substring(16)); } @@ -156,17 +144,17 @@ protected String resolveScriptToExecute(JSCall call) { return functionDefinitionWithCall; } - protected <T> void registerExtension(JSTarget target) { + protected <T> void registerExtension(PageExtensionRegistry registry, JSTarget target) { if (target.getName() == null || target.getName().isEmpty()) { throw new IllegalArgumentException("The extension " + target.getInterface() + "has no mapping."); } - if (GraphenePageExtensionsContext.getRegistryProxy().getExtension(target.getName()) != null) { + if (registry.getExtension(target.getName()) != null) { return; } JavaScriptPageExtension extension = new JavaScriptPageExtension(target.getInterface()); - GraphenePageExtensionsContext.getRegistryProxy().register(extension); + registry.register(extension); for (JSTarget dependency: target.getJSInterfaceDependencies()) { - registerExtension(dependency); + registerExtension(registry, dependency); } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java index dddd0ed95..4f1aeb5de 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java @@ -1,9 +1,9 @@ package org.jboss.arquillian.graphene.javascript; -import org.openqa.selenium.WebDriver; +import org.jboss.arquillian.graphene.GrapheneContext; public interface ExecutionResolver { - Object execute(WebDriver driver, JSCall call); + Object execute(GrapheneContext context, JSCall call); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java index 1e7906aea..c8369cd49 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java @@ -1,31 +1,21 @@ package org.jboss.arquillian.graphene.javascript; import java.lang.reflect.Modifier; - -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.WebDriver; +import org.jboss.arquillian.graphene.GrapheneContext; public class JSInterfaceFactory<T> { - private JSInterfaceHandler handler; - - private JSInterfaceFactory(WebDriver driver, Class<T> jsInterface) { + private final JSInterfaceHandler handler; + public JSInterfaceFactory(GrapheneContext context, Class<T> jsInterface) { if (!jsInterface.isInterface() && !Modifier.isAbstract(jsInterface.getModifiers())) { throw new IllegalArgumentException("interface or abstract class must be provided :" + jsInterface); } - - this.handler = new JSInterfaceHandler(driver, new JSTarget(jsInterface)); - - } - - public static <T> T create(Class<T> jsInterface) { - return create((WebDriver) GrapheneContext.getProxyForInterfaces(JavascriptExecutor.class), jsInterface); + this.handler = new JSInterfaceHandler(new JSTarget(jsInterface), context); } - public static <T> T create(WebDriver driver, Class<T> jsInterface) { - return new JSInterfaceFactory<T>(driver, jsInterface).instantiate(); + public static <T> T create(GrapheneContext context, Class<T> jsInterface) { + return new JSInterfaceFactory<T>(context, jsInterface).instantiate(); } @SuppressWarnings("unchecked") diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java index ecec25efd..f8a2bea4e 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java @@ -2,19 +2,18 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import org.openqa.selenium.WebDriver; - import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; +import org.jboss.arquillian.graphene.GrapheneContext; public class JSInterfaceHandler implements MethodInterceptor { private final JSTarget target; - private final WebDriver driver; + private final GrapheneContext context; - public JSInterfaceHandler(WebDriver driver, JSTarget jsTarget) { - this.target = jsTarget; - this.driver = driver; + public JSInterfaceHandler(JSTarget target, GrapheneContext context) { + this.target = target; + this.context = context; } public JSTarget getTarget() { @@ -28,8 +27,11 @@ public Object intercept(Object obj, Method method, Object[] args, MethodProxy me return methodProxy.invokeSuper(obj, args); } } + if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) { + return null; + } args = (args != null) ? args : new Object[]{}; JSCall call = new JSCall(new JSMethod(target, method), args); - return target.getResolver().execute(driver, call); + return target.getResolver().execute(context, call); } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/GraphenePageExtensionRegistrar.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/GraphenePageExtensionRegistrar.java deleted file mode 100644 index 79dd3d7db..000000000 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/GraphenePageExtensionRegistrar.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.arquillian.graphene.page.extension; - -import java.util.Collection; - -import org.jboss.arquillian.core.api.Event; -import org.jboss.arquillian.core.api.Instance; -import org.jboss.arquillian.core.api.InstanceProducer; -import org.jboss.arquillian.core.api.annotation.Inject; -import org.jboss.arquillian.core.api.annotation.Observes; -import org.jboss.arquillian.core.spi.ServiceLoader; -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext; -import org.jboss.arquillian.graphene.spi.page.PageExtensionProvider; -import org.jboss.arquillian.graphene.spi.page.PageExtensionsCleaned; -import org.jboss.arquillian.graphene.spi.page.PageExtensionsReady; -import org.jboss.arquillian.test.spi.TestClass; -import org.jboss.arquillian.test.spi.annotation.ClassScoped; -import org.jboss.arquillian.test.spi.event.suite.AfterClass; -import org.jboss.arquillian.test.spi.event.suite.BeforeClass; -import org.openqa.selenium.JavascriptExecutor; - -/** - * @author <a href="mailto:[email protected]">Jan Papousek</a> - */ -public class GraphenePageExtensionRegistrar { - - @Inject - @ClassScoped - private InstanceProducer<PageExtensionRegistry> pageExtensionRegistry; - @Inject - @ClassScoped - private InstanceProducer<PageExtensionInstallatorProvider> pageExtensionInstallatorProvider; - @Inject - private Instance<ServiceLoader> serviceLoader; - @Inject - private Event<PageExtensionsReady> pageExtensionsReady; - @Inject - private Event<PageExtensionsCleaned> pageExtensionsCleaned; - - public void registerPageExtensionRegistry(@Observes BeforeClass event, TestClass testClass) { - pageExtensionRegistry.set(new PageExtensionRegistryImpl()); - loadPageExtensions(testClass); - GraphenePageExtensionsContext.setRegistry(pageExtensionRegistry.get()); - pageExtensionInstallatorProvider.set(new RemotePageExtensionInstallatorProvider(pageExtensionRegistry.get(), GrapheneContext.<JavascriptExecutor>getProxyForInterfaces(JavascriptExecutor.class))); - GraphenePageExtensionsContext.setInstallatorProvider(pageExtensionInstallatorProvider.get()); - pageExtensionsReady.fire(new PageExtensionsReady()); - } - - public void unregisterPageExtensionRegistry(@Observes AfterClass event) { - pageExtensionRegistry.get().flush(); - GraphenePageExtensionsContext.reset(); - pageExtensionsCleaned.fire(new PageExtensionsCleaned()); - } - - protected void loadPageExtensions(TestClass testClass) { - Collection<PageExtensionProvider> providers = serviceLoader.get().all(PageExtensionProvider.class); - for (PageExtensionProvider provider: providers) { - pageExtensionRegistry.get().register(provider.getPageExtensions(testClass)); - } - } - -} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java index 728dd4f76..a98fa6710 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java @@ -24,6 +24,7 @@ import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; +import org.jboss.arquillian.graphene.GrapheneContext; import net.sf.cglib.proxy.Enhancer; @@ -58,16 +59,16 @@ public static boolean isProxyInstance(Object target) { * @return the proxy wrapping the target */ @SuppressWarnings("unchecked") - public static <T> T getProxyForTarget(T target) { + public static <T> T getProxyForTarget(GrapheneContext context, T target) { if (Modifier.isFinal(target.getClass().getModifiers())) { if (target.getClass().getInterfaces().length > 0) { - return GrapheneProxy.getProxyForTargetWithInterfaces(target, target.getClass().getInterfaces()); + return GrapheneProxy.getProxyForTargetWithInterfaces(context, target, target.getClass().getInterfaces()); } else { throw new IllegalStateException("Can't create a proxy for " + target.getClass() + ", it's final and id doesn't implement any interface."); } } - GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(target); + GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(context, target); return (T) createProxy(handler, target.getClass()); } @@ -86,8 +87,8 @@ public static <T> T getProxyForTarget(T target) { * @return the proxy wrapping the target */ @SuppressWarnings("unchecked") - public static <T> T getProxyForTargetWithInterfaces(T target, Class<?>... interfaces) { - GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(target); + public static <T> T getProxyForTargetWithInterfaces(GrapheneContext context, T target, Class<?>... interfaces) { + GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(context, target); return (T) createProxy(handler, null, interfaces); } @@ -114,18 +115,16 @@ public static <T> T getProxyForTargetWithInterfaces(T target, Class<?>... interf * @return the proxy wrapping the future target */ @Deprecated - public static <T> T getProxyForFutureTarget(FutureTarget futureTarget, Class<?> baseType, Class<?>... additionalInterfaces) { + public static <T> T getProxyForFutureTarget(GrapheneContext context, FutureTarget futureTarget, Class<?> baseType, Class<?>... additionalInterfaces) { if (baseType != null && !baseType.isInterface() && Modifier.isFinal(baseType.getModifiers())) { if (additionalInterfaces.length > 0) { - return GrapheneProxy.getProxyForFutureTarget(futureTarget, additionalInterfaces[0], additionalInterfaces); + return GrapheneProxy.getProxyForFutureTarget(context, futureTarget, additionalInterfaces[0], additionalInterfaces); } else { throw new IllegalStateException("Can't create a proxy for " + baseType + ", it's final and no additional interface has been given."); } } - - GrapheneProxyHandler handler = GrapheneProxyHandler.forFuture(futureTarget); - + GrapheneProxyHandler handler = GrapheneProxyHandler.forFuture(context, futureTarget); return getProxyForHandler(handler, baseType, additionalInterfaces); } @@ -176,4 +175,19 @@ public interface FutureTarget { Object getTarget(); } + + public static class ConstantFutureTarget implements FutureTarget { + + private final Object target; + + public ConstantFutureTarget(Object target) { + this.target = target; + } + + @Override + public Object getTarget() { + return target; + } + + } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java index be0a2250a..3bdd4a959 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java @@ -26,9 +26,14 @@ import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.logging.Logger; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; +import org.jboss.arquillian.graphene.BrowserActions; +import org.jboss.arquillian.graphene.GrapheneContext; import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget; @@ -48,9 +53,11 @@ public class GrapheneProxyHandler implements MethodInterceptor, InvocationHandle private Object target; private FutureTarget future; + private final GrapheneContext context; private Map<Class<?>, Interceptor> interceptors = new HashMap<Class<?>, Interceptor>(); - private GrapheneProxyHandler() { + private GrapheneProxyHandler(GrapheneContext context) { + this.context = context; } /** @@ -59,8 +66,8 @@ private GrapheneProxyHandler() { * @param target the target of invocation * @return invocation handler which wraps the given target instance */ - public static GrapheneProxyHandler forTarget(Object target) { - GrapheneProxyHandler handler = new GrapheneProxyHandler(); + public static GrapheneProxyHandler forTarget(GrapheneContext context, Object target) { + GrapheneProxyHandler handler = new GrapheneProxyHandler(context); handler.target = target; return handler; } @@ -71,8 +78,8 @@ public static GrapheneProxyHandler forTarget(Object target) { * @param future the future target * @return invocation handler which wraps the target for future computation */ - public static GrapheneProxyHandler forFuture(FutureTarget future) { - GrapheneProxyHandler handler = new GrapheneProxyHandler(); + public static GrapheneProxyHandler forFuture(GrapheneContext context, FutureTarget future) { + GrapheneProxyHandler handler = new GrapheneProxyHandler(context); handler.future = future; return handler; } @@ -93,6 +100,17 @@ public static GrapheneProxyHandler forFuture(FutureTarget future) { */ @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + // handle finalizer + if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) { + if (!method.isAccessible()) { + method.setAccessible(true); + } + Object target = getTarget(); + if (target instanceof GrapheneProxyInstance) { + return ((GrapheneProxyInstance) target).unwrap(); + } + method.invoke(target); + } // handle the GrapheneProxyInstance's method unwrap if (method.equals(GrapheneProxyInstance.class.getMethod("unwrap"))) { Object target = getTarget(); @@ -122,10 +140,10 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg if (method.equals(GrapheneProxyInstance.class.getMethod("copy"))) { GrapheneProxyInstance clone; if (this.future != null) { - clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForFutureTarget(this.future, this.future.getTarget() + clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForFutureTarget(context, this.future, this.future.getTarget() .getClass(), this.future.getTarget().getClass().getInterfaces()); } else { - clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(this.target); + clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(context, this.target); } for (Interceptor interceptor : interceptors.values()) { clone.registerInterceptor(interceptor); @@ -136,6 +154,10 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg if (method.equals(GrapheneProxyInstance.class.getMethod("getHandler"))) { return this; } + // handle GrapheneProxyInstance's method getContext + if (method.equals(GrapheneProxyInstance.class.getMethod("getContext"))) { + return context; + } InvocationContext invocationContext = new InvocationContext() { @@ -147,7 +169,7 @@ public Object invoke() throws Throwable { } if (isProxyable(method, args) && !(result instanceof GrapheneProxyInstance)) { Class<?>[] interfaces = GrapheneProxyUtil.getInterfaces(result.getClass()); - Object newProxy = GrapheneProxy.getProxyForTargetWithInterfaces(result, interfaces); + Object newProxy = GrapheneProxy.getProxyForTargetWithInterfaces(context, result, interfaces); // List<Interceptor> inheritingInterceptors = ((GrapheneProxyInstance)proxy).getInheritingInterceptors(); @@ -171,11 +193,39 @@ public Object getTarget() { return GrapheneProxyHandler.this.getTarget(); } + @Override + public Object getProxy() { + return proxy; + } + + @Override + public GrapheneContext getGrapheneContext() { + return context; + } + }; for (Interceptor interceptor : interceptors.values()) { invocationContext = new InvocationContextImpl(interceptor, invocationContext); } - return invocationContext.invoke(); + final InvocationContext finalInvocationContext = invocationContext; + if (context != null) { + return context.getBrowserActions().performAction(new Callable<Object>() { + @Override + public Object call() throws Exception { + try { + return finalInvocationContext.invoke(); + } catch (Throwable e) { + if (e instanceof Exception) { + throw (Exception) e; + } else { + throw new IllegalStateException("Can't invoke method " + method.getName() + ".", e); + } + } + } + }); + } else { + return finalInvocationContext.invoke(); + } } /** @@ -183,7 +233,7 @@ public Object getTarget() { */ @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { - return invoke(proxy, method, args); + return invoke(obj, method, args); } /** @@ -220,7 +270,7 @@ Object invokeReal(Object target, Method method, Object[] args) throws Throwable } catch (Exception e) { throw new RuntimeException("unexpected invocation exception during invocation of " + method.getDeclaringClass().getName() + "#" + method.getName() + "(), on target '" - + target.getClass().getName() + "': " + e.getMessage(), e); + + target + "': " + e.getMessage(), e); } return result; } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java index cfd6aefa6..470381d6c 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java @@ -21,6 +21,8 @@ */ package org.jboss.arquillian.graphene.proxy; +import org.jboss.arquillian.graphene.GrapheneContext; + /** * <p> @@ -40,4 +42,6 @@ public interface GrapheneProxyInstance { <T> T copy(); <T> T unwrap(); + + GrapheneContext getContext(); } \ No newline at end of file diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java index ece13c16f..919593844 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java @@ -21,6 +21,7 @@ */ package org.jboss.arquillian.graphene.proxy; +import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; @@ -100,4 +101,25 @@ public static Class<?>[] concatClasses(Class<?>[] classes, Class<?> clazz) { out[length] = clazz; return out; } + + public static boolean isProxy(Class<?> clazz) { + if (clazz.equals(Object.class)) { + return false; + } + if (net.sf.cglib.proxy.Proxy.isProxyClass(clazz) || Proxy.isProxyClass(clazz)) { + return true; + } else { + for (Class<?> interfaze: clazz.getInterfaces()) { + if (interfaze.getName().endsWith(".cglib.proxy.Factory")) { + return true; + } + } + return false; + } + } + + public static boolean isProxy(Object target) { + return isProxy(target.getClass()); + + } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java index 47bc28e26..15f97d57e 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java @@ -22,6 +22,7 @@ package org.jboss.arquillian.graphene.proxy; import java.lang.reflect.Method; +import org.jboss.arquillian.graphene.GrapheneContext; /** * @author <a href="mailto:[email protected]">Jan Papousek</a> @@ -48,6 +49,11 @@ public interface InvocationContext extends GrapheneProxy.FutureTarget { /** * @return the target object of the method invocation */ + @Override Object getTarget(); + Object getProxy(); + + GrapheneContext getGrapheneContext(); + } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java index 78534e1fb..f2be44ba2 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java @@ -22,6 +22,7 @@ package org.jboss.arquillian.graphene.proxy; import java.lang.reflect.Method; +import org.jboss.arquillian.graphene.GrapheneContext; /** * @author <a href="mailto:[email protected]">Jan Papousek</a> @@ -31,24 +32,34 @@ public class InvocationContextImpl implements InvocationContext { private final InvocationContext following; private final Interceptor interceptor; private final Object target; + private final Object proxy; private final Method method; private final Object[] arguments; + private final GrapheneContext context; - public InvocationContextImpl(Object target, Method method, Object[] arguments) { + public InvocationContextImpl(GrapheneContext context, Object target, Object proxy, Method method, Object[] arguments) { if (target == null) { throw new IllegalArgumentException("The parameter [target] is null."); } + if (proxy == null) { + throw new IllegalArgumentException("The parameter [proxy] is null."); + } if (method == null) { throw new IllegalArgumentException("The parameter [method] is null."); } if (arguments == null) { throw new IllegalArgumentException("The parameter [arguments] is null."); } + if (context == null) { + throw new IllegalArgumentException("The parameter [context] is null."); + } this.following = null; this.interceptor = null; this.arguments = arguments; this.method = method; this.target = target; + this.context = context; + this.proxy = proxy; } public InvocationContextImpl(Interceptor interceptor, InvocationContext following) { @@ -63,6 +74,8 @@ public InvocationContextImpl(Interceptor interceptor, InvocationContext followin this.arguments = null; this.method = null; this.target = null; + this.context = null; + this.proxy = null; } @Override @@ -89,4 +102,14 @@ public Object getTarget() { return target == null ? following.getTarget() : target; } + @Override + public Object getProxy() { + return proxy == null ? following.getProxy() : proxy; + } + + @Override + public GrapheneContext getGrapheneContext() { + return context == null ? following.getGrapheneContext() : context; + } + } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriver.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriver.java similarity index 97% rename from graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriver.java rename to graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriver.java index e766996eb..e68242532 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriver.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriver.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.context; +package org.jboss.arquillian.graphene; import org.openqa.selenium.HasCapabilities; import org.openqa.selenium.HasInputDevices; diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStub.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStub.java similarity index 98% rename from graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStub.java rename to graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStub.java index 6bf76ae9c..a77b3f59b 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStub.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStub.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.context; +package org.jboss.arquillian.graphene; import java.util.List; import java.util.Set; diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStubExtension.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStubExtension.java similarity index 95% rename from graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStubExtension.java rename to graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStubExtension.java index 44e1eae3f..591967efc 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStubExtension.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStubExtension.java @@ -19,7 +19,7 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.jboss.arquillian.graphene.context; +package org.jboss.arquillian.graphene; /** * @author Lukas Fryc diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java index 1065ab1f0..19aecbf08 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java @@ -32,7 +32,6 @@ import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor; import org.jboss.arquillian.config.descriptor.api.ExtensionDef; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; import org.jboss.arquillian.graphene.spi.configuration.GrapheneConfigured; import org.jboss.arquillian.graphene.spi.configuration.GrapheneUnconfigured; import org.jboss.arquillian.test.spi.annotation.SuiteScoped; @@ -73,11 +72,12 @@ public void testConfigurationViaDescriptor() { getManager().bind(SuiteScoped.class, ArquillianDescriptor.class, descriptor); fire(new BeforeClass(Object.class)); assertEventFired(GrapheneConfigured.class); - assertNotNull("Configuration instance has to be available.", GrapheneConfigurationContext.getProxy()); - GrapheneConfigurationContext.getProxy().validate(); - assertEquals("'waitGuiInterval' should be 5", 5, GrapheneConfigurationContext.getProxy().getWaitGuiInterval()); - assertEquals("'waitAjaxInterval' should be 25", 25, GrapheneConfigurationContext.getProxy().getWaitAjaxInterval()); - assertEquals("'waitModelInterval' should be 125", 125, GrapheneConfigurationContext.getProxy().getWaitModelInterval()); + GrapheneConfiguration configuration = getManager().resolve(GrapheneConfiguration.class); + assertNotNull("Configuration instance has to be available.", configuration); + configuration.validate(); + assertEquals("'waitGuiInterval' should be 5", 5, configuration.getWaitGuiInterval()); + assertEquals("'waitAjaxInterval' should be 25", 25, configuration.getWaitAjaxInterval()); + assertEquals("'waitModelInterval' should be 125", 125, configuration.getWaitModelInterval()); fire(new AfterClass(Object.class)); assertEventFired(GrapheneUnconfigured.class); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextHolding.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextHolding.java deleted file mode 100644 index c948c3f3e..000000000 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextHolding.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.arquillian.graphene.context; - -import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openqa.selenium.TakesScreenshot; -import org.openqa.selenium.WebDriver; - -/** - * @author Lukas Fryc - */ -public class TestGrapheneContextHolding { - - @Mock - WebDriver driver; - - @Mock(extraInterfaces = GrapheneProxyInstance.class) - WebDriver driverProxy; - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void when_instance_is_provided_to_context_then_context_holds_it() { - // having - // when - GrapheneContext.set(driver); - - // then - assertSame(driver, GrapheneContext.get()); - } - - @Test - public void when_instance_is_provided_to_context_then_context_is_initialized() { - // having - // when - GrapheneContext.set(driver); - - // then - assertTrue(GrapheneContext.isInitialized()); - } - - @Test - public void when_context_is_reset_then_context_is_not_initialized() { - // having - GrapheneContext.set(driver); - - // when - GrapheneContext.reset(); - - // then - assertFalse(GrapheneContext.isInitialized()); - } - - @Test(expected = NullPointerException.class) - public void when_calling_get_on_not_initialized_context_then_context_throws_exception() { - GrapheneContext.reset(); - GrapheneContext.get(); - } - - @Test(expected = IllegalArgumentException.class) - public void when_set_null_instance_to_context_then_context_throws_exception() { - GrapheneContext.set(null); - } - - @Test - public void context_should_determine_that_holds_instance_of_some_interface() { - GrapheneContext.set(new TestingDriverStub()); - assertTrue(GrapheneContext.holdsInstanceOf(TakesScreenshot.class)); - } - - @Test - public void context_should_fail_when_checked_for_being_instance_of_non_implemented_class() { - GrapheneContext.set(new TestingDriverStub()); - assertFalse(GrapheneContext.holdsInstanceOf(Collection.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void when_set_proxy_instance_to_context_then_context_throws_exception() { - GrapheneContext.set(driverProxy); - } -} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextProxying.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextProxying.java deleted file mode 100644 index 9e23028b1..000000000 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextProxying.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.arquillian.graphene.context; - -import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; -import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.only; -import static org.mockito.Mockito.atLeastOnce; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriver.Navigation; -import org.openqa.selenium.WebElement; - -/** - * @author Lukas Fryc - */ -@RunWith(MockitoJUnitRunner.class) -public class TestGrapheneContextProxying { - - private static final String SAMPLE_STRING = "sample"; - - @Mock - WebDriver driver; - - @Test - public void context_provides_proxy_which_delegates_to_current_context() { - // having - WebDriver driver = new DriverReturningSampleString(); - - // when - GrapheneContext.set(driver); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - - // then - WebDriver proxy = GrapheneContext.getProxy(); - assertEquals(SAMPLE_STRING, proxy.toString()); - } - - @Test - public void when_proxy_returns_webdriver_api_then_another_proxy_is_returned_wrapping_the_result_of_invocation() { - // having - Navigation navigation = mock(Navigation.class); - - // when - GrapheneContext.set(driver); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - when(driver.navigate()).thenReturn(navigation); - - // then - WebDriver driverProxy = GrapheneContext.getProxy(); - Navigation navigationProxy = driverProxy.navigate(); - assertTrue(navigationProxy instanceof GrapheneProxyInstance); - - // verify - verify(driver, only()).navigate(); - } - - @Test - public void when_proxy_returns_result_of_invocation_with_arguments_then_returned_object_is_proxied() { - // having - WebElement webElement = mock(WebElement.class); - By byId = By.id("id"); - - // when - GrapheneContext.set(driver); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - when(driver.findElement(byId)).thenReturn(webElement); - - // then - WebDriver driverProxy = GrapheneContext.getProxy(); - WebElement webElementProxy = driverProxy.findElement(byId); - webElementProxy.clear(); - assertTrue(webElementProxy instanceof GrapheneProxyInstance); - - // verify - verify(driver, atLeastOnce()).findElement(byId); - } - - @Test - public void when_proxy_returns_result_of_invocation_with_arguments_then_returned_object_can_be_invoked() { - // having - WebElement webElement = mock(WebElement.class); - By byId = By.id("id"); - - // when - GrapheneContext.set(driver); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - when(driver.findElement(byId)).thenReturn(webElement); - - // then - WebDriver driverProxy = GrapheneContext.getProxy(); - WebElement webElementProxy = driverProxy.findElement(byId); - webElementProxy.clear(); - - // verify - verify(webElement, only()).clear(); - } - - @Test - - public void test_that_context_can_be_unwrapped() { - // having - GrapheneContext.set(driver); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - WebDriver driverProxy = GrapheneContext.getProxy(); - - // when - WebDriver unwrapped = ((GrapheneProxyInstance) driverProxy).unwrap(); - - // then - assertSame(driver, unwrapped); - } - - private static class DriverReturningSampleString extends TestingDriverStub { - @Override - public String toString() { - return SAMPLE_STRING; - } - } -} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextTheadLocality.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextTheadLocality.java deleted file mode 100644 index 7e4853163..000000000 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextTheadLocality.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * JBoss, Home of Professional Open Source - * Copyright 2012, Red Hat, Inc. and individual contributors - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.arquillian.graphene.context; - -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - -import java.util.concurrent.CountDownLatch; - -import org.junit.Test; -import org.openqa.selenium.WebDriver; - -/** - * @author Lukas Fryc - */ -public class TestGrapheneContextTheadLocality { - - @Test - public void context_holds_one_instance_per_thread() { - final CountDownLatch secondInstanceSet = new CountDownLatch(1); - final CountDownLatch firstInstanceVerified = new CountDownLatch(1); - final WebDriver driver1 = mock(WebDriver.class); - final WebDriver driver2 = mock(WebDriver.class); - - new Thread(new Runnable() { - public void run() { - GrapheneContext.set(driver1); - await(secondInstanceSet); - assertSame(driver1, GrapheneContext.get()); - firstInstanceVerified.countDown(); - } - }).start(); - - new Thread(new Runnable() { - public void run() { - GrapheneContext.set(driver2); - secondInstanceSet.countDown(); - assertSame(driver2, GrapheneContext.get()); - } - }).start(); - await(firstInstanceVerified); - } - - private void await(CountDownLatch condition) { - try { - condition.await(); - } catch (InterruptedException e) { - fail("thread has been interrupted"); - } - } -} diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java index 5725af5b7..7a3b57876 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java @@ -27,9 +27,12 @@ import java.util.Arrays; import org.jboss.arquillian.core.api.Instance; +import org.jboss.arquillian.core.impl.InstanceImpl; import org.jboss.arquillian.core.spi.ServiceLoader; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.TestingDriver; import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher; import org.jboss.arquillian.test.spi.TestEnricher; import org.junit.Before; @@ -49,6 +52,9 @@ public abstract class AbstractGrapheneEnricherTest { @Mock private Instance<ServiceLoader> serviceLoaderInstance; + @Mock + protected TestingDriver browser; + @Mock private ServiceLoader serviceLoader; @@ -63,9 +69,16 @@ public abstract class AbstractGrapheneEnricherTest { @Before public void prepareServiceLoader() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { grapheneEnricher = new GrapheneEnricher(); - webElementEnricher = new WebElementEnricher(); + Instance<GrapheneConfiguration> configuration = new Instance() { + @Override + public Object get() { + return new GrapheneConfiguration(); + } + + }; + webElementEnricher = new WebElementEnricher(configuration); pageObjectEnricher = new PageObjectEnricher(); - pageFragmentEnricher = new PageFragmentEnricher(); + pageFragmentEnricher = new PageFragmentEnricher(configuration); when(serviceLoaderInstance.get()).thenReturn(serviceLoader); when(serviceLoader.all(TestEnricher.class)).thenReturn(Arrays.asList(grapheneEnricher)); when(serviceLoader.all(SearchContextTestEnricher.class)).thenReturn(Arrays.asList(webElementEnricher, pageObjectEnricher, pageFragmentEnricher)); @@ -82,7 +95,7 @@ public void prepareServiceLoader() throws NoSuchFieldException, IllegalArgumentE serviceLoaderField.set(o, serviceLoaderInstance); } - GrapheneConfigurationContext.set(new GrapheneConfiguration()); + GrapheneContext.setContextFor(new GrapheneConfiguration(), browser, Default.class); } protected final TestEnricher getGrapheneEnricher() { diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java index 6e3faa53d..31f8a1da1 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java @@ -1,17 +1,22 @@ package org.jboss.arquillian.graphene.enricher; +import java.util.Arrays; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import org.jboss.arquillian.graphene.context.GrapheneContext; import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.ActionsProvider; import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.KeyboardProvider; import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.MouseProvider; import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.WebDriverProvider; +import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -21,9 +26,11 @@ import org.openqa.selenium.HasInputDevices; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keyboard; +import org.openqa.selenium.Keys; import org.openqa.selenium.Mouse; import org.openqa.selenium.WebDriver; import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.interactions.internal.Coordinates; /** * @author Lukas Fryc @@ -36,12 +43,65 @@ public class TestSeleniumResourceProvider { @Before public void setUp() { - GrapheneContext.set(driver); + when(((HasInputDevices) driver).getKeyboard()).thenReturn(new Keyboard() { + @Override + public void sendKeys(CharSequence... keysToSend) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void pressKey(Keys keyToPress) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void releaseKey(Keys keyToRelease) { + throw new UnsupportedOperationException("Not supported yet."); + } + }); + when(((HasInputDevices) driver).getMouse()).thenReturn(new Mouse() { + + @Override + public void click(Coordinates where) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void doubleClick(Coordinates where) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void mouseDown(Coordinates where) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void mouseUp(Coordinates where) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void mouseMove(Coordinates where) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void mouseMove(Coordinates where, long xOffset, long yOffset) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void contextClick(Coordinates where) { + throw new UnsupportedOperationException("Not supported yet."); + } + }); + GrapheneContext.setContextFor(new GrapheneConfiguration(), driver, Default.class); } @After public void tearDown() { - GrapheneContext.reset(); + GrapheneContext.removeContextFor(Default.class); } @Test @@ -79,7 +139,9 @@ public void testIndirectProviderLookup() { // when Object object = provider.lookup(null, null); // then + assertNotNull(object); assertTrue(object instanceof Keyboard); + assertTrue(object instanceof GrapheneProxyInstance); } @Test @@ -89,7 +151,9 @@ public void testMouseProviderLookup() { // when Object object = provider.lookup(null, null); // then + assertNotNull(object); assertTrue(object instanceof Mouse); + assertTrue(object instanceof GrapheneProxyInstance); } @Test diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java index 43f08645c..9ca56910b 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java @@ -21,12 +21,13 @@ */ package org.jboss.arquillian.graphene.enricher; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; @@ -55,10 +56,10 @@ public void generated_webelement_implements_WrapsElement_interface() { assertTrue(page.element instanceof WrapsElement); - GrapheneContext.set(driver); + GrapheneContext.setContextFor(new GrapheneConfiguration(), driver, Default.class); when(driver.findElement(Mockito.any(By.class))).thenReturn(element); WebElement wrappedElement = ((WrapsElement) page.element).getWrappedElement(); - GrapheneContext.reset(); + GrapheneContext.removeContextFor(Default.class); assertEquals(element, wrappedElement); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java index dc17a08fb..12b1a4a8d 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java @@ -8,7 +8,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; -import org.jboss.arquillian.graphene.context.GrapheneContext; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; @@ -19,63 +18,65 @@ public class TestWebElementLazyEvaluation extends AbstractGrapheneEnricherTest { @Test public void when_WebElement_is_injected_then_it_is_first_evaluated_at_first_interaction() { - WebDriver driver = mock(WebDriver.class); WebElement element = mock(WebElement.class); - when(driver.findElement(any(By.class))).thenReturn(element); - - GrapheneContext.set(driver); + when(browser.findElement(any(By.class))).thenReturn(element); TPageFragment fragment = new TPageFragment(); getGrapheneEnricher().enrich(fragment); - verifyZeroInteractions(driver, element); + verifyZeroInteractions(browser, element); - fragment.element.click(); - fragment.element.click(); + fragment.getElement().click(); + fragment.getElement().click(); // the search for element should be done for every invocation - verify(driver, times(2)).findElement(any(By.class)); + verify(browser, times(2)).findElement(any(By.class)); verify(element, times(2)).click(); - verifyNoMoreInteractions(driver, element); + verifyNoMoreInteractions(browser, element); } @Test public void when_page_fragment_is_injected_then_searching_for_its_siblings_is_done_for_each_invocation() { - WebDriver driver = mock(WebDriver.class); WebElement rootElement = mock(WebElement.class); WebElement element = mock(WebElement.class); - when(driver.findElement(any(By.class))).thenReturn(rootElement); + when(browser.findElement(any(By.class))).thenReturn(rootElement); when(rootElement.findElement(any(By.class))).thenReturn(element); - GrapheneContext.set(driver); - TPage page = new TPage(); getGrapheneEnricher().enrich(page); - verifyZeroInteractions(driver, element); + verifyZeroInteractions(browser, element); - page.fragment.element.click(); - page.fragment.element.click(); - page.fragment.element.click(); + page.getFragment().getElement().click(); + page.getFragment().getElement().click(); + page.getFragment().getElement().click(); // the search for element should be done for every invocation - verify(driver, times(3)).findElement(any(By.class)); + verify(browser, times(3)).findElement(any(By.class)); verify(rootElement, times(3)).findElement(any(By.class)); verify(element, times(3)).click(); - verifyNoMoreInteractions(driver, element); + verifyNoMoreInteractions(browser, element); } - private static class TPage { + public static class TPage { @FindBy(id = "test") TPageFragment fragment; + + public TPageFragment getFragment() { + return fragment; + } } - private static class TPageFragment { + public static class TPageFragment { @FindBy(id = "test") WebElement element; + + public WebElement getElement() { + return element; + } } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java index ff12f9cf9..a2db9d7a1 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java @@ -10,7 +10,6 @@ import java.util.HashMap; import java.util.Map; -import org.jboss.arquillian.graphene.context.GrapheneContext; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -20,7 +19,6 @@ import org.mockito.stubbing.Answer; import org.openqa.selenium.By; import org.openqa.selenium.StaleElementReferenceException; -import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -29,7 +27,6 @@ public class TestWebElementStaleness extends AbstractGrapheneEnricherTest { private Map<WebElement, Boolean> staleness = new HashMap<WebElement, Boolean>(); - private WebDriver driver; private WebElement rootElement; private WebElement webElement; @@ -37,13 +34,10 @@ public class TestWebElementStaleness extends AbstractGrapheneEnricherTest { @Before public void prepare() { - driver = mock(WebDriver.class); - GrapheneContext.set(driver); - rootElement = mock(WebElement.class, new StaleElementAnswer()); webElement = mock(WebElement.class, new StaleElementAnswer()); - when(driver.findElement(any(By.class))).thenReturn(rootElement); + when(browser.findElement(any(By.class))).thenReturn(rootElement); when(rootElement.findElement(any(By.class))).thenReturn(webElement); page = new Page(); @@ -54,14 +48,14 @@ public void prepare() { public void test_fragment_subelement_is_stale() { // when makeStale(webElement); - page.fragment.element.click(); + page.getFragment().getElement().click(); // then - verify(driver, times(2)).findElement(any(By.class)); + verify(browser, times(2)).findElement(any(By.class)); verify(rootElement, times(2)).findElement(any(By.class)); verify(webElement, times(2)).click(); - verifyNoMoreInteractions(driver, webElement); + verifyNoMoreInteractions(browser, webElement); } @Test @@ -69,14 +63,14 @@ public void test_page_where_page_fragment_reference_is_stale() { // when makeStale(rootElement); makeStale(webElement); - page.fragment.element.click(); + page.getFragment().getElement().click(); // then - verify(driver, times(2)).findElement(any(By.class)); + verify(browser, times(2)).findElement(any(By.class)); verify(rootElement, times(2)).findElement(any(By.class)); verify(webElement, times(2)).click(); - verifyNoMoreInteractions(driver, webElement); + verifyNoMoreInteractions(browser, webElement); } private boolean isStale(WebElement element) { @@ -95,16 +89,24 @@ private void makeStale(WebElement element) { private static class Page { @FindBy(id = "test") - PageFragment fragment; + private PageFragment fragment; + + public PageFragment getFragment() { + return fragment; + } } - private static class PageFragment { + public static class PageFragment { @FindBy(id = "test") - WebElement element; + private WebElement element; + + public WebElement getElement() { + return element; + } } - private class StaleElementAnswer implements Answer<Object> { + public class StaleElementAnswer implements Answer<Object> { @Override public Object answer(InvocationOnMock invocation) throws Throwable { diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java index 2428e8cf4..e4a7b0a21 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java @@ -33,12 +33,15 @@ public class WrongPageFragmentTooManyRoots { @SuppressWarnings("unused") @Root private WebElement root1; - + @SuppressWarnings("unused") @Root private WebElement root2; - + @SuppressWarnings("unused") @FindBy(className="randomClassName") private WebElement foo; + + public void doSomething() { + } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java index 9f6fd17d0..2dc096e8d 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java @@ -12,10 +12,11 @@ public class TestIntercepting { public void testInterceptorCalling() { // having MyObject target = new MyObject(); - MyObject proxy = GrapheneProxy.getProxyForTarget(target); + MyObject proxy = GrapheneProxy.getProxyForTarget(null, target); // when ((GrapheneProxyInstance) proxy).registerInterceptor(new Interceptor() { + @Override public Object intercept(InvocationContext context) throws Throwable { return context.invoke(); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java index c4a538224..d7d531012 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java @@ -1,5 +1,8 @@ package org.jboss.arquillian.graphene.intercept; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -35,6 +38,8 @@ public class TestInterceptorBuilder { @Mock By by; + GrapheneContext context; + @Before public void before() throws Throwable { Answer invoke = new Answer<Object>() { @@ -46,6 +51,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { when(interceptor1.intercept(Mockito.any(InvocationContext.class))).thenAnswer(invoke); when(interceptor2.intercept(Mockito.any(InvocationContext.class))).thenAnswer(invoke); + context = GrapheneContext.setContextFor(new GrapheneConfiguration(), driver, Default.class); } @Test @@ -55,7 +61,7 @@ public void test() throws Throwable { builder.interceptInvocation(WebDriver.class, interceptor2).findElement(Interceptors.any(By.class)); Interceptor builtInterceptor = builder.build(); - WebDriver driverProxy = GrapheneProxy.getProxyForTargetWithInterfaces(driver, WebDriver.class); + WebDriver driverProxy = GrapheneProxy.getProxyForTargetWithInterfaces(context, driver, WebDriver.class); GrapheneProxyInstance proxy = (GrapheneProxyInstance) driverProxy; proxy.registerInterceptor(builtInterceptor); diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java index 4af4a5588..99f6393da 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java @@ -1,12 +1,9 @@ package org.jboss.arquillian.graphene.javascript; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.TestingDriverStub; import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext; -import org.jboss.arquillian.graphene.context.TestingDriverStub; -import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl; -import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider; import org.junit.Test; import static org.mockito.Mockito.times; import static org.mockito.Mockito.spy; @@ -32,11 +29,7 @@ public void test_execution() { when(executor.executeScript("return true;")).thenReturn(true); // when - GrapheneContext.set(executor); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl()); - GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor)); - TestingInterface instance = JSInterfaceFactory.create(TestingInterface.class); + TestingInterface instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class); instance.method(); // then @@ -51,11 +44,7 @@ public void test_execution_with_named_method() { when(executor.executeScript("return true;")).thenReturn(true); // when - GrapheneContext.set(executor); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl()); - GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor)); - TestingInterface instance = JSInterfaceFactory.create(TestingInterface.class); + TestingInterface instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class); instance.namedMethod(); // then @@ -75,11 +64,7 @@ public void test_execution_with_base() { when(executor.executeScript("return true;")).thenReturn(true); // when - GrapheneContext.set(executor); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl()); - GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor)); - TestingInterfaceWithBase instance = JSInterfaceFactory.create(TestingInterfaceWithBase.class); + TestingInterfaceWithBase instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterfaceWithBase.class); instance.method(); // then diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java index fe3124019..0202d972f 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java @@ -1,17 +1,24 @@ package org.jboss.arquillian.graphene.javascript; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; +import org.jboss.arquillian.graphene.TestingDriverStub; import static org.junit.Assert.assertTrue; import org.junit.Test; +import org.mockito.Spy; public class TestInstantiation { + @Spy + TestingDriverStub executor = new TestingDriverStub(); + @JavaScript public static interface TestingInterface { } @Test public void factory_should_create_valid_instance_of_given_interface() { - TestingInterface instance = JSInterfaceFactory.create(TestingInterface.class); + TestingInterface instance = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), TestingInterface.class); assertTrue("instance should implement the provided interface", instance instanceof TestingInterface); } @@ -21,6 +28,6 @@ public static class InvalidClass { @Test(expected = IllegalArgumentException.class) public void factory_should_fail_when_class_provided() { - JSInterfaceFactory.create(InvalidClass.class); + InvalidClass instance = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), InvalidClass.class); } } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java index 2f1a11146..be2d82f11 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java @@ -1,17 +1,15 @@ package org.jboss.arquillian.graphene.javascript; -import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; +import java.util.Arrays; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext; -import org.jboss.arquillian.graphene.context.TestingDriverStub; -import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl; -import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider; +import org.jboss.arquillian.graphene.TestingDriverStub; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; @@ -42,11 +40,7 @@ public interface TestingInterface { public void prepareTest() { // given MockitoAnnotations.initMocks(this); - GrapheneContext.set(executor); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl()); - GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor)); - instance = JSInterfaceFactory.create(TestingInterface.class); + instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class); when(executor.executeScript("return true;")).thenReturn(true); } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java index a57077fc0..6d0ea78fb 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java @@ -1,17 +1,14 @@ package org.jboss.arquillian.graphene.javascript; -import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; -import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.jboss.arquillian.graphene.context.GrapheneContext; -import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext; -import org.jboss.arquillian.graphene.context.TestingDriverStub; -import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl; -import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider; +import org.jboss.arquillian.graphene.TestingDriverStub; +import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -46,13 +43,10 @@ public interface TestingInterface { public void prepareTest() { // given MockitoAnnotations.initMocks(this); - GrapheneContext.set(executor); - GrapheneConfigurationContext.set(new GrapheneConfiguration()); - GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl()); - GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor)); - instance = JSInterfaceFactory.create(TestingInterface.class); + instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class); when(executor.executeScript(Mockito.anyString())).then(new Answer<Object>() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return answer; } diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java index 3886d4fc7..44b8aca76 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java @@ -21,7 +21,6 @@ */ package org.jboss.arquillian.graphene.proxy; -import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; @@ -32,6 +31,8 @@ import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; +import org.jboss.arquillian.drone.api.annotation.Default; +import org.jboss.arquillian.graphene.GrapheneContext; import org.junit.Before; import org.junit.Test; @@ -60,6 +61,7 @@ private class IsProxyable implements Answer<Object> { List<Method> violations = new LinkedList<Method>(); + @Override public Object answer(InvocationOnMock invocation) throws Throwable { Method method = invocation.getMethod(); if (!handler.isProxyable(method, invocation.getArguments())) { @@ -77,6 +79,7 @@ private class IsNotProxyable implements Answer<Object> { List<Method> violations = new LinkedList<Method>(); + @Override public Object answer(InvocationOnMock invocation) throws Throwable { Method method = invocation.getMethod(); if (handler.isProxyable(method, invocation.getArguments())) { @@ -92,7 +95,7 @@ public List<Method> getViolations() { @Before public void prepare() { - handler = GrapheneProxyHandler.forTarget(null); + handler = GrapheneProxyHandler.forTarget(GrapheneContext.getContextFor(Default.class), null); } @Test diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java index a098e73bd..a91778ace 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java @@ -21,8 +21,7 @@ */ package org.jboss.arquillian.graphene.proxy; -import org.jboss.arquillian.graphene.context.TestingDriverStub; -import org.jboss.arquillian.graphene.proxy.GrapheneProxy; +import org.jboss.arquillian.graphene.TestingDriverStub; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; @@ -43,7 +42,7 @@ public Object getTarget() { }; // when - TestingDriver driver = GrapheneProxy.<TestingDriver>getProxyForFutureTarget(target, TestingDriver.class); + TestingDriver driver = GrapheneProxy.<TestingDriver>getProxyForFutureTarget(null, target, TestingDriver.class); try { driver.quit(); fail("exception should be thrown because of FutureTarget definition"); diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java index 68e081cea..5000a1e86 100644 --- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java +++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java @@ -27,9 +27,9 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import org.jboss.arquillian.graphene.context.TestingDriver; -import org.jboss.arquillian.graphene.context.TestingDriverStub; -import org.jboss.arquillian.graphene.context.TestingDriverStubExtension; +import org.jboss.arquillian.graphene.TestingDriver; +import org.jboss.arquillian.graphene.TestingDriverStub; +import org.jboss.arquillian.graphene.TestingDriverStubExtension; import org.junit.Test; import org.openqa.selenium.SearchContext;
a0be0f79a696abe57fec91088db97a2dcced676a
drools
fix failing tests--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModules.java b/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModules.java index 9b5d94e1a1c..a4f45369d1d 100644 --- a/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModules.java +++ b/drools-compiler/src/main/java/org/kie/builder/impl/AbstractKieModules.java @@ -24,15 +24,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; +import static org.kie.builder.impl.KieBuilderImpl.isKieExtension; + public abstract class AbstractKieModules implements InternalKieModule { @@ -49,10 +48,10 @@ public abstract class AbstractKieModules private Map<GAV, InternalKieModule> kieModules; - private Map<String, InternalKieModule> kJarFromKBaseName = new HashMap<String, InternalKieModule>(); + private final Map<String, InternalKieModule> kJarFromKBaseName = new HashMap<String, InternalKieModule>(); - private Map<String, KieBaseModel> kBaseModels = new HashMap<String, KieBaseModel>(); - private Map<String, KieSessionModel> kSessionModels = new HashMap<String, KieSessionModel>(); + private final Map<String, KieBaseModel> kBaseModels = new HashMap<String, KieBaseModel>(); + private final Map<String, KieSessionModel> kSessionModels = new HashMap<String, KieSessionModel>(); public AbstractKieModules(GAV gav) { this.gav = gav; @@ -144,10 +143,7 @@ public static void indexParts(Map<GAV, InternalKieModule> kJars, public CompositeClassLoader createClassLaoder() { Map<String, byte[]> classes = new HashMap<String, byte[]>(); - for( Entry<GAV, InternalKieModule> entry : kieModules.entrySet() ) { - GAV gav = entry.getKey(); - InternalKieModule kModule = entry.getValue(); - List<String> fileNames = new ArrayList<String>(); + for( InternalKieModule kModule : kieModules.values() ) { for( String fileName : kModule.getFileNames() ) { if ( fileName.endsWith( ".class" ) ) { classes.put( fileName, kModule.getBytes( fileName ) ); @@ -224,16 +220,10 @@ public static void addFiles(CompositeKnowledgeBuilder ckbuilder, String prefixPath = kieBaseModel.getName().replace( '.', '/' ); for ( String fileName : kieModule.getFileNames() ) { - if ( fileName.startsWith( prefixPath ) ) { - String upperCharName = fileName.toUpperCase(); - - if ( upperCharName.endsWith( "DRL" ) ) { - ckbuilder.add( ResourceFactory.newByteArrayResource( kieModule.getBytes( fileName ) ), - ResourceType.DRL ); - fileCount++; - } else if ( upperCharName.endsWith( "BPMN2" ) ) { + if ( ((KieBaseModelImpl)kieBaseModel).isDefault() || fileName.startsWith( prefixPath ) ) { + if ( isKieExtension(fileName) ) { ckbuilder.add( ResourceFactory.newByteArrayResource( kieModule.getBytes( fileName ) ), - ResourceType.DRL ); + ResourceType.determineResourceType( fileName ) ); fileCount++; } } diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java index 76f10e51f58..c46fd856478 100644 --- a/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java +++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieBuilderImpl.java @@ -7,7 +7,6 @@ import org.drools.commons.jci.readers.DiskResourceReader; import org.drools.commons.jci.readers.ResourceReader; import org.drools.compiler.io.memory.MemoryFileSystem; -import org.drools.core.util.ClassUtils; import org.drools.core.util.StringUtils; import org.drools.kproject.GAVImpl; import org.drools.kproject.models.KieBaseModelImpl; @@ -27,8 +26,6 @@ import org.kie.builder.Message.Level; import org.kie.builder.ResourceType; import org.kie.builder.Results; -import org.kie.util.ClassLoaderUtil; -import org.kie.util.CompositeClassLoader; import java.io.ByteArrayInputStream; import java.io.File; @@ -46,6 +43,8 @@ public class KieBuilderImpl implements KieBuilder { + private static final String RESOURCES_ROOT = "src/main/resources/"; + private Messages messages; private final ResourceReader srcMfs; @@ -106,7 +105,7 @@ public Results build() { trgMfs = new MemoryFileSystem(); writePomAndKProject(); - ClassLoader classLoader = compileJavaClasses(); + compileJavaClasses(); addKBasesFilesToTrg(); kieModule = new MemoryKieModules( gav, @@ -149,12 +148,11 @@ private KnowledgeBaseConfiguration getKnowledgeBaseConfiguration(KieBaseModel ki } private void addKBaseFilesToTrg(KieBaseModel kieBase) { - String resourcesRoot = "src/main/resources/"; for ( String fileName : srcMfs.getFileNames() ) { if ( filterFileInKBase( kieBase, fileName ) ) { byte[] bytes = srcMfs.getBytes( fileName ); - trgMfs.write( fileName.substring( resourcesRoot.length() - 1 ), + trgMfs.write( fileName.substring( RESOURCES_ROOT.length() - 1 ), bytes, true ); } @@ -162,11 +160,10 @@ private void addKBaseFilesToTrg(KieBaseModel kieBase) { } private void addMetaInfBuilder() { - String resourcesRoot = "src/main/resources/"; for ( String fileName : srcMfs.getFileNames() ) { - if ( fileName.startsWith( resourcesRoot ) ) { + if ( fileName.startsWith( RESOURCES_ROOT ) && !isKieExtension(fileName) ) { byte[] bytes = srcMfs.getBytes( fileName ); - trgMfs.write( fileName.substring( resourcesRoot.length() - 1 ), + trgMfs.write( fileName.substring( RESOURCES_ROOT.length() - 1 ), bytes, true ); } @@ -198,10 +195,10 @@ private boolean isFileInKiePackage(String fileName, String pkgName) { String pathName = pkgName.replace( '.', '/' ); - return (fileName.startsWith( "src/main/resources/" + pathName + "/" ) || fileName.contains( "/" + pathName + "/" )); + return (fileName.startsWith( RESOURCES_ROOT + pathName + "/" ) || fileName.contains( "/" + pathName + "/" )); } - private boolean isKieExtension(String fileName) { + static boolean isKieExtension(String fileName) { return fileName.endsWith( ResourceType.DRL.getDefaultExtension() ) || fileName.endsWith( ResourceType.BPMN2.getDefaultExtension() ); } @@ -362,7 +359,7 @@ public static String generatePomProperties(GAV gav) { return sBuilder.toString(); } - private ClassLoader compileJavaClasses() { + private void compileJavaClasses() { List<String> classFiles = new ArrayList<String>(); for ( String fileName : srcMfs.getFileNames() ) { if ( fileName.endsWith( ".class" ) ) { @@ -382,7 +379,7 @@ private ClassLoader compileJavaClasses() { } } if ( javaFiles.isEmpty() ) { - return getCompositeClassLoader(); + return; } String[] sourceFiles = javaFiles.toArray( new String[javaFiles.size()] ); @@ -398,8 +395,6 @@ private ClassLoader compileJavaClasses() { for ( CompilationProblem problem : res.getWarnings() ) { messages.addMessage( problem ); } - - return res.getErrors().length == 0 ? getCompositeClassLoader() : getClass().getClassLoader(); } public static String findPomProperties(ZipFile zipFile) { @@ -434,15 +429,6 @@ public static File recurseToPomProperties(File file) { return null; } - private CompositeClassLoader getCompositeClassLoader() { - CompositeClassLoader ccl = ClassLoaderUtil.getClassLoader( null, - getClass(), - true ); - ccl.addClassLoader( new ClassUtils.MapClassLoader( trgMfs.getMap(), - ccl ) ); - return ccl; - } - private EclipseJavaCompiler createCompiler(String prefix) { EclipseJavaCompilerSettings settings = new EclipseJavaCompilerSettings(); settings.setSourceVersion( "1.5" ); @@ -450,5 +436,4 @@ private EclipseJavaCompiler createCompiler(String prefix) { return new EclipseJavaCompiler( settings, prefix ); } - } diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java index 0d9f13920bb..a0dd2000029 100644 --- a/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java +++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieContainerImpl.java @@ -68,13 +68,11 @@ public KieBase getKieBase(String kBaseName) { } public KieSession getKieSession() { - // @TODO - throw new UnsupportedOperationException( "This method is still to be implemented" ); + return getKieBase().newKieSession(); } public StatelessKieSession getKieStatelessSession() { - // @TODO - throw new UnsupportedOperationException( "This method is still to be implemented" ); + return getKieBase().newStatelessKieSession(); } public KieSession getKieSession(String kSessionName) { diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java index 2f1a8567e2d..887e9dac3db 100644 --- a/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java +++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java @@ -1,9 +1,5 @@ package org.kie.builder.impl; -import static org.drools.compiler.io.memory.MemoryFileSystem.readFromJar; - -import java.io.File; - import org.drools.audit.KnowledgeRuntimeLoggerProviderImpl; import org.drools.command.impl.CommandFactoryServiceImpl; import org.drools.concurrent.ExecutorProviderImpl; @@ -25,6 +21,10 @@ import org.kie.persistence.jpa.KieStoreServices; import org.kie.util.ServiceRegistryImpl; +import java.io.File; + +import static org.drools.compiler.io.memory.MemoryFileSystem.readFromJar; + public class KieServicesImpl implements KieServices { private ResourceFactoryService resourceFactory; @@ -43,7 +43,7 @@ public KieRepository getKieRepository() { * Returns KieContainer for the classpath */ public KieContainer getKieContainer() { - return new KieContainerImpl( new ClasspathKieProject( getKieRepository() ), getKieRepository() ); + return getKieContainer(getKieRepository().getDefaultGAV()); } public KieContainer getKieContainer(GAV gav) { diff --git a/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java b/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java index 7b5c29e7262..f79bae34a1b 100644 --- a/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java +++ b/drools-compiler/src/test/java/org/drools/builder/KieBuilderTest.java @@ -5,7 +5,6 @@ import org.drools.core.util.FileManager; import org.drools.kproject.GAVImpl; import org.drools.kproject.models.KieBaseModelImpl; -import org.drools.kproject.models.KieModuleModelImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -33,9 +32,9 @@ import java.util.Arrays; import java.util.List; -import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class KieBuilderTest { @@ -100,14 +99,14 @@ public void testKieModuleDepednencies() throws ClassNotFoundException, Interrupt fail("Unable to build KieJar\n" + kb1.getResults( ).toString() ); } KieRepository kr = ks.getKieRepository(); - KieModule kModule1 = kr.getKieModule( gav1 ); + KieModule kModule1 = kr.getKieModule(gav1); assertNotNull( kModule1 ); String namespace2 = "org.kie.test2"; GAV gav2 = KieFactory.Factory.get().newGav( namespace2, "memory", "1.0-SNAPSHOT" ); KieModuleModel kProj2 = createKieProject(namespace2); - KieBaseModelImpl kieBase2 = ( KieBaseModelImpl ) ((KieModuleModelImpl)kProj2).getKieBaseModels().get( namespace2 ); + KieBaseModelImpl kieBase2 = ( KieBaseModelImpl ) kProj2.getKieBaseModels().get( namespace2 ); kieBase2.addInclude( namespace1 ); KieFileSystem kfs2 = KieFactory.Factory.get().newKieFileSystem(); @@ -120,7 +119,7 @@ public void testKieModuleDepednencies() throws ClassNotFoundException, Interrupt if ( kb2.hasResults( Level.ERROR ) ) { fail("Unable to build KieJar\n" + kb2.getResults( ).toString() ); } - KieModule kModule2= kr.getKieModule( gav2 ); + KieModule kModule2= kr.getKieModule(gav2); assertNotNull( kModule2); KieContainer kContainer = ks.getKieContainer( gav2 ); @@ -132,8 +131,13 @@ public void testKieModuleDepednencies() throws ClassNotFoundException, Interrupt kSession.fireAllRules(); assertEquals( 2, list.size() ); - assertEquals( "org.kie.test.Message", list.get(0).getClass().getName() ); - } + if ("org.kie.test1.Message".equals(list.get(0).getClass().getName())) { + assertEquals( "org.kie.test2.Message", list.get(1).getClass().getName() ); + } else { + assertEquals( "org.kie.test2.Message", list.get(0).getClass().getName() ); + assertEquals( "org.kie.test1.Message", list.get(1).getClass().getName() ); + } + } @Test public void testNoPomXml() throws ClassNotFoundException, InterruptedException, IOException { diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java index dda33523c8b..85bd6827967 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java @@ -32,7 +32,7 @@ public void testHelloWorld() throws Exception { KieServices ks = KieServices.Factory.get(); KieFactory kf = KieFactory.Factory.get(); - KieFileSystem kfs = kf.newKieFileSystem().write( "r1.drl", drl ); + KieFileSystem kfs = kf.newKieFileSystem().write( "src/main/resources/r1.drl", drl ); ks.newKieBuilder( kfs ).build(); KieSession ksession = ks.getKieContainer().getKieSession(); @@ -54,7 +54,7 @@ public void testFailingHelloWorld() throws Exception { KieServices ks = KieServices.Factory.get(); KieFactory kf = KieFactory.Factory.get(); - KieFileSystem kfs = kf.newKieFileSystem().write( "r1.drl", drl ); + KieFileSystem kfs = kf.newKieFileSystem().write( "src/main/resources/r1.drl", drl ); Results results = ks.newKieBuilder( kfs ).build(); assertEquals( 1, results.getInsertedMessages().size() ); @@ -81,8 +81,8 @@ public void testHelloWorldWithPackages() throws Exception { KieFileSystem kfs = kf.newKieFileSystem() .generateAndWritePomXML( gav ) - .write("src/main/resoureces/org/pkg1/r1.drl", drl1) - .write("src/main/resoureces/org/pkg2/r2.drl", drl2) + .write("src/main/resources/KBase1/org/pkg1/r1.drl", drl1) + .write("src/main/resources/KBase1/org/pkg2/r2.drl", drl2) .writeProjectXML( createKieProjectWithPackages(kf).toXML()); ks.newKieBuilder( kfs ).build(); diff --git a/drools-core/src/main/java/org/drools/world/impl/WorldImpl.java b/drools-core/src/main/java/org/drools/world/impl/WorldImpl.java index 53d4769979c..2f868da93c4 100644 --- a/drools-core/src/main/java/org/drools/world/impl/WorldImpl.java +++ b/drools-core/src/main/java/org/drools/world/impl/WorldImpl.java @@ -16,28 +16,16 @@ package org.drools.world.impl; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Set; -import java.util.concurrent.TimeUnit; - import org.drools.command.GetDefaultValue; -import org.drools.command.NewStatefulKnowledgeSessionCommand; -import org.drools.command.ResolvingKnowledgeCommandContext; import org.drools.command.impl.ContextImpl; import org.drools.command.impl.GenericCommand; -import org.drools.time.SessionPseudoClock; import org.kie.command.Command; import org.kie.command.Context; import org.kie.command.World; import org.kie.runtime.CommandExecutor; -import org.kie.runtime.StatefulKnowledgeSession; -import org.kie.simulation.Simulation; -import org.kie.simulation.SimulationPath; -import org.kie.simulation.SimulationStep; + +import java.util.HashMap; +import java.util.Map; public class WorldImpl implements World, GetDefaultValue, CommandExecutor { diff --git a/drools-maven-plugin/src/test/java/org/drools/BuildMojoTest.java b/drools-maven-plugin/src/test/java/org/drools/BuildMojoTest.java index 4ec028d0dc4..13d75aca5c3 100644 --- a/drools-maven-plugin/src/test/java/org/drools/BuildMojoTest.java +++ b/drools-maven-plugin/src/test/java/org/drools/BuildMojoTest.java @@ -1,13 +1,14 @@ package org.drools; -import java.io.File; - import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import java.io.File; + +@Ignore public class BuildMojoTest extends AbstractMojoTestCase { @Before @@ -20,7 +21,7 @@ protected void tearDown() throws Exception { super.tearDown(); } - @Test @Ignore + @Test public void testSomething() throws Exception {
c5c87c4a4809078b14a2ce49c8da6010dbad17b7
elasticsearch
[TEST] Don't delete data dirs after test - only- delete their content.--Closes -5815-
c
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/common/io/FileSystemUtils.java b/src/main/java/org/elasticsearch/common/io/FileSystemUtils.java index 103ea959ec4ab..5da1c0759be0b 100644 --- a/src/main/java/org/elasticsearch/common/io/FileSystemUtils.java +++ b/src/main/java/org/elasticsearch/common/io/FileSystemUtils.java @@ -74,20 +74,23 @@ public static boolean exists(File... files) { return false; } - public static boolean deleteRecursively(File[] roots) { + /** + * Deletes the given files recursively. if <tt>deleteRoots</tt> is set to <code>true</code> + * the given root files will be deleted as well. Otherwise only their content is deleted. + */ + public static boolean deleteRecursively(File[] roots, boolean deleteRoots) { boolean deleted = true; for (File root : roots) { - deleted &= deleteRecursively(root); + deleted &= deleteRecursively(root, deleteRoots); } return deleted; } - public static boolean deleteRecursively(File root) { - return deleteRecursively(root, true); - } - - private static boolean innerDeleteRecursively(File root) { - return deleteRecursively(root, true); + /** + * Deletes the given files recursively including the given roots. + */ + public static boolean deleteRecursively(File... roots) { + return deleteRecursively(roots, true); } /** @@ -105,7 +108,7 @@ public static boolean deleteRecursively(File root, boolean deleteRoot) { File[] children = root.listFiles(); if (children != null) { for (File aChildren : children) { - innerDeleteRecursively(aChildren); + deleteRecursively(aChildren, true); } } } diff --git a/src/test/java/org/elasticsearch/test/TestCluster.java b/src/test/java/org/elasticsearch/test/TestCluster.java index 5ca85ad10b06a..2e905192927ca 100644 --- a/src/test/java/org/elasticsearch/test/TestCluster.java +++ b/src/test/java/org/elasticsearch/test/TestCluster.java @@ -762,10 +762,11 @@ private void resetClients() { private void wipeDataDirectories() { if (!dataDirToClean.isEmpty()) { - logger.info("Wipe data directory for all nodes locations: {}", this.dataDirToClean); + boolean deleted = false; try { - FileSystemUtils.deleteRecursively(dataDirToClean.toArray(new File[dataDirToClean.size()])); + deleted = FileSystemUtils.deleteRecursively(dataDirToClean.toArray(new File[dataDirToClean.size()]), false); } finally { + logger.info("Wipe data directory for all nodes locations: {} success: {}", this.dataDirToClean, deleted); this.dataDirToClean.clear(); } }
efa5448aa3dd8afae7d1c5f3eb8798befb247e41
hbase
HBASE-3429 HBaseObjectWritable should support- arrays of any Writable or Serializable
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 1669735cb1d8..9843b6c1d928 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -46,6 +46,8 @@ Release 0.91.0 - Unreleased (Jesse Yates via Stack) HBASE-3393 Update Avro gateway to use Avro 1.4.1 and the new server.join() method (Jeff Hammerbacher via Stack) + HBASE-3429 HBaseObjectWritable should support arrays of any Writable + or Serializable, not just Writable[] (Ed Kohlwey via Stack) NEW FEATURES diff --git a/src/main/java/org/apache/hadoop/hbase/io/HbaseObjectWritable.java b/src/main/java/org/apache/hadoop/hbase/io/HbaseObjectWritable.java index ba9db37d8718..5b6bf2db526e 100644 --- a/src/main/java/org/apache/hadoop/hbase/io/HbaseObjectWritable.java +++ b/src/main/java/org/apache/hadoop/hbase/io/HbaseObjectWritable.java @@ -84,6 +84,7 @@ import org.apache.hadoop.hbase.regionserver.wal.HLog; import org.apache.hadoop.hbase.regionserver.wal.HLogKey; import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.Classes; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.ObjectWritable; import org.apache.hadoop.io.Text; @@ -382,7 +383,9 @@ public static void writeObject(DataOutput out, Object instance, declClass = Writable.class; } writeClassCode(out, declClass); - if (declClass.isArray()) { // array + // used to just be arrays. Now check for ones for which there's a + // class code, and let the others get scooped up by serializable. + if (declClass.isArray() && CLASS_TO_CODE.get(declClass)!=null) { // array // If bytearray, just dump it out -- avoid the recursion and // byte-at-a-time we were previously doing. if (declClass.equals(byte [].class)) { @@ -449,18 +452,27 @@ public static void writeObject(DataOutput out, Object instance, } else { writeClassCode(out, c); } - ByteArrayOutputStream bos = null; - ObjectOutputStream oos = null; - try{ - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - oos.writeObject(instanceObj); - byte[] value = bos.toByteArray(); - out.writeInt(value.length); - out.write(value); - } finally { - if(bos!=null) bos.close(); - if(oos!=null) oos.close(); + if(declClass.isArray()){ + int length = Array.getLength(instanceObj); + out.writeInt(length); + for (int i = 0; i < length; i++) { + writeObject(out, Array.get(instanceObj, i), + declClass.getComponentType(), conf); + } + } else { + ByteArrayOutputStream bos = null; + ObjectOutputStream oos = null; + try{ + bos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(bos); + oos.writeObject(instanceObj); + byte[] value = bos.toByteArray(); + out.writeInt(value.length); + out.write(value); + } finally { + if(bos!=null) bos.close(); + if(oos!=null) oos.close(); + } } } else { throw new IOException("Can't write: "+instanceObj+" as "+declClass); @@ -569,21 +581,29 @@ public static Object readObject(DataInput in, instance = null; } } else { - int length = in.readInt(); - byte[] objectBytes = new byte[length]; - in.readFully(objectBytes); - ByteArrayInputStream bis = null; - ObjectInputStream ois = null; - try { - bis = new ByteArrayInputStream(objectBytes); - ois = new ObjectInputStream(bis); - instance = ois.readObject(); - } catch (ClassNotFoundException e) { - LOG.error("Error in readFields", e); - throw new IOException("Error in readFields", e); - } finally { - if(bis!=null) bis.close(); - if(ois!=null) ois.close(); + if(instanceClass.isArray()){ + int length = in.readInt(); + instance = Array.newInstance(instanceClass.getComponentType(), length); + for(int i = 0; i< length; i++){ + Array.set(instance, i, HbaseObjectWritable.readObject(in, conf)); + } + } else { + int length = in.readInt(); + byte[] objectBytes = new byte[length]; + in.readFully(objectBytes); + ByteArrayInputStream bis = null; + ObjectInputStream ois = null; + try { + bis = new ByteArrayInputStream(objectBytes); + ois = new ObjectInputStream(bis); + instance = ois.readObject(); + } catch (ClassNotFoundException e) { + LOG.error("Error in readFields", e); + throw new IOException("Error in readFields", e); + } finally { + if(bis!=null) bis.close(); + if(ois!=null) ois.close(); + } } } } diff --git a/src/test/java/org/apache/hadoop/hbase/io/TestHbaseObjectWritable.java b/src/test/java/org/apache/hadoop/hbase/io/TestHbaseObjectWritable.java index 6bce5cd3e94f..2f0fa7dbad1f 100644 --- a/src/test/java/org/apache/hadoop/hbase/io/TestHbaseObjectWritable.java +++ b/src/test/java/org/apache/hadoop/hbase/io/TestHbaseObjectWritable.java @@ -21,6 +21,7 @@ import java.io.*; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import junit.framework.TestCase; @@ -122,6 +123,20 @@ public void testCustomWritable() throws Exception { assertEquals("mykey", ((CustomFilter)child).getKey()); } + public void testCustomWritableArray() throws Exception { + Configuration conf = HBaseConfiguration.create(); + + // test proper serialization of un-encoded custom writables + CustomWritable custom1 = new CustomWritable("test phrase"); + CustomWritable custom2 = new CustomWritable("test phrase2"); + CustomWritable[] customs = {custom1, custom2}; + Object obj = doType(conf, customs, CustomWritable[].class); + + assertTrue("Arrays should match " + Arrays.toString(customs) + ", " + + Arrays.toString((Object[]) obj), + Arrays.equals(customs, (Object[])obj)); + } + public void testCustomSerializable() throws Exception { Configuration conf = HBaseConfiguration.create(); @@ -132,6 +147,20 @@ public void testCustomSerializable() throws Exception { assertTrue(obj instanceof CustomSerializable); assertEquals("test phrase", ((CustomSerializable)obj).getValue()); } + + + public void testCustomSerializableArray() throws Exception { + Configuration conf = HBaseConfiguration.create(); + + // test proper serialization of un-encoded serialized java objects + CustomSerializable custom1 = new CustomSerializable("test phrase"); + CustomSerializable custom2 = new CustomSerializable("test phrase2"); + CustomSerializable[] custom = {custom1, custom2}; + Object obj = doType(conf, custom, CustomSerializable[].class); + assertTrue("Arrays should match " + Arrays.toString(custom) + ", " + + Arrays.toString((Object[]) obj), + Arrays.equals(custom, (Object[]) obj)); + } private Object doType(final Configuration conf, final Object value, final Class<?> clazz) @@ -149,7 +178,7 @@ private Object doType(final Configuration conf, final Object value, } public static class CustomSerializable implements Serializable { - private static final long serialVersionUID = 1048445561865740632L; + private static final long serialVersionUID = 1048445561865740633L; private String value = null; public CustomSerializable() { @@ -167,6 +196,21 @@ public void setValue(String value) { this.value = value; } + @Override + public boolean equals(Object obj) { + return (obj instanceof CustomSerializable) && ((CustomSerializable)obj).value.equals(value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return "<" + value + ">"; + } + } public static class CustomWritable implements Writable { @@ -190,6 +234,21 @@ public void write(DataOutput out) throws IOException { public void readFields(DataInput in) throws IOException { this.value = Text.readString(in); } + + @Override + public boolean equals(Object obj) { + return (obj instanceof CustomWritable) && ((CustomWritable)obj).value.equals(value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return "<" + value + ">"; + } } public static class CustomFilter extends FilterBase {
a2f8902b3a8569a1ebb4b4c87fab5a412cf4d389
spring-framework
Inlined AntPathStringMatcher into AntPathMatcher--Also initializing the capacity of the AntPathStringMatcher cache to 256 now.-
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java b/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java index dd69dee00418..059c9f7a10c4 100644 --- a/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java +++ b/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java @@ -18,6 +18,8 @@ import java.util.Comparator; import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; @@ -43,6 +45,7 @@ * @author Juergen Hoeller * @author Rob Harrop * @author Arjen Poutsma + * @author Rossen Stoyanchev * @since 16.07.2003 */ public class AntPathMatcher implements PathMatcher { @@ -55,7 +58,7 @@ public class AntPathMatcher implements PathMatcher { private String pathSeparator = DEFAULT_PATH_SEPARATOR; private final Map<String, AntPathStringMatcher> stringMatcherCache = - new ConcurrentHashMap<String, AntPathStringMatcher>(); + new ConcurrentHashMap<String, AntPathStringMatcher>(256); /** Set the path separator to use for pattern parsing. Default is "/", as in Ant. */ @@ -213,8 +216,9 @@ else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) { } /** - * Tests whether or not a string matches against a pattern. The pattern may contain two special characters:<br> '*' - * means zero or more characters<br> '?' means one and only one character + * Tests whether or not a string matches against a pattern. The pattern may contain two special characters: + * <br>'*' means zero or more characters + * <br>'?' means one and only one character * @param pattern pattern to match against. Must not be <code>null</code>. * @param str string which must be matched against the pattern. Must not be <code>null</code>. * @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise. @@ -462,4 +466,88 @@ private int getPatternLength(String pattern) { } } + + /** + * Tests whether or not a string matches against a pattern via a {@link Pattern}. + * <p>The pattern may contain special characters: '*' means zero or more characters; '?' means one and + * only one character; '{' and '}' indicate a URI template pattern. For example <tt>/users/{user}</tt>. + */ + private static class AntPathStringMatcher { + + private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}"); + + private static final String DEFAULT_VARIABLE_PATTERN = "(.*)"; + + private final Pattern pattern; + + private final List<String> variableNames = new LinkedList<String>(); + + public AntPathStringMatcher(String pattern) { + StringBuilder patternBuilder = new StringBuilder(); + Matcher m = GLOB_PATTERN.matcher(pattern); + int end = 0; + while (m.find()) { + patternBuilder.append(quote(pattern, end, m.start())); + String match = m.group(); + if ("?".equals(match)) { + patternBuilder.append('.'); + } + else if ("*".equals(match)) { + patternBuilder.append(".*"); + } + else if (match.startsWith("{") && match.endsWith("}")) { + int colonIdx = match.indexOf(':'); + if (colonIdx == -1) { + patternBuilder.append(DEFAULT_VARIABLE_PATTERN); + this.variableNames.add(m.group(1)); + } + else { + String variablePattern = match.substring(colonIdx + 1, match.length() - 1); + patternBuilder.append('('); + patternBuilder.append(variablePattern); + patternBuilder.append(')'); + String variableName = match.substring(1, colonIdx); + this.variableNames.add(variableName); + } + } + end = m.end(); + } + patternBuilder.append(quote(pattern, end, pattern.length())); + this.pattern = Pattern.compile(patternBuilder.toString()); + } + + private String quote(String s, int start, int end) { + if (start == end) { + return ""; + } + return Pattern.quote(s.substring(start, end)); + } + + /** + * Main entry point. + * @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise. + */ + public boolean matchStrings(String str, Map<String, String> uriTemplateVariables) { + Matcher matcher = this.pattern.matcher(str); + if (matcher.matches()) { + if (uriTemplateVariables != null) { + // SPR-8455 + Assert.isTrue(this.variableNames.size() == matcher.groupCount(), + "The number of capturing groups in the pattern segment " + this.pattern + + " does not match the number of URI template variables it defines, which can occur if " + + " capturing groups are used in a URI template regex. Use non-capturing groups instead."); + for (int i = 1; i <= matcher.groupCount(); i++) { + String name = this.variableNames.get(i - 1); + String value = matcher.group(i); + uriTemplateVariables.put(name, value); + } + } + return true; + } + else { + return false; + } + } + } + } diff --git a/spring-core/src/main/java/org/springframework/util/AntPathStringMatcher.java b/spring-core/src/main/java/org/springframework/util/AntPathStringMatcher.java deleted file mode 100644 index 424b60930e21..000000000000 --- a/spring-core/src/main/java/org/springframework/util/AntPathStringMatcher.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2002-2012 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.util; - -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Package-protected helper class for {@link AntPathMatcher}. Tests whether or not a string matches against a pattern - * via a {@link Pattern}. - * - * <p>The pattern may contain special characters: '*' means zero or more characters; '?' means one and only one - * character; '{' and '}' indicate a URI template pattern. For example <tt>/users/{user}</tt>. - * - * @author Arjen Poutsma - * @author Rossen Stoyanchev - * @since 3.0 - */ -class AntPathStringMatcher { - - private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}"); - - private static final String DEFAULT_VARIABLE_PATTERN = "(.*)"; - - private final Pattern pattern; - - private final List<String> variableNames = new LinkedList<String>(); - - - /** Construct a new instance of the <code>AntPatchStringMatcher</code>. */ - AntPathStringMatcher(String pattern) { - this.pattern = createPattern(pattern); - } - - private Pattern createPattern(String pattern) { - StringBuilder patternBuilder = new StringBuilder(); - Matcher m = GLOB_PATTERN.matcher(pattern); - int end = 0; - while (m.find()) { - patternBuilder.append(quote(pattern, end, m.start())); - String match = m.group(); - if ("?".equals(match)) { - patternBuilder.append('.'); - } - else if ("*".equals(match)) { - patternBuilder.append(".*"); - } - else if (match.startsWith("{") && match.endsWith("}")) { - int colonIdx = match.indexOf(':'); - if (colonIdx == -1) { - patternBuilder.append(DEFAULT_VARIABLE_PATTERN); - variableNames.add(m.group(1)); - } - else { - String variablePattern = match.substring(colonIdx + 1, match.length() - 1); - patternBuilder.append('('); - patternBuilder.append(variablePattern); - patternBuilder.append(')'); - String variableName = match.substring(1, colonIdx); - variableNames.add(variableName); - } - } - end = m.end(); - } - patternBuilder.append(quote(pattern, end, pattern.length())); - return Pattern.compile(patternBuilder.toString()); - } - - private String quote(String s, int start, int end) { - if (start == end) { - return ""; - } - return Pattern.quote(s.substring(start, end)); - } - - /** - * Main entry point. - * - * @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise. - */ - public boolean matchStrings(String str, Map<String, String> uriTemplateVariables) { - Matcher matcher = pattern.matcher(str); - if (matcher.matches()) { - if (uriTemplateVariables != null) { - // SPR-8455 - Assert.isTrue(variableNames.size() == matcher.groupCount(), - "The number of capturing groups in the pattern segment " + pattern + - " does not match the number of URI template variables it defines, which can occur if " + - " capturing groups are used in a URI template regex. Use non-capturing groups instead."); - for (int i = 1; i <= matcher.groupCount(); i++) { - String name = this.variableNames.get(i - 1); - String value = matcher.group(i); - uriTemplateVariables.put(name, value); - } - } - return true; - } - else { - return false; - } - } - -}
874b4979d00ef6c9c350efcb77bc452bcfea8754
hadoop
YARN-1920. Fixed- TestFileSystemApplicationHistoryStore failure on windows. Contributed by- Vinod Kumar Vavilapalli. svn merge --ignore-ancestry -c 1586414 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1586420 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 188a80035ac85..e2af3191db8e9 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -82,6 +82,9 @@ Release 2.4.1 - UNRELEASED YARN-1910. Fixed a race condition in TestAMRMTokens that causes the test to fail more often on Windows. (Xuan Gong via vinodkv) + YARN-1920. Fixed TestFileSystemApplicationHistoryStore failure on windows. + (Vinod Kumar Vavilapalli via zjshen) + Release 2.4.0 - 2014-04-07 INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java index 4c8d7452a251e..a5725ebfffeeb 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java @@ -179,7 +179,7 @@ public ApplicationHistoryData getApplication(ApplicationId appId) LOG.info("Completed reading history information of application " + appId); return historyData; } catch (IOException e) { - LOG.error("Error when reading history file of application " + appId); + LOG.error("Error when reading history file of application " + appId, e); throw e; } finally { hfReader.close(); @@ -296,7 +296,7 @@ public ApplicationAttemptHistoryData getApplicationAttempt( return historyData; } catch (IOException e) { LOG.error("Error when reading history file of application attempt" - + appAttemptId); + + appAttemptId, e); throw e; } finally { hfReader.close(); @@ -344,7 +344,7 @@ public ContainerHistoryData getContainer(ContainerId containerId) + containerId); return historyData; } catch (IOException e) { - LOG.error("Error when reading history file of container " + containerId); + LOG.error("Error when reading history file of container " + containerId, e); throw e; } finally { hfReader.close(); @@ -420,7 +420,7 @@ public void applicationStarted(ApplicationStartData appStart) + appStart.getApplicationId()); } catch (IOException e) { LOG.error("Error when openning history file of application " - + appStart.getApplicationId()); + + appStart.getApplicationId(), e); throw e; } outstandingWriters.put(appStart.getApplicationId(), hfWriter); @@ -437,7 +437,7 @@ public void applicationStarted(ApplicationStartData appStart) + appStart.getApplicationId() + " is written"); } catch (IOException e) { LOG.error("Error when writing start information of application " - + appStart.getApplicationId()); + + appStart.getApplicationId(), e); throw e; } } @@ -456,7 +456,7 @@ public void applicationFinished(ApplicationFinishData appFinish) + appFinish.getApplicationId() + " is written"); } catch (IOException e) { LOG.error("Error when writing finish information of application " - + appFinish.getApplicationId()); + + appFinish.getApplicationId(), e); throw e; } finally { hfWriter.close(); @@ -480,7 +480,7 @@ public void applicationAttemptStarted( + appAttemptStart.getApplicationAttemptId() + " is written"); } catch (IOException e) { LOG.error("Error when writing start information of application attempt " - + appAttemptStart.getApplicationAttemptId()); + + appAttemptStart.getApplicationAttemptId(), e); throw e; } } @@ -501,7 +501,7 @@ public void applicationAttemptFinished( + appAttemptFinish.getApplicationAttemptId() + " is written"); } catch (IOException e) { LOG.error("Error when writing finish information of application attempt " - + appAttemptFinish.getApplicationAttemptId()); + + appAttemptFinish.getApplicationAttemptId(), e); throw e; } } @@ -521,7 +521,7 @@ public void containerStarted(ContainerStartData containerStart) + containerStart.getContainerId() + " is written"); } catch (IOException e) { LOG.error("Error when writing start information of container " - + containerStart.getContainerId()); + + containerStart.getContainerId(), e); throw e; } } @@ -541,7 +541,7 @@ public void containerFinished(ContainerFinishData containerFinish) + containerFinish.getContainerId() + " is written"); } catch (IOException e) { LOG.error("Error when writing finish information of container " - + containerFinish.getContainerId()); + + containerFinish.getContainerId(), e); } } @@ -676,9 +676,10 @@ public Entry(HistoryDataKey key, byte[] value) { private TFile.Reader reader; private TFile.Reader.Scanner scanner; + FSDataInputStream fsdis; public HistoryFileReader(Path historyFile) throws IOException { - FSDataInputStream fsdis = fs.open(historyFile); + fsdis = fs.open(historyFile); reader = new TFile.Reader(fsdis, fs.getFileStatus(historyFile).getLen(), getConfig()); @@ -707,7 +708,7 @@ public void reset() throws IOException { } public void close() { - IOUtils.cleanup(LOG, scanner, reader); + IOUtils.cleanup(LOG, scanner, reader, fsdis); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java index 627b7b2dd656e..d31018c118134 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java @@ -23,6 +23,8 @@ import org.junit.Assert; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; @@ -42,6 +44,9 @@ public class TestFileSystemApplicationHistoryStore extends ApplicationHistoryStoreTestUtils { + private static Log LOG = LogFactory + .getLog(TestFileSystemApplicationHistoryStore.class.getName()); + private FileSystem fs; private Path fsWorkingPath; @@ -50,9 +55,12 @@ public void setup() throws Exception { fs = new RawLocalFileSystem(); Configuration conf = new Configuration(); fs.initialize(new URI("/"), conf); - fsWorkingPath = new Path("Test"); + fsWorkingPath = + new Path("target", + TestFileSystemApplicationHistoryStore.class.getSimpleName()); fs.delete(fsWorkingPath, true); - conf.set(YarnConfiguration.FS_APPLICATION_HISTORY_STORE_URI, fsWorkingPath.toString()); + conf.set(YarnConfiguration.FS_APPLICATION_HISTORY_STORE_URI, + fsWorkingPath.toString()); store = new FileSystemApplicationHistoryStore(); store.init(conf); store.start(); @@ -67,6 +75,7 @@ public void tearDown() throws Exception { @Test public void testReadWriteHistoryData() throws IOException { + LOG.info("Starting testReadWriteHistoryData"); testWriteHistoryData(5); testReadHistoryData(5); } @@ -167,6 +176,7 @@ private void testReadHistoryData( @Test public void testWriteAfterApplicationFinish() throws IOException { + LOG.info("Starting testWriteAfterApplicationFinish"); ApplicationId appId = ApplicationId.newInstance(0, 1); writeApplicationStartData(appId); writeApplicationFinishData(appId); @@ -203,6 +213,7 @@ public void testWriteAfterApplicationFinish() throws IOException { @Test public void testMassiveWriteContainerHistoryData() throws IOException { + LOG.info("Starting testMassiveWriteContainerHistoryData"); long mb = 1024 * 1024; long usedDiskBefore = fs.getContentSummary(fsWorkingPath).getLength() / mb; ApplicationId appId = ApplicationId.newInstance(0, 1); @@ -221,12 +232,14 @@ public void testMassiveWriteContainerHistoryData() throws IOException { @Test public void testMissingContainerHistoryData() throws IOException { + LOG.info("Starting testMissingContainerHistoryData"); testWriteHistoryData(3, true, false); testReadHistoryData(3, true, false); } @Test public void testMissingApplicationAttemptHistoryData() throws IOException { + LOG.info("Starting testMissingApplicationAttemptHistoryData"); testWriteHistoryData(3, false, true); testReadHistoryData(3, false, true); }
50fb6add9826b85691e3fc25be61dc531fcb0407
Valadoc
gtkdoc-importer: Add support for literallayout
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index 23e421bb06..bec1d065d0 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -1416,6 +1416,8 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { append_inline_content_not_null (run, parse_highlighted_template ("term", Run.Style.ITALIC)); } else if (current.type == TokenType.XML_OPEN && current.content == "literal") { append_inline_content_not_null (run, parse_highlighted_template ("literal", Run.Style.ITALIC)); + } else if (current.type == TokenType.XML_OPEN && current.content == "literallayout") { + append_inline_content_not_null (run, parse_highlighted_template ("literallayout", Run.Style.MONOSPACED)); } else if (current.type == TokenType.XML_OPEN && current.content == "application") { append_inline_content_not_null (run, parse_highlighted_template ("application", Run.Style.MONOSPACED)); } else if (current.type == TokenType.XML_OPEN && current.content == "varname") {
9e6fab3a6dcbf26e3aad60aa5cf371adbdc3b47b
elasticsearch
Added support for acknowledgements to update- cluster settings api--As a side note
a
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java index ec018f8ca3b3d..73150e802b463 100644 --- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java +++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java @@ -20,8 +20,9 @@ package org.elasticsearch.action.admin.cluster.settings; import org.elasticsearch.ElasticSearchGenerationException; +import org.elasticsearch.Version; import org.elasticsearch.action.ActionRequestValidationException; -import org.elasticsearch.action.support.master.MasterNodeOperationRequest; +import org.elasticsearch.action.support.master.AcknowledgedRequest; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.ImmutableSettings; @@ -39,8 +40,9 @@ import static org.elasticsearch.common.settings.ImmutableSettings.writeSettingsToStream; /** + * Request for an update cluster settings action */ -public class ClusterUpdateSettingsRequest extends MasterNodeOperationRequest<ClusterUpdateSettingsRequest> { +public class ClusterUpdateSettingsRequest extends AcknowledgedRequest<ClusterUpdateSettingsRequest> { private Settings transientSettings = EMPTY_SETTINGS; private Settings persistentSettings = EMPTY_SETTINGS; @@ -65,21 +67,34 @@ Settings persistentSettings() { return persistentSettings; } + /** + * Sets the transient settings to be updated. They will not survive a full cluster restart + */ public ClusterUpdateSettingsRequest transientSettings(Settings settings) { this.transientSettings = settings; return this; } + /** + * Sets the transient settings to be updated. They will not survive a full cluster restart + */ public ClusterUpdateSettingsRequest transientSettings(Settings.Builder settings) { this.transientSettings = settings.build(); return this; } + /** + * Sets the source containing the transient settings to be updated. They will not survive a full cluster restart + */ public ClusterUpdateSettingsRequest transientSettings(String source) { this.transientSettings = ImmutableSettings.settingsBuilder().loadFromSource(source).build(); return this; } + /** + * Sets the transient settings to be updated. They will not survive a full cluster restart + */ + @SuppressWarnings("unchecked") public ClusterUpdateSettingsRequest transientSettings(Map source) { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); @@ -91,21 +106,34 @@ public ClusterUpdateSettingsRequest transientSettings(Map source) { return this; } + /** + * Sets the persistent settings to be updated. They will get applied cross restarts + */ public ClusterUpdateSettingsRequest persistentSettings(Settings settings) { this.persistentSettings = settings; return this; } + /** + * Sets the persistent settings to be updated. They will get applied cross restarts + */ public ClusterUpdateSettingsRequest persistentSettings(Settings.Builder settings) { this.persistentSettings = settings.build(); return this; } + /** + * Sets the source containing the persistent settings to be updated. They will get applied cross restarts + */ public ClusterUpdateSettingsRequest persistentSettings(String source) { this.persistentSettings = ImmutableSettings.settingsBuilder().loadFromSource(source).build(); return this; } + /** + * Sets the persistent settings to be updated. They will get applied cross restarts + */ + @SuppressWarnings("unchecked") public ClusterUpdateSettingsRequest persistentSettings(Map source) { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); @@ -117,12 +145,12 @@ public ClusterUpdateSettingsRequest persistentSettings(Map source) { return this; } - @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); transientSettings = readSettingsFromStream(in); persistentSettings = readSettingsFromStream(in); + readTimeout(in, Version.V_0_90_6); } @Override @@ -130,5 +158,6 @@ public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); writeSettingsToStream(transientSettings, out); writeSettingsToStream(persistentSettings, out); + writeTimeout(out, Version.V_0_90_6); } } diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java index d7a849cc35853..991b9deae3b21 100644 --- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java +++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java @@ -20,7 +20,7 @@ package org.elasticsearch.action.admin.cluster.settings; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; +import org.elasticsearch.action.support.master.AcknowledgedRequestBuilder; import org.elasticsearch.client.ClusterAdminClient; import org.elasticsearch.client.internal.InternalClusterAdminClient; import org.elasticsearch.common.settings.Settings; @@ -28,48 +28,73 @@ import java.util.Map; /** + * Builder for a cluster update settings request */ -public class ClusterUpdateSettingsRequestBuilder extends MasterNodeOperationRequestBuilder<ClusterUpdateSettingsRequest, ClusterUpdateSettingsResponse, ClusterUpdateSettingsRequestBuilder> { +public class ClusterUpdateSettingsRequestBuilder extends AcknowledgedRequestBuilder<ClusterUpdateSettingsRequest, ClusterUpdateSettingsResponse, ClusterUpdateSettingsRequestBuilder> { public ClusterUpdateSettingsRequestBuilder(ClusterAdminClient clusterClient) { super((InternalClusterAdminClient) clusterClient, new ClusterUpdateSettingsRequest()); } + /** + * Sets the transient settings to be updated. They will not survive a full cluster restart + */ public ClusterUpdateSettingsRequestBuilder setTransientSettings(Settings settings) { request.transientSettings(settings); return this; } + /** + * Sets the transient settings to be updated. They will not survive a full cluster restart + */ public ClusterUpdateSettingsRequestBuilder setTransientSettings(Settings.Builder settings) { request.transientSettings(settings); return this; } + /** + * Sets the source containing the transient settings to be updated. They will not survive a full cluster restart + */ public ClusterUpdateSettingsRequestBuilder setTransientSettings(String settings) { request.transientSettings(settings); return this; } + /** + * Sets the transient settings to be updated. They will not survive a full cluster restart + */ public ClusterUpdateSettingsRequestBuilder setTransientSettings(Map settings) { request.transientSettings(settings); return this; } + /** + * Sets the persistent settings to be updated. They will get applied cross restarts + */ public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Settings settings) { request.persistentSettings(settings); return this; } + /** + * Sets the persistent settings to be updated. They will get applied cross restarts + */ public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Settings.Builder settings) { request.persistentSettings(settings); return this; } + /** + * Sets the source containing the persistent settings to be updated. They will get applied cross restarts + */ public ClusterUpdateSettingsRequestBuilder setPersistentSettings(String settings) { request.persistentSettings(settings); return this; } + /** + * Sets the persistent settings to be updated. They will get applied cross restarts + */ public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Map settings) { request.persistentSettings(settings); return this; diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java index 96598394bc061..0b7ed0a5f76ab 100644 --- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java +++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java @@ -19,18 +19,19 @@ package org.elasticsearch.action.admin.cluster.settings; -import java.io.IOException; - -import org.elasticsearch.action.ActionResponse; +import org.elasticsearch.Version; +import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; +import java.io.IOException; + /** * A response for a cluster update settings action. */ -public class ClusterUpdateSettingsResponse extends ActionResponse { +public class ClusterUpdateSettingsResponse extends AcknowledgedResponse { Settings transientSettings; Settings persistentSettings; @@ -40,7 +41,8 @@ public class ClusterUpdateSettingsResponse extends ActionResponse { this.transientSettings = ImmutableSettings.EMPTY; } - ClusterUpdateSettingsResponse(Settings transientSettings, Settings persistentSettings) { + ClusterUpdateSettingsResponse(boolean acknowledged, Settings transientSettings, Settings persistentSettings) { + super(acknowledged); this.persistentSettings = persistentSettings; this.transientSettings = transientSettings; } @@ -50,6 +52,7 @@ public void readFrom(StreamInput in) throws IOException { super.readFrom(in); transientSettings = ImmutableSettings.readSettingsFromStream(in); persistentSettings = ImmutableSettings.readSettingsFromStream(in); + readAcknowledged(in, Version.V_0_90_6); } public Settings getTransientSettings() { @@ -65,5 +68,6 @@ public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); ImmutableSettings.writeSettingsToStream(transientSettings, out); ImmutableSettings.writeSettingsToStream(persistentSettings, out); + writeAcknowledged(out, Version.V_0_90_6); } } diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java index 4dd19c9d90ed4..c320636b8a24e 100644 --- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java +++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java @@ -22,16 +22,17 @@ import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction; +import org.elasticsearch.cluster.AckedClusterStateUpdateTask; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.ClusterStateUpdateTask; -import org.elasticsearch.cluster.TimeoutClusterStateUpdateTask; import org.elasticsearch.cluster.block.ClusterBlocks; import org.elasticsearch.cluster.metadata.MetaData; +import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.routing.allocation.AllocationService; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.cluster.settings.ClusterDynamicSettings; import org.elasticsearch.cluster.settings.DynamicSettings; +import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Priority; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.ImmutableSettings; @@ -42,6 +43,7 @@ import java.util.Map; +import static org.elasticsearch.cluster.ClusterState.builder; import static org.elasticsearch.cluster.ClusterState.newClusterStateBuilder; /** @@ -86,7 +88,91 @@ protected void masterOperation(final ClusterUpdateSettingsRequest request, final final ImmutableSettings.Builder transientUpdates = ImmutableSettings.settingsBuilder(); final ImmutableSettings.Builder persistentUpdates = ImmutableSettings.settingsBuilder(); - clusterService.submitStateUpdateTask("cluster_update_settings", Priority.URGENT, new TimeoutClusterStateUpdateTask() { + clusterService.submitStateUpdateTask("cluster_update_settings", Priority.URGENT, new AckedClusterStateUpdateTask() { + + private volatile boolean changed = false; + + @Override + public boolean mustAck(DiscoveryNode discoveryNode) { + return true; + } + + @Override + public void onAllNodesAcked(@Nullable Throwable t) { + if (changed) { + reroute(true); + } else { + listener.onResponse(new ClusterUpdateSettingsResponse(true, transientUpdates.build(), persistentUpdates.build())); + } + + } + + @Override + public void onAckTimeout() { + if (changed) { + reroute(false); + } else { + listener.onResponse(new ClusterUpdateSettingsResponse(false, transientUpdates.build(), persistentUpdates.build())); + } + } + + private void reroute(final boolean updateSettingsAcked) { + clusterService.submitStateUpdateTask("reroute_after_cluster_update_settings", Priority.URGENT, new AckedClusterStateUpdateTask() { + + @Override + public boolean mustAck(DiscoveryNode discoveryNode) { + //we wait for the reroute ack only if the update settings was acknowledged + return updateSettingsAcked; + } + + @Override + public void onAllNodesAcked(@Nullable Throwable t) { + //we return when the cluster reroute is acked (the acknowledged flag depends on whether the update settings was acknowledged) + listener.onResponse(new ClusterUpdateSettingsResponse(updateSettingsAcked, transientUpdates.build(), persistentUpdates.build())); + } + + @Override + public void onAckTimeout() { + //we return when the cluster reroute ack times out (acknowledged false) + listener.onResponse(new ClusterUpdateSettingsResponse(false, transientUpdates.build(), persistentUpdates.build())); + } + + @Override + public TimeValue ackTimeout() { + return request.timeout(); + } + + @Override + public TimeValue timeout() { + return request.masterNodeTimeout(); + } + + @Override + public void onFailure(String source, Throwable t) { + //if the reroute fails we only log + logger.debug("failed to perform [{}]", t, source); + } + + @Override + public ClusterState execute(final ClusterState currentState) { + // now, reroute in case things that require it changed (e.g. number of replicas) + RoutingAllocation.Result routingResult = allocationService.reroute(currentState); + if (!routingResult.changed()) { + return currentState; + } + return newClusterStateBuilder().state(currentState).routingResult(routingResult).build(); + } + + @Override + public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { + } + }); + } + + @Override + public TimeValue ackTimeout() { + return request.timeout(); + } @Override public TimeValue timeout() { @@ -101,7 +187,6 @@ public void onFailure(String source, Throwable t) { @Override public ClusterState execute(final ClusterState currentState) { - boolean changed = false; ImmutableSettings.Builder transientSettings = ImmutableSettings.settingsBuilder(); transientSettings.put(currentState.metaData().transientSettings()); for (Map.Entry<String, String> entry : request.transientSettings().getAsMap().entrySet()) { @@ -152,38 +237,12 @@ public ClusterState execute(final ClusterState currentState) { blocks.removeGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK); } - return ClusterState.builder().state(currentState).metaData(metaData).blocks(blocks).build(); + return builder().state(currentState).metaData(metaData).blocks(blocks).build(); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { - if (oldState == newState) { - // nothing changed... - listener.onResponse(new ClusterUpdateSettingsResponse(transientUpdates.build(), persistentUpdates.build())); - return; - } - // now, reroute - clusterService.submitStateUpdateTask("reroute_after_cluster_update_settings", Priority.URGENT, new ClusterStateUpdateTask() { - @Override - public ClusterState execute(final ClusterState currentState) { - try { - // now, reroute in case things change that require it (like number of replicas) - RoutingAllocation.Result routingResult = allocationService.reroute(currentState); - if (!routingResult.changed()) { - return currentState; - } - return newClusterStateBuilder().state(currentState).routingResult(routingResult).build(); - } finally { - listener.onResponse(new ClusterUpdateSettingsResponse(transientUpdates.build(), persistentUpdates.build())); - } - } - @Override - public void onFailure(String source, Throwable t) { - logger.warn("unexpected failure during [{}]", t, source); - listener.onResponse(new ClusterUpdateSettingsResponse(transientUpdates.build(), persistentUpdates.build())); - } - }); } }); } diff --git a/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java b/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java index 6e62adae2de81..9be3a61be50e4 100644 --- a/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java +++ b/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java @@ -19,7 +19,6 @@ package org.elasticsearch.rest.action.admin.cluster.settings; -import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest; import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse; import org.elasticsearch.client.Client; @@ -29,7 +28,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.rest.*; -import org.elasticsearch.rest.action.support.RestXContentBuilder; import java.io.IOException; import java.util.Map; @@ -48,6 +46,7 @@ public RestClusterUpdateSettingsAction(Settings settings, Client client, RestCon public void handleRequest(final RestRequest request, final RestChannel channel) { final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = Requests.clusterUpdateSettingsRequest(); clusterUpdateSettingsRequest.listenerThreaded(false); + clusterUpdateSettingsRequest.timeout(request.paramAsTime("timeout", clusterUpdateSettingsRequest.timeout())); clusterUpdateSettingsRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterUpdateSettingsRequest.masterNodeTimeout())); try { Map<String, Object> source = XContentFactory.xContent(request.content()).createParser(request.content()).mapAndClose(); @@ -66,31 +65,21 @@ public void handleRequest(final RestRequest request, final RestChannel channel) return; } - client.admin().cluster().updateSettings(clusterUpdateSettingsRequest, new ActionListener<ClusterUpdateSettingsResponse>() { - @Override - public void onResponse(ClusterUpdateSettingsResponse response) { - try { - XContentBuilder builder = RestXContentBuilder.restContentBuilder(request); - builder.startObject(); - - builder.startObject("persistent"); - for (Map.Entry<String, String> entry : response.getPersistentSettings().getAsMap().entrySet()) { - builder.field(entry.getKey(), entry.getValue()); - } - builder.endObject(); - - builder.startObject("transient"); - for (Map.Entry<String, String> entry : response.getTransientSettings().getAsMap().entrySet()) { - builder.field(entry.getKey(), entry.getValue()); - } - builder.endObject(); + client.admin().cluster().updateSettings(clusterUpdateSettingsRequest, new AcknowledgedRestResponseActionListener<ClusterUpdateSettingsResponse>(request, channel, logger) { - builder.endObject(); + @Override + protected void addCustomFields(XContentBuilder builder, ClusterUpdateSettingsResponse response) throws IOException { + builder.startObject("persistent"); + for (Map.Entry<String, String> entry : response.getPersistentSettings().getAsMap().entrySet()) { + builder.field(entry.getKey(), entry.getValue()); + } + builder.endObject(); - channel.sendResponse(new XContentRestResponse(request, RestStatus.OK, builder)); - } catch (Throwable e) { - onFailure(e); + builder.startObject("transient"); + for (Map.Entry<String, String> entry : response.getTransientSettings().getAsMap().entrySet()) { + builder.field(entry.getKey(), entry.getValue()); } + builder.endObject(); } @Override @@ -98,11 +87,7 @@ public void onFailure(Throwable e) { if (logger.isDebugEnabled()) { logger.debug("failed to handle cluster state", e); } - try { - channel.sendResponse(new XContentThrowableRestResponse(request, e)); - } catch (IOException e1) { - logger.error("Failed to send failure response", e1); - } + super.onFailure(e); } }); } diff --git a/src/test/java/org/elasticsearch/cluster/ack/AckTests.java b/src/test/java/org/elasticsearch/cluster/ack/AckTests.java index b2dc9332e9736..b4e36b3b23e8f 100644 --- a/src/test/java/org/elasticsearch/cluster/ack/AckTests.java +++ b/src/test/java/org/elasticsearch/cluster/ack/AckTests.java @@ -33,10 +33,7 @@ import org.elasticsearch.action.admin.indices.warmer.put.PutWarmerResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.routing.IndexRoutingTable; -import org.elasticsearch.cluster.routing.MutableShardRouting; -import org.elasticsearch.cluster.routing.RoutingNode; -import org.elasticsearch.cluster.routing.ShardRoutingState; +import org.elasticsearch.cluster.routing.*; import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; @@ -238,4 +235,49 @@ private static MoveAllocationCommand getAllocationCommand() { return new MoveAllocationCommand(shardToBeMoved.shardId(), fromNodeId, toNodeId); } + + @Test + public void testClusterUpdateSettingsAcknowledgement() { + client().admin().indices().prepareCreate("test") + .setSettings(settingsBuilder() + .put("number_of_shards", atLeast(cluster().numNodes())) + .put("number_of_replicas", 0)).get(); + ensureGreen(); + + NodesInfoResponse nodesInfo = client().admin().cluster().prepareNodesInfo().get(); + String excludedNodeId = null; + for (NodeInfo nodeInfo : nodesInfo) { + if (nodeInfo.getNode().isDataNode()) { + excludedNodeId = nodesInfo.getAt(0).getNode().id(); + break; + } + } + assert excludedNodeId != null; + + ClusterUpdateSettingsResponse clusterUpdateSettingsResponse = client().admin().cluster().prepareUpdateSettings() + .setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", excludedNodeId)).get(); + assertThat(clusterUpdateSettingsResponse.isAcknowledged(), equalTo(true)); + assertThat(clusterUpdateSettingsResponse.getTransientSettings().get("cluster.routing.allocation.exclude._id"), equalTo(excludedNodeId)); + + for (Client client : clients()) { + ClusterState clusterState = client.admin().cluster().prepareState().setLocal(true).get().getState(); + assertThat(clusterState.routingNodes().metaData().transientSettings().get("cluster.routing.allocation.exclude._id"), equalTo(excludedNodeId)); + for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) { + for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) { + for (ShardRouting shardRouting : indexShardRoutingTable) { + if (clusterState.nodes().get(shardRouting.currentNodeId()).id().equals(excludedNodeId)) { + //if the shard is still there it must be relocating and all nodes need to know, since the request was acknowledged + assertThat(shardRouting.relocating(), equalTo(true)); + } + } + } + } + } + + //let's wait for the relocation to be completed, otherwise there can be issues with after test checks (mock directory wrapper etc.) + waitForRelocation(); + + //removes the allocation exclude settings + client().admin().cluster().prepareUpdateSettings().setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", "")).get(); + } } diff --git a/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java b/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java index 23f92eaafa149..e1f4fdfaaec8f 100644 --- a/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java +++ b/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java @@ -204,9 +204,7 @@ public void testAwarenessZonesIncrementalNodes() throws InterruptedException { assertThat(counts.get(B_1), equalTo(2)); assertThat(counts.containsKey(noZoneNode), equalTo(false)); client().admin().cluster().prepareUpdateSettings().setTransientSettings(ImmutableSettings.settingsBuilder().put("cluster.routing.allocation.awareness.attributes", "").build()).get(); - - - client().admin().cluster().prepareReroute().get(); + health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("4").setWaitForActiveShards(10).setWaitForRelocatingShards(0).execute().actionGet(); assertThat(health.isTimedOut(), equalTo(false)); diff --git a/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java b/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java index 4a03798c27dd0..9bbea5b043b3d 100644 --- a/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java +++ b/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java @@ -35,8 +35,6 @@ import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.hamcrest.Matchers.equalTo; -/** - */ @ClusterScope(scope=Scope.TEST, numNodes=0) public class FilteringAllocationTests extends AbstractIntegrationTest { @@ -65,9 +63,7 @@ public void testDecommissionNodeNoReplicas() throws Exception { client().admin().cluster().prepareUpdateSettings() .setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._name", node_1)) .execute().actionGet(); - - client().admin().cluster().prepareReroute().get(); - ensureGreen(); + waitForRelocation(); logger.info("--> verify all are allocated on node1 now"); ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState(); @@ -140,7 +136,6 @@ public void testDisablingAllocationFiltering() throws Exception { client().admin().indices().prepareUpdateSettings("test") .setSettings(settingsBuilder().put("index.routing.allocation.exclude._name", "")) .execute().actionGet(); - client().admin().cluster().prepareReroute().get(); ensureGreen();
ac32fa187cf37e5a51fd579e052105662ab3c411
hadoop
YARN-3457. NPE when NodeManager.serviceInit fails- and stopRecoveryStore called. Contributed by Bibin A Chundatt.--(cherry picked from commit dd852f5b8c8fe9e52d15987605f36b5b60f02701)-
c
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index a4673bdc2dc5d..d9e1754c8ef23 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -105,6 +105,9 @@ Release 2.8.0 - UNRELEASED YARN-3110. Few issues in ApplicationHistory web ui. (Naganarasimha G R via xgong) + YARN-3457. NPE when NodeManager.serviceInit fails and stopRecoveryStore called. + (Bibin A Chundatt via ozawa) + Release 2.7.0 - UNRELEASED INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java index 5727f102d4bdf..d54180a3627b5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java @@ -176,16 +176,18 @@ private void initAndStartRecoveryStore(Configuration conf) private void stopRecoveryStore() throws IOException { nmStore.stop(); - if (context.getDecommissioned() && nmStore.canRecover()) { - LOG.info("Removing state store due to decommission"); - Configuration conf = getConfig(); - Path recoveryRoot = new Path( - conf.get(YarnConfiguration.NM_RECOVERY_DIR)); - LOG.info("Removing state store at " + recoveryRoot - + " due to decommission"); - FileSystem recoveryFs = FileSystem.getLocal(conf); - if (!recoveryFs.delete(recoveryRoot, true)) { - LOG.warn("Unable to delete " + recoveryRoot); + if (null != context) { + if (context.getDecommissioned() && nmStore.canRecover()) { + LOG.info("Removing state store due to decommission"); + Configuration conf = getConfig(); + Path recoveryRoot = + new Path(conf.get(YarnConfiguration.NM_RECOVERY_DIR)); + LOG.info("Removing state store at " + recoveryRoot + + " due to decommission"); + FileSystem recoveryFs = FileSystem.getLocal(conf); + if (!recoveryFs.delete(recoveryRoot, true)) { + LOG.warn("Unable to delete " + recoveryRoot); + } } } }
e6d707a5fdfb1d928c335ad499f72e5128928e27
restlet-framework-java
Fixed internal client connector.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java index 2dff59b097..c27d81cd3d 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java @@ -201,7 +201,6 @@ protected void readMessage() throws IOException { getOutboundMessages().poll(); // Allows the connection to write another request setOutboundBusy(false); - setInboundBusy(false); } // Add it to the helper queue diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/ControllerTask.java b/modules/org.restlet/src/org/restlet/engine/http/connector/ControllerTask.java index e0f18ab829..a9dff18e63 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/ControllerTask.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/ControllerTask.java @@ -69,7 +69,7 @@ protected void controlConnections() throws IOException { for (final Connection<?> conn : getHelper().getConnections()) { if (conn.getState() == ConnectionState.CLOSED) { getHelper().getConnections().remove(conn); - } else if ((conn.getState() == ConnectionState.CLOSING)) { + } else if ((conn.getState() == ConnectionState.CLOSING) && !conn.isBusy()) { conn.close(true); } else { if ((isOverloaded() && !getHelper().isClientSide())
48d33ec70a8ea6f872006e46d1c8e0cdd48a2c81
elasticsearch
Cluster Health API: Add `wait_for_nodes` (accepts- "N"
a
https://github.com/elastic/elasticsearch
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthRequest.java index b137902474add..8dd124ece5bf1 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthRequest.java @@ -46,6 +46,8 @@ public class ClusterHealthRequest extends MasterNodeOperationRequest { private int waitForActiveShards = -1; + private String waitForNodes = ""; + ClusterHealthRequest() { } @@ -110,6 +112,18 @@ public ClusterHealthRequest waitForActiveShards(int waitForActiveShards) { return this; } + public String waitForNodes() { + return waitForNodes; + } + + /** + * Waits for N number of nodes. Use "12" for exact mapping, ">12" and "<12" for range. + */ + public ClusterHealthRequest waitForNodes(String waitForNodes) { + this.waitForNodes = waitForNodes; + return this; + } + @Override public ActionRequestValidationException validate() { return null; } @@ -131,6 +145,7 @@ public ClusterHealthRequest waitForActiveShards(int waitForActiveShards) { } waitForRelocatingShards = in.readInt(); waitForActiveShards = in.readInt(); + waitForNodes = in.readUTF(); } @Override public void writeTo(StreamOutput out) throws IOException { @@ -152,5 +167,6 @@ public ClusterHealthRequest waitForActiveShards(int waitForActiveShards) { } out.writeInt(waitForRelocatingShards); out.writeInt(waitForActiveShards); + out.writeUTF(waitForNodes); } } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponse.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponse.java index 878da47de34dd..199f5c7dd1cbd 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponse.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponse.java @@ -40,6 +40,8 @@ public class ClusterHealthResponse implements ActionResponse, Iterable<ClusterIn private String clusterName; + int numberOfNodes = 0; + int activeShards = 0; int relocatingShards = 0; @@ -127,6 +129,14 @@ public int getActivePrimaryShards() { return activePrimaryShards(); } + public int numberOfNodes() { + return this.numberOfNodes; + } + + public int getNumberOfNodes() { + return numberOfNodes(); + } + /** * <tt>true</tt> if the waitForXXX has timeout out and did not match. */ @@ -163,6 +173,7 @@ public Map<String, ClusterIndexHealth> getIndices() { activePrimaryShards = in.readVInt(); activeShards = in.readVInt(); relocatingShards = in.readVInt(); + numberOfNodes = in.readVInt(); status = ClusterHealthStatus.fromValue(in.readByte()); int size = in.readVInt(); for (int i = 0; i < size; i++) { @@ -185,6 +196,7 @@ public Map<String, ClusterIndexHealth> getIndices() { out.writeVInt(activePrimaryShards); out.writeVInt(activeShards); out.writeVInt(relocatingShards); + out.writeVInt(numberOfNodes); out.writeByte(status.value()); out.writeVInt(indices.size()); for (ClusterIndexHealth indexHealth : this) { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java index fe8806ac6b364..c5cd20ea1f831 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java @@ -65,7 +65,7 @@ public class TransportClusterHealthAction extends TransportMasterNodeOperationAc } @Override protected ClusterHealthResponse masterOperation(ClusterHealthRequest request, ClusterState state) throws ElasticSearchException { - int waitFor = 3; + int waitFor = 4; if (request.waitForStatus() == null) { waitFor--; } @@ -75,6 +75,9 @@ public class TransportClusterHealthAction extends TransportMasterNodeOperationAc if (request.waitForActiveShards() == -1) { waitFor--; } + if (request.waitForNodes().isEmpty()) { + waitFor--; + } if (waitFor == 0) { // no need to wait for anything return clusterHealth(request); @@ -92,6 +95,34 @@ public class TransportClusterHealthAction extends TransportMasterNodeOperationAc if (request.waitForActiveShards() != -1 && response.activeShards() >= request.waitForActiveShards()) { waitForCounter++; } + if (!request.waitForNodes().isEmpty()) { + if (request.waitForNodes().startsWith(">=")) { + int expected = Integer.parseInt(request.waitForNodes().substring(2)); + if (response.numberOfNodes() >= expected) { + waitForCounter++; + } + } else if (request.waitForNodes().startsWith("M=")) { + int expected = Integer.parseInt(request.waitForNodes().substring(2)); + if (response.numberOfNodes() <= expected) { + waitForCounter++; + } + } else if (request.waitForNodes().startsWith(">")) { + int expected = Integer.parseInt(request.waitForNodes().substring(1)); + if (response.numberOfNodes() > expected) { + waitForCounter++; + } + } else if (request.waitForNodes().startsWith("<")) { + int expected = Integer.parseInt(request.waitForNodes().substring(1)); + if (response.numberOfNodes() < expected) { + waitForCounter++; + } + } else { + int expected = Integer.parseInt(request.waitForNodes()); + if (response.numberOfNodes() == expected) { + waitForCounter++; + } + } + } if (waitForCounter == waitFor) { return response; } @@ -113,7 +144,7 @@ private ClusterHealthResponse clusterHealth(ClusterHealthRequest request) { ClusterState clusterState = clusterService.state(); RoutingTableValidation validation = clusterState.routingTable().validate(clusterState.metaData()); ClusterHealthResponse response = new ClusterHealthResponse(clusterName.value(), validation.failures()); - + response.numberOfNodes = clusterState.nodes().size(); request.indices(clusterState.metaData().concreteIndices(request.indices())); for (String index : request.indices()) { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/action/admin/cluster/health/ClusterHealthRequestBuilder.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/action/admin/cluster/health/ClusterHealthRequestBuilder.java index 7961c3ba7f403..1a40edbee03a0 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/action/admin/cluster/health/ClusterHealthRequestBuilder.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/action/admin/cluster/health/ClusterHealthRequestBuilder.java @@ -84,6 +84,14 @@ public ClusterHealthRequestBuilder setWaitForActiveShards(int waitForActiveShard return this; } + /** + * Waits for N number of nodes. Use "12" for exact mapping, ">12" and "<12" for range. + */ + public ClusterHealthRequestBuilder setWaitForNodes(String waitForNodes) { + request.waitForNodes(waitForNodes); + return this; + } + @Override protected void doExecute(ActionListener<ClusterHealthResponse> listener) { client.health(request, listener); } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java index d50018e477d37..9caa0058b346b 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java @@ -276,6 +276,9 @@ public class RobinEngine extends AbstractIndexShardComponent implements Engine, // we obtain a read lock here, since we don't want a flush to happen while we are refreshing // since it flushes the index as well (though, in terms of concurrency, we are allowed to do it) rwl.readLock().lock(); + if (indexWriter == null) { + throw new EngineClosedException(shardId); + } try { // this engine always acts as if waitForOperations=true if (refreshMutex.compareAndSet(false, true)) { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java index 348a215578ed1..54f136a12e6d4 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java @@ -36,10 +36,7 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadSafe; import org.elasticsearch.index.cache.IndexCache; -import org.elasticsearch.index.engine.Engine; -import org.elasticsearch.index.engine.EngineException; -import org.elasticsearch.index.engine.RefreshFailedEngineException; -import org.elasticsearch.index.engine.ScheduledRefreshableEngine; +import org.elasticsearch.index.engine.*; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.DocumentMapperNotFoundException; import org.elasticsearch.index.mapper.MapperService; @@ -517,6 +514,8 @@ private class EngineRefresher implements Runnable { @Override public void run() { try { engine.refresh(new Engine.Refresh(false)); + } catch (EngineClosedException e) { + // we are being closed, ignore } catch (RefreshFailedEngineException e) { if (e.getCause() instanceof InterruptedException) { // ignore, we are being shutdown diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java index 037ff0c32e205..1a8e477257011 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java @@ -57,6 +57,7 @@ public class RestClusterHealthAction extends BaseRestHandler { } clusterHealthRequest.waitForRelocatingShards(request.paramAsInt("wait_for_relocating_shards", clusterHealthRequest.waitForRelocatingShards())); clusterHealthRequest.waitForActiveShards(request.paramAsInt("wait_for_active_shards", clusterHealthRequest.waitForActiveShards())); + clusterHealthRequest.waitForNodes(request.param("wait_for_nodes", clusterHealthRequest.waitForNodes())); String sLevel = request.param("level"); if (sLevel != null) { if ("cluster".equals("sLevel")) { @@ -85,6 +86,7 @@ public class RestClusterHealthAction extends BaseRestHandler { builder.field("status", response.status().name().toLowerCase()); builder.field("timed_out", response.timedOut()); + builder.field("number_of_nodes", response.numberOfNodes()); builder.field("active_primary_shards", response.activePrimaryShards()); builder.field("active_shards", response.activeShards()); builder.field("relocating_shards", response.relocatingShards()); diff --git a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/datanode/SimpleDataNodesTests.java b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/datanode/SimpleDataNodesTests.java index 967180e807fd7..908406a84a90f 100644 --- a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/datanode/SimpleDataNodesTests.java +++ b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/datanode/SimpleDataNodesTests.java @@ -52,7 +52,7 @@ public class SimpleDataNodesTests extends AbstractNodesTests { } startNode("nonData2", settingsBuilder().put("node.data", false).build()); - Thread.sleep(500); + assertThat(client("nonData1").admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet().timedOut(), equalTo(false)); // still no shard should be allocated try { @@ -64,7 +64,7 @@ public class SimpleDataNodesTests extends AbstractNodesTests { // now, start a node data, and see that it gets with shards startNode("data1", settingsBuilder().put("node.data", true).build()); - Thread.sleep(500); + assertThat(client("nonData1").admin().cluster().prepareHealth().setWaitForNodes("3").execute().actionGet().timedOut(), equalTo(false)); IndexResponse indexResponse = client("nonData2").index(Requests.indexRequest("test").type("type1").id("1").source(source("1", "test"))).actionGet(); assertThat(indexResponse.id(), equalTo("1")); diff --git a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/indexlifecycle/IndexLifecycleActionTests.java b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/indexlifecycle/IndexLifecycleActionTests.java index 5cc344d2d79cb..76b80ae7e68c8 100644 --- a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/indexlifecycle/IndexLifecycleActionTests.java +++ b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/indexlifecycle/IndexLifecycleActionTests.java @@ -89,12 +89,10 @@ public class IndexLifecycleActionTests extends AbstractNodesTests { logger.info("Starting server2"); // start another server startNode("server2", settings); - Thread.sleep(200); - ClusterService clusterService2 = ((InternalNode) node("server2")).injector().getInstance(ClusterService.class); logger.info("Running Cluster Health"); - clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus()).actionGet(); + clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); @@ -113,12 +111,11 @@ public class IndexLifecycleActionTests extends AbstractNodesTests { logger.info("Starting server3"); // start another server startNode("server3", settings); - Thread.sleep(200); ClusterService clusterService3 = ((InternalNode) node("server3")).injector().getInstance(ClusterService.class); logger.info("Running Cluster Health"); - clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0)).actionGet(); + clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForNodes("3").waitForRelocatingShards(0)).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); @@ -146,11 +143,9 @@ public class IndexLifecycleActionTests extends AbstractNodesTests { logger.info("Closing server1"); // kill the first server closeNode("server1"); - // wait a bit so it will be discovered as removed - Thread.sleep(200); // verify health logger.info("Running Cluster Health"); - clusterHealth = client("server2").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0)).actionGet(); + clusterHealth = client("server2").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); @@ -219,11 +214,9 @@ public class IndexLifecycleActionTests extends AbstractNodesTests { // start another server logger.info("Starting server2"); startNode("server2", settings); - // wait a bit - Thread.sleep(200); logger.info("Running Cluster Health"); - clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0)).actionGet(); + clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); @@ -247,13 +240,11 @@ public class IndexLifecycleActionTests extends AbstractNodesTests { // start another server logger.info("Starting server3"); startNode("server3"); - // wait a bit so assignment will start - Thread.sleep(200); ClusterService clusterService3 = ((InternalNode) node("server3")).injector().getInstance(ClusterService.class); logger.info("Running Cluster Health"); - clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0)).actionGet(); + clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("3")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); @@ -281,11 +272,9 @@ public class IndexLifecycleActionTests extends AbstractNodesTests { logger.info("Closing server1"); // kill the first server closeNode("server1"); - // wait a bit so it will be discovered as removed - Thread.sleep(200); logger.info("Running Cluster Health"); - clusterHealth = client("server3").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForRelocatingShards(0)).actionGet(); + clusterHealth = client("server3").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForNodes("2").waitForRelocatingShards(0)).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); diff --git a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/FullRollingRestartTests.java b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/FullRollingRestartTests.java index 6c167df304260..f9e73d0152bf5 100644 --- a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/FullRollingRestartTests.java +++ b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/FullRollingRestartTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.test.integration.recovery; -import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.test.integration.AbstractNodesTests; import org.testng.annotations.AfterMethod; @@ -57,14 +56,14 @@ public class FullRollingRestartTests extends AbstractNodesTests { startNode("node3"); // make sure the cluster state is green, and all has been recovered - assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("3").execute().actionGet().timedOut(), equalTo(false)); // now start adding nodes startNode("node4"); startNode("node5"); // make sure the cluster state is green, and all has been recovered - assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("5").execute().actionGet().timedOut(), equalTo(false)); client("node1").admin().indices().prepareRefresh().execute().actionGet(); for (int i = 0; i < 10; i++) { @@ -74,10 +73,10 @@ public class FullRollingRestartTests extends AbstractNodesTests { // now start shutting nodes down closeNode("node1"); // make sure the cluster state is green, and all has been recovered - assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("4").execute().actionGet().timedOut(), equalTo(false)); closeNode("node2"); // make sure the cluster state is green, and all has been recovered - assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("3").execute().actionGet().timedOut(), equalTo(false)); client("node5").admin().indices().prepareRefresh().execute().actionGet(); @@ -87,11 +86,11 @@ public class FullRollingRestartTests extends AbstractNodesTests { closeNode("node3"); // make sure the cluster state is green, and all has been recovered - assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("2").execute().actionGet().timedOut(), equalTo(false)); closeNode("node4"); // make sure the cluster state is green, and all has been recovered - assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForYellowStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.YELLOW)); + assertThat(client("node5").admin().cluster().prepareHealth().setTimeout("1m").setWaitForYellowStatus().setWaitForNodes("1").execute().actionGet().timedOut(), equalTo(false)); client("node5").admin().indices().prepareRefresh().execute().actionGet(); for (int i = 0; i < 10; i++) { diff --git a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/RecoveryWhileUnderLoadTests.java b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/RecoveryWhileUnderLoadTests.java index d3b109fcf11a9..d4466da4f77da 100644 --- a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/RecoveryWhileUnderLoadTests.java +++ b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/RecoveryWhileUnderLoadTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.test.integration.recovery; -import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; @@ -104,7 +103,7 @@ public class RecoveryWhileUnderLoadTests extends AbstractNodesTests { logger.info("--> waiting for GREEN health status ..."); // make sure the cluster state is green, and all has been recovered - assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("2").execute().actionGet().timedOut(), equalTo(false)); logger.info("--> waiting for 100000 docs to be indexed ..."); while (client("node1").prepareCount().setQuery(matchAllQuery()).execute().actionGet().count() < 100000) { @@ -185,7 +184,7 @@ public class RecoveryWhileUnderLoadTests extends AbstractNodesTests { startNode("node4"); logger.info("--> waiting for GREEN health status ..."); - assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("4").execute().actionGet().timedOut(), equalTo(false)); logger.info("--> waiting for 150000 docs to be indexed ..."); @@ -271,7 +270,7 @@ public class RecoveryWhileUnderLoadTests extends AbstractNodesTests { startNode("node4"); logger.info("--> waiting for GREEN health status ..."); - assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node1").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("4").execute().actionGet().timedOut(), equalTo(false)); logger.info("--> waiting for 100000 docs to be indexed ..."); @@ -285,24 +284,24 @@ public class RecoveryWhileUnderLoadTests extends AbstractNodesTests { logger.info("--> shutting down [node1] ..."); closeNode("node1"); logger.info("--> waiting for GREEN health status ..."); - assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("3").execute().actionGet().timedOut(), equalTo(false)); logger.info("--> shutting down [node3] ..."); closeNode("node3"); logger.info("--> waiting for GREEN health status ..."); - assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.GREEN)); + assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForGreenStatus().setWaitForNodes("2").execute().actionGet().timedOut(), equalTo(false)); logger.info("--> shutting down [node4] ..."); closeNode("node4"); logger.info("--> waiting for YELLOW health status ..."); - assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForYellowStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.YELLOW)); + assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForYellowStatus().setWaitForNodes("1").execute().actionGet().timedOut(), equalTo(false)); logger.info("--> marking and waiting for indexing threads to stop ..."); stop.set(true); stopLatch.await(); logger.info("--> indexing threads stopped"); - assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForYellowStatus().execute().actionGet().status(), equalTo(ClusterHealthStatus.YELLOW)); + assertThat(client("node2").admin().cluster().prepareHealth().setTimeout("1m").setWaitForYellowStatus().setWaitForNodes("1").execute().actionGet().timedOut(), equalTo(false)); logger.info("--> refreshing the index"); client("node2").admin().indices().prepareRefresh().execute().actionGet(); diff --git a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/SimpleRecoveryTests.java b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/SimpleRecoveryTests.java index a60be29d7bcdc..948f9f0a6c064 100644 --- a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/SimpleRecoveryTests.java +++ b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/recovery/SimpleRecoveryTests.java @@ -86,9 +86,8 @@ public class SimpleRecoveryTests extends AbstractNodesTests { // now start another one so we move some primaries startNode("server3"); - Thread.sleep(1000); logger.info("Running Cluster Health"); - clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus()).actionGet(); + clusterHealth = client("server1").admin().cluster().health(clusterHealth().waitForGreenStatus().waitForNodes("3")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); diff --git a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/search/TransportSearchFailuresTests.java b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/search/TransportSearchFailuresTests.java index 6487c12eaed41..74837b72d5fb9 100644 --- a/modules/test/integration/src/test/java/org/elasticsearch/test/integration/search/TransportSearchFailuresTests.java +++ b/modules/test/integration/src/test/java/org/elasticsearch/test/integration/search/TransportSearchFailuresTests.java @@ -75,7 +75,7 @@ public class TransportSearchFailuresTests extends AbstractNodesTests { } startNode("server2"); - Thread.sleep(500); + assertThat(client("server1").admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet().timedOut(), equalTo(false)); logger.info("Running Cluster Health"); ClusterHealthResponse clusterHealth = client("server1").admin().cluster().health(clusterHealth("test")
e23873e4201e5e64884df41c1eb9dfb5b08af103
Mylyn Reviews
339480 Set execution environment to java 1.5
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/.classpath b/tbr/org.eclipse.mylyn.reviews.tasks.core/.classpath index 121e527a..64c5e31b 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/.classpath +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/.classpath @@ -1,7 +1,7 @@ <?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.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/> <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src"/> <classpathentry kind="output" path="bin"/> </classpath> diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF index 5a07632b..2612cf12 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF @@ -12,6 +12,6 @@ Require-Bundle: org.eclipse.core.resources;bundle-version="3.5.0", org.eclipse.mylyn.tasks.core, org.eclipse.mylyn.reviews.tasks.dsl;bundle-version="0.8.0", org.eclipse.mylyn.versions.core;bundle-version="0.1.0" -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-RequiredExecutionEnvironment: J2SE-1.5 Export-Package: org.eclipse.mylyn.reviews.tasks.core;x-friends:="org.eclipse.mylyn.tasks.ui", org.eclipse.mylyn.reviews.tasks.core.internal;x-friends:="org.eclipse.mylyn.reviews.tasks.ui" diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangeSetReviewFile.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangeSetReviewFile.java index d482b714..99a8f88a 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangeSetReviewFile.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangeSetReviewFile.java @@ -39,22 +39,18 @@ public ChangeSetReviewFile(Change change) { this.change = change; } - @Override public String getFileName() { return change.getTarget().getPath(); } - @Override public boolean isNewFile() { return change.getChangeType().equals(ChangeType.ADDED); } - @Override public boolean canReview() { return true; } - @Override public ICompareInput getCompareInput() { ICompareInput ci = new DiffNode(Differencer.CHANGE, null, new CompareItem(change.getBase()), new CompareItem(change.getTarget())); diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangesetScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangesetScopeItem.java index ce2e1cb7..15a974b4 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangesetScopeItem.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangesetScopeItem.java @@ -43,7 +43,6 @@ public ChangesetScopeItem(String revisionId, String repositoryUrl) { this.repositoryUrl = repositoryUrl; } - @Override public List<IReviewFile> getReviewFiles(NullProgressMonitor monitor) throws CoreException { for (ScmConnector connector : ScmCore.getAllRegisteredConnectors()) { @@ -53,62 +52,51 @@ public List<IReviewFile> getReviewFiles(NullProgressMonitor monitor) ChangeSet changeset = connector.getChangeSet(repository, new IFileRevision() { - @Override public IStorage getStorage( IProgressMonitor monitor) throws CoreException { return null; } - @Override public String getName() { return null; } - @Override public URI getURI() { return null; } - @Override public long getTimestamp() { return 0; } - @Override public boolean exists() { return false; } - @Override public String getContentIdentifier() { return revisionId; } - @Override public String getAuthor() { return null; } - @Override public String getComment() { // TODO Auto-generated method stub return null; } - @Override public ITag[] getTags() { // TODO Auto-generated method stub return null; } - @Override public boolean isPropertyMissing() { // TODO Auto-generated method stub return false; } - @Override public IFileRevision withAllProperties( IProgressMonitor monitor) throws CoreException { @@ -137,12 +125,10 @@ public String getRevisionId() { return revisionId; } - @Override public String getDescription() { return "Changeset " + revisionId; } - @Override public String getType(int count) { return count == 1 ? "changeset" : "changesets"; } 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 695f25f4..50980deb 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 @@ -60,7 +60,6 @@ public Reader createReader() throws CoreException { }; } - @Override public List<IReviewFile> getReviewFiles( NullProgressMonitor nullProgressMonitor) throws CoreException { IFilePatch2[] parsedPatch = PatchParser.parsePatch(getPatch()); @@ -71,12 +70,10 @@ public List<IReviewFile> getReviewFiles( return files; } - @Override public String getDescription() { return "Patch "+attachment.getFileName(); } - @Override public String getType(int count) { return count ==1? "patch":"patches"; } 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 05ec47fd..2c84ff7c 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 @@ -43,7 +43,6 @@ public Attachment getAttachment() { return attachment; } - @Override public List<IReviewFile> getReviewFiles(NullProgressMonitor monitor) throws CoreException { @@ -92,17 +91,14 @@ public InputStream getContents() } - @Override public String getFileName() { return fileName; } - @Override public boolean isNewFile() { return true; } - @Override public boolean canReview() { return true; @@ -134,12 +130,10 @@ public String getType() { } - @Override public String getDescription() { 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/internal/AbstractTreeNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/AbstractTreeNode.java index 29be86c5..b183ef8d 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/AbstractTreeNode.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/AbstractTreeNode.java @@ -29,12 +29,10 @@ protected AbstractTreeNode(ITaskProperties task) { this.task=task; } - @Override public List<ITreeNode> getChildren() { return Collections.unmodifiableList(children); } - @Override public ITreeNode getParent() { return parent; } @@ -44,17 +42,14 @@ public void addChildren(ITreeNode child) { child.setParent(this); } - @Override public void setParent(ITreeNode parent) { this.parent = parent; } - @Override public String getTaskId() { return task!=null? task.getTaskId():null; } - @Override public ITaskProperties getTask() { return task; } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchReviewFile.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchReviewFile.java index 6f12ea48..0288c4e5 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchReviewFile.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchReviewFile.java @@ -102,17 +102,14 @@ private boolean patchAddsFile() { return true; } - @Override public String getFileName() { return patch.getTargetPath(configuration).lastSegment(); } - @Override public boolean isNewFile() { return patchAddsFile(); } - @Override public boolean canReview() { return sourceFileExists() || patchAddsFile(); diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewResultNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewResultNode.java index dcc1da41..7317c554 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewResultNode.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewResultNode.java @@ -29,12 +29,10 @@ public String getDescription() { return result.getComment(); } - @Override public Rating getResult() { return result.getRating(); } - @Override public String getPerson() { return result.getReviewer(); } 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 504c2c51..8f2529f3 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 @@ -78,7 +78,6 @@ private String convertScopeToDescription() { return sb.toString(); } - @Override public Rating getResult() { Rating rating = null; for (ReviewResult res : results) { @@ -90,7 +89,6 @@ public Rating getResult() { return rating; } - @Override public String getPerson() { // TODO return scope.getCreator(); diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java index 45dff368..0d63c6be 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java @@ -50,7 +50,6 @@ public ReviewTaskMapper(IReviewDslMapper parser, this.serializer = serializer; } - @Override public ReviewScope mapTaskToScope(ITaskProperties properties) throws CoreException { Assert.isNotNull(properties); @@ -76,14 +75,12 @@ public ReviewScope mapTaskToScope(ITaskProperties properties) } - @Override public void mapScopeToTask(ReviewScope scope, ITaskProperties taskProperties) { ReviewDslScope scope2 = mapScope(scope); taskProperties.setDescription(serializer.serialize(scope2)); } - @Override public void mapResultToTask( org.eclipse.mylyn.reviews.tasks.core.ReviewResult res, ITaskProperties taskProperties) { @@ -110,7 +107,6 @@ public void mapResultToTask( taskProperties.setNewCommentText(resultAsText); } - @Override public org.eclipse.mylyn.reviews.tasks.core.ReviewResult mapCurrentReviewResult( ITaskProperties taskProperties) { Assert.isNotNull(taskProperties); @@ -135,7 +131,6 @@ public org.eclipse.mylyn.reviews.tasks.core.ReviewResult mapCurrentReviewResult( return result; } - @Override public List<ReviewResult> mapTaskToResults(ITaskProperties taskProperties) { List<ReviewResult> results = new ArrayList<ReviewResult>(); for (TaskComment comment : taskProperties.getComments()) { 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 bc582f6e..01ac403c 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 @@ -24,7 +24,6 @@ public TaskNode(ITaskProperties task) { super(task); } - @Override public String getDescription() { int patchCount=0; int otherCount=0; @@ -56,13 +55,11 @@ public String getDescription() { return sb.toString(); } - @Override public Rating getResult() { // TODO Auto-generated method stub return null; } - @Override public String getPerson() { //TODO return "FIXME"; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskProperties.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskProperties.java index d93259e3..da6ee7c5 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskProperties.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskProperties.java @@ -41,19 +41,16 @@ public TaskProperties(ITaskDataManager manager, TaskData taskData) { this.manager = manager; } - @Override public String getDescription() { return taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION) .getValue(); } - @Override public String getAssignedTo() { return taskData.getRoot() .getMappedAttribute(TaskAttribute.USER_ASSIGNED).getValue(); } - @Override public List<Attachment> getAttachments() { List<TaskAttribute> attachments = taskData.getAttributeMapper() .getAttributesByType(taskData, TaskAttribute.TYPE_ATTACHMENT); @@ -76,7 +73,6 @@ private String attributeValue(TaskAttribute parent, String attribute) { return parent.getMappedAttribute(attribute).getValue(); } - @Override public List<TaskComment> getComments() { List<TaskComment> comments = new ArrayList<TaskComment>(); for (TaskAttribute attr : taskData.getRoot().getAttributes().values()) { @@ -99,7 +95,6 @@ public List<TaskComment> getComments() { return comments; } - @Override public String getNewCommentText() { TaskAttribute attribute = this.taskData.getRoot().getMappedAttribute( TaskAttribute.COMMENT_NEW); @@ -109,7 +104,6 @@ public String getNewCommentText() { return attribute.getValue(); } - @Override public void setNewCommentText(String value) { TaskAttribute attribute = this.taskData.getRoot().getMappedAttribute( TaskAttribute.COMMENT_NEW); @@ -129,7 +123,6 @@ public static ITaskProperties fromTaskData(ITaskDataManager manager, return new TaskProperties(manager, taskData); } - @Override public ITaskProperties loadFor(String taskId) throws CoreException { TaskData td = manager.getTaskData( new TaskRepository(taskData.getConnectorKind(), taskData @@ -137,12 +130,10 @@ public ITaskProperties loadFor(String taskId) throws CoreException { return new TaskProperties(manager, td); } - @Override public String getTaskId() { return taskData.getTaskId(); } - @Override public void setDescription(String description) { setValue(TaskAttribute.DESCRIPTION, description); } @@ -157,24 +148,20 @@ private void setValue(String mappedAttributeName, String value) { attribute.setValue(value); } - @Override public void setSummary(String summary) { taskData.getRoot().getMappedAttribute(TaskAttribute.SUMMARY) .setValue(summary); } - @Override public void setAssignedTo(String assignee) { taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED) .setValue(assignee); } - @Override public String getRepositoryUrl() { return taskData.getRepositoryUrl(); } - @Override public String getReporter() { return attributeValue(taskData.getRoot(),TaskAttribute.USER_REPORTER); } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/.classpath b/tbr/org.eclipse.mylyn.reviews.tasks.ui/.classpath index ad32c83a..64c5e31b 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/.classpath +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/.classpath @@ -1,6 +1,6 @@ <?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.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/> <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> <classpathentry kind="src" path="src"/> <classpathentry kind="output" path="bin"/> diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF index 33f6fabb..3f7973a1 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF @@ -16,6 +16,6 @@ Require-Bundle: org.eclipse.ui, org.eclipse.mylyn.versions.core;bundle-version="0.1.0", org.eclipse.mylyn.versions.tasks.core;bundle-version="0.1.0" Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-RequiredExecutionEnvironment: J2SE-1.5 Export-Package: org.eclipse.mylyn.reviews.tasks.ui.internal;x-internal:=true, org.eclipse.mylyn.reviews.tasks.ui.internal.editors;x-internal:=true diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewFromChangeSetAction.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewFromChangeSetAction.java index e5699b10..745c0c1f 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewFromChangeSetAction.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewFromChangeSetAction.java @@ -48,7 +48,6 @@ public class CreateReviewFromChangeSetAction extends Action implements private IStructuredSelection selection; - @Override public void run(IAction action) { try { ITask task = ((TaskChangeSet)selection.getFirstElement()).getTask(); @@ -112,7 +111,6 @@ private List<TaskChangeSet> getSelectedChangesets(ITask task) { return cs; } - @Override public void selectionChanged(IAction action, ISelection selection) { setEnabled(selection.isEmpty() && selection instanceof IStructuredSelection); diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java index 8a256914..92ed9129 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java @@ -203,33 +203,27 @@ public boolean select(Viewer viewer, Object parentElement, private static class ReviewResultContentProvider implements ITreeContentProvider { - @Override public Object[] getChildren(Object parentElement) { return ((ITreeNode) parentElement).getChildren().toArray(); } - @Override public Object getParent(Object element) { return ((ITreeNode) element).getParent(); } - @Override public boolean hasChildren(Object element) { return !((ITreeNode) element).getChildren().isEmpty(); } - @Override public void dispose() { // nothing to do } - @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // nothing to do } - @Override public Object[] getElements(Object inputElement) { if (inputElement instanceof Object[]) { return (Object[]) inputElement; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPart.java index 5220bb90..5598526a 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPart.java @@ -239,7 +239,6 @@ protected Object prepareInput( SafeRunner.run(new ISafeRunnable() { - @Override public void run() throws Exception { ReviewScope reviewScope = getReviewScope(); @@ -266,7 +265,6 @@ public void run() throws Exception { } Display.getCurrent().asyncExec(new Runnable() { - @Override public void run() { fileList.setInput(rootNodes); if (rootNodes.length == 0) { @@ -277,7 +275,6 @@ public void run() { } - @Override public void handleException(Throwable exception) { exception.printStackTrace(); } @@ -374,7 +371,6 @@ void registerEditOperations(ReviewResult result) { final IReviewMapper mapper = ReviewsUiPlugin.getMapper(); PropertyChangeListener listener = new PropertyChangeListener() { - @Override public void propertyChange(PropertyChangeEvent arg0) { ReviewResult result = (ReviewResult) arg0.getSource();
cd580a4dc6e8511a96a65c7bfd8c717b22d4aa1f
brandonborkholder$glg2d
More complete demo of swing functionality.
p
https://github.com/brandonborkholder/glg2d
diff --git a/src/test/java/glg2d/examples/shaders/UIDemo.java b/src/test/java/glg2d/examples/shaders/UIDemo.java index ef72662e..54f750fd 100644 --- a/src/test/java/glg2d/examples/shaders/UIDemo.java +++ b/src/test/java/glg2d/examples/shaders/UIDemo.java @@ -1,5 +1,7 @@ package glg2d.examples.shaders; +import glg2d.G2DGLCanvas; + import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; @@ -27,40 +29,71 @@ import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; +import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; +import javax.swing.ScrollPaneConstants; import javax.swing.SpinnerDateModel; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; +import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.border.EtchedBorder; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; -import net.miginfocom.swing.MigLayout; - @SuppressWarnings("serial") public class UIDemo extends JPanel { public UIDemo() { - JTabbedPane tabs = new JTabbedPane(); - tabs.add(new JScrollPane(createButtonComponent()), "Buttons"); - tabs.add(new JScrollPane(createTreeComponent()), "Tree"); - tabs.add(new JScrollPane(createTableComponent()), "Table"); - tabs.add(new JScrollPane(createBorderComponent()), "Borders"); - tabs.add(new JScrollPane(createListComponent()), "List"); - tabs.add(new JScrollPane(createInputComponent()), "Inputs"); - tabs.add(new JScrollPane(createProgressComponent()), "Progress"); + JPanel leftPanel = new JPanel(new BorderLayout()); + leftPanel.add(new JScrollPane(createTreeComponent()), BorderLayout.NORTH); + leftPanel.add(new JScrollPane(createTableComponent()), BorderLayout.CENTER); + leftPanel.add(new JScrollPane(createListComponent()), BorderLayout.SOUTH); + + JSplitPane mainSplit = new JSplitPane(); + mainSplit.setDividerSize(8); + mainSplit.setOneTouchExpandable(true); + mainSplit.setContinuousLayout(true); + mainSplit.setLeftComponent(leftPanel); + + JPanel rightPanel = new JPanel(new BorderLayout()); + mainSplit.setRightComponent(rightPanel); + rightPanel.add(createButtonComponent(), BorderLayout.NORTH); + + JPanel rightSubPanel = new JPanel(new BorderLayout()); + rightPanel.add(rightSubPanel, BorderLayout.CENTER); + rightSubPanel.add(createProgressComponent(), BorderLayout.NORTH); + + JSplitPane rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); + rightSplit.setDividerSize(10); + rightSplit.setOneTouchExpandable(true); + rightSplit.setTopComponent(createInputComponent()); + rightSplit.setBottomComponent(createBorderComponent()); + + rightSubPanel.add(rightSplit, BorderLayout.CENTER); + rightSubPanel.add(createTabComponent(), BorderLayout.SOUTH); setLayout(new BorderLayout()); - add(tabs, BorderLayout.CENTER); + mainSplit.setDividerLocation(400); + add(mainSplit, BorderLayout.CENTER); + } + + JComponent createTabComponent() { + JTabbedPane tabs = new JTabbedPane(); + tabs.addTab("Tab 1", new JLabel("Foo bar")); + tabs.addTab("Tab 2", new JLabel("Foo bar")); + tabs.addTab("Tab 3", new JLabel("Foo bar")); + tabs.addTab("Tab 4", new JLabel("Foo bar")); + tabs.addTab("Tab 5", new JLabel("Foo bar")); + return tabs; } JComponent createProgressComponent() { - JPanel panel = new JPanel(new MigLayout("fill,flowy")); + JPanel panel = new JPanel(); JProgressBar bar = new JProgressBar(); bar.setIndeterminate(true); @@ -83,7 +116,7 @@ public void actionPerformed(ActionEvent e) { } JComponent createInputComponent() { - JPanel panel = new JPanel(new MigLayout("fill,flowy")); + JPanel panel = new JPanel(); JComboBox box = new JComboBox(new String[] { "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel" }); panel.add(box); @@ -95,14 +128,20 @@ JComponent createInputComponent() { panel.add(spinner); JTextField field = new JTextField(); + field.setText("lorem ipsum..."); field.setColumns(10); panel.add(field); JTextArea area = new JTextArea(); + area.setText("lorem ipsum... lorem ipsum lorem ipsum...\n lorem ipsum...\n lorem ipsum..."); area.setColumns(10); area.setRows(3); panel.add(new JScrollPane(area)); + JPanel p = new JPanel(); + p.setPreferredSize(new Dimension(100, 50)); + panel.add(new JScrollPane(p, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS)); + JSlider slider = new JSlider(); slider.setPaintTicks(true); slider.setPaintLabels(true); @@ -112,7 +151,7 @@ JComponent createInputComponent() { } JComponent createBorderComponent() { - JPanel panel = new JPanel(new MigLayout("fill,flowy")); + JPanel panel = new JPanel(); JLabel label = new JLabel("no border"); panel.add(label); @@ -191,7 +230,7 @@ JComponent createTreeComponent() { } JComponent createButtonComponent() { - JPanel panel = new JPanel(new MigLayout("fill,flowy")); + JPanel panel = new JPanel(); JButton button = new JButton("Normal"); panel.add(button); @@ -241,9 +280,12 @@ Icon getIcon(String name) { } } - public static void main(String[] args) { + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JFrame frame = new JFrame("Swing Demo"); - frame.setContentPane(new UIDemo()); + +// frame.setContentPane(new UIDemo()); + frame.setContentPane(new G2DGLCanvas(new UIDemo())); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(1024, 768)); frame.pack();
1f47d355234777b707191b9c8e813c0000ecf212
hadoop
YARN-2059. Added admin ACLs support to Timeline- Server. Contributed by Zhijie Shen. svn merge --ignore-ancestry -c 1597207- ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1597208 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 e34b930003f51..c74e777d400fc 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -87,6 +87,9 @@ Release 2.5.0 - UNRELEASED YARN-2012. Fair Scheduler: allow default queue placement rule to take an arbitrary queue (Ashwin Shankar via Sandy Ryza) + YARN-2059. Added admin ACLs support to Timeline Server. (Zhijie Shen via + vinodkv) + OPTIMIZATIONS BUG FIXES 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/TimelineACLsManager.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/TimelineACLsManager.java index 5bc8705222f88..8009b39c94f72 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/TimelineACLsManager.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/TimelineACLsManager.java @@ -27,8 +27,8 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity; -import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; +import org.apache.hadoop.yarn.security.AdminACLsManager; import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.EntityIdentifier; import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.TimelineStore.SystemFilter; @@ -42,11 +42,10 @@ public class TimelineACLsManager { private static final Log LOG = LogFactory.getLog(TimelineACLsManager.class); - private boolean aclsEnabled; + private AdminACLsManager adminAclsManager; public TimelineACLsManager(Configuration conf) { - aclsEnabled = conf.getBoolean(YarnConfiguration.YARN_ACL_ENABLE, - YarnConfiguration.DEFAULT_YARN_ACL_ENABLE); + this.adminAclsManager = new AdminACLsManager(conf); } public boolean checkAccess(UserGroupInformation callerUGI, @@ -57,7 +56,7 @@ public boolean checkAccess(UserGroupInformation callerUGI, + new EntityIdentifier(entity.getEntityId(), entity.getEntityType())); } - if (!aclsEnabled) { + if (!adminAclsManager.areACLsEnabled()) { return true; } @@ -70,10 +69,12 @@ public boolean checkAccess(UserGroupInformation callerUGI, + " is corrupted."); } String owner = values.iterator().next().toString(); - // TODO: Currently we just check the user is the timeline entity owner. In - // the future, we need to check whether the user is admin or is in the + // TODO: Currently we just check the user is the admin or the timeline + // entity owner. In the future, we need to check whether the user is in the // allowed user/group list - if (callerUGI != null && callerUGI.getShortUserName().equals(owner)) { + if (callerUGI != null + && (adminAclsManager.isAdmin(callerUGI) || + callerUGI.getShortUserName().equals(owner))) { return true; } return false; @@ -81,8 +82,11 @@ public boolean checkAccess(UserGroupInformation callerUGI, @Private @VisibleForTesting - public void setACLsEnabled(boolean aclsEnabled) { - this.aclsEnabled = aclsEnabled; + public AdminACLsManager + setAdminACLsManager(AdminACLsManager adminAclsManager) { + AdminACLsManager oldAdminACLsManager = this.adminAclsManager; + this.adminAclsManager = adminAclsManager; + return oldAdminACLsManager; } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java index 6041779b13a94..5d749fa090653 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java @@ -346,8 +346,9 @@ public TimelinePutResponse postEntities( new EntityIdentifier(entity.getEntityId(), entity.getEntityType()); // check if there is existing entity + TimelineEntity existingEntity = null; try { - TimelineEntity existingEntity = + existingEntity = store.getEntity(entityID.getId(), entityID.getType(), EnumSet.of(Field.PRIMARY_FILTERS)); if (existingEntity != null @@ -369,10 +370,14 @@ public TimelinePutResponse postEntities( continue; } - // inject owner information for the access check + // inject owner information for the access check if this is the first + // time to post the entity, in case it's the admin who is updating + // the timeline data. try { - injectOwnerInfo(entity, - callerUGI == null ? "" : callerUGI.getShortUserName()); + if (existingEntity == null) { + injectOwnerInfo(entity, + callerUGI == null ? "" : callerUGI.getShortUserName()); + } } catch (YarnException e) { // Skip the entity which messes up the primary filter and record the // error diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java index 2c536681aed25..39102b43badfa 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java @@ -49,6 +49,7 @@ public void testYarnACLsNotEnabled() throws Exception { public void testYarnACLsEnabled() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); + conf.set(YarnConfiguration.YARN_ADMIN_ACL, "admin"); TimelineACLsManager timelineACLsManager = new TimelineACLsManager(conf); TimelineEntity entity = new TimelineEntity(); @@ -63,12 +64,17 @@ public void testYarnACLsEnabled() throws Exception { "Other shouldn't be allowed to access", timelineACLsManager.checkAccess( UserGroupInformation.createRemoteUser("other"), entity)); + Assert.assertTrue( + "Admin should be allowed to access", + timelineACLsManager.checkAccess( + UserGroupInformation.createRemoteUser("admin"), entity)); } @Test public void testCorruptedOwnerInfo() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); + conf.set(YarnConfiguration.YARN_ADMIN_ACL, "owner"); TimelineACLsManager timelineACLsManager = new TimelineACLsManager(conf); TimelineEntity entity = new TimelineEntity(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java index 9b0ae3761d26a..7e3e409940386 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java @@ -40,6 +40,7 @@ import org.apache.hadoop.yarn.api.records.timeline.TimelineEvents; import org.apache.hadoop.yarn.api.records.timeline.TimelinePutResponse; import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.security.AdminACLsManager; import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.TestMemoryTimelineStore; import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.TimelineStore; import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.security.TimelineACLsManager; @@ -64,6 +65,7 @@ public class TestTimelineWebServices extends JerseyTest { private static TimelineStore store; private static TimelineACLsManager timelineACLsManager; + private static AdminACLsManager adminACLsManager; private static String remoteUser; private long beforeTime; @@ -83,6 +85,9 @@ protected void configureServlets() { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, false); timelineACLsManager = new TimelineACLsManager(conf); + conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); + conf.set(YarnConfiguration.YARN_ADMIN_ACL, "admin"); + adminACLsManager = new AdminACLsManager(conf); bind(TimelineACLsManager.class).toInstance(timelineACLsManager); serve("/*").with(GuiceContainer.class); filter("/*").through(TestFilter.class); @@ -387,7 +392,8 @@ public void testPostEntities() throws Exception { @Test public void testPostEntitiesWithYarnACLsEnabled() throws Exception { - timelineACLsManager.setACLsEnabled(true); + AdminACLsManager oldAdminACLsManager = + timelineACLsManager.setAdminACLsManager(adminACLsManager); remoteUser = "tester"; try { TimelineEntities entities = new TimelineEntities(); @@ -419,14 +425,15 @@ public void testPostEntitiesWithYarnACLsEnabled() throws Exception { Assert.assertEquals(TimelinePutResponse.TimelinePutError.ACCESS_DENIED, putResponse.getErrors().get(0).getErrorCode()); } finally { - timelineACLsManager.setACLsEnabled(false); + timelineACLsManager.setAdminACLsManager(oldAdminACLsManager); remoteUser = null; } } @Test public void testGetEntityWithYarnACLsEnabled() throws Exception { - timelineACLsManager.setACLsEnabled(true); + AdminACLsManager oldAdminACLsManager = + timelineACLsManager.setAdminACLsManager(adminACLsManager); remoteUser = "tester"; try { TimelineEntities entities = new TimelineEntities(); @@ -481,14 +488,15 @@ public void testGetEntityWithYarnACLsEnabled() throws Exception { assertEquals(ClientResponse.Status.NOT_FOUND, response.getClientResponseStatus()); } finally { - timelineACLsManager.setACLsEnabled(false); + timelineACLsManager.setAdminACLsManager(oldAdminACLsManager); remoteUser = null; } } @Test public void testGetEntitiesWithYarnACLsEnabled() { - timelineACLsManager.setACLsEnabled(true); + AdminACLsManager oldAdminACLsManager = + timelineACLsManager.setAdminACLsManager(adminACLsManager); remoteUser = "tester"; try { TimelineEntities entities = new TimelineEntities(); @@ -526,14 +534,15 @@ public void testGetEntitiesWithYarnACLsEnabled() { assertEquals("test type 4", entities.getEntities().get(0).getEntityType()); assertEquals("test id 5", entities.getEntities().get(0).getEntityId()); } finally { - timelineACLsManager.setACLsEnabled(false); + timelineACLsManager.setAdminACLsManager(oldAdminACLsManager); remoteUser = null; } } @Test public void testGetEventsWithYarnACLsEnabled() { - timelineACLsManager.setACLsEnabled(true); + AdminACLsManager oldAdminACLsManager = + timelineACLsManager.setAdminACLsManager(adminACLsManager); remoteUser = "tester"; try { TimelineEntities entities = new TimelineEntities(); @@ -579,7 +588,7 @@ public void testGetEventsWithYarnACLsEnabled() { assertEquals(1, events.getAllEvents().size()); assertEquals("test id 6", events.getAllEvents().get(0).getEntityId()); } finally { - timelineACLsManager.setACLsEnabled(false); + timelineACLsManager.setAdminACLsManager(oldAdminACLsManager); remoteUser = null; } }
c8be0df67073618a84ec809513850d3da64dff0b
genericworkflownodes$genericknimenodes
first draft of actual relocator functionality
p
https://github.com/genericworkflownodes/genericknimenodes
diff --git a/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/outputconverter/Relocator.java b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/outputconverter/Relocator.java index 1d4cd5db..9fb803c7 100644 --- a/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/outputconverter/Relocator.java +++ b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/outputconverter/Relocator.java @@ -18,6 +18,9 @@ */ package com.genericworkflownodes.knime.outputconverter; +import java.io.File; +import java.net.URI; + import com.genericworkflownodes.knime.config.INodeConfiguration; /** @@ -29,13 +32,18 @@ * <ul> * <li>%TEMP% - The temporary dirctory obtained from the Java Runtime.</li> * <li>%PWD% - The working directory for the tool execution.</li> - * <li>%BASE% - The base name of the original output file passed to the tool.</li> + * <li>%BASE% - The name of the original output file passed to the tool without + * extension</li> * </ul> * * @author aiche */ public class Relocator { + private static String TEMP = "%TEMP%"; + private static String PWD = "%PWD%"; + private static String BASENAME = "%BASENAME[.*]%"; + /** * The referenced parameter that should be transformed. */ @@ -44,19 +52,19 @@ public class Relocator { /** * The regular expression used to find the parameter. */ - private String pattern; + private String location; /** * C'tor. * * @param parameter * The name of the output parameter that should be transformed - * @param pattern + * @param location * The pattern used to find the output file. */ - public Relocator(String parameter, String pattern) { + public Relocator(String parameter, String location) { reference = parameter; - this.pattern = pattern; + this.location = location; } /** @@ -65,9 +73,37 @@ public Relocator(String parameter, String pattern) { * * @param config * The node configuration of the tool at execution time. + * @param target + * The original output target specified when calling the tool and + * the place where the found output should be stored. + * @param workingDirectory + * The directory where the tool was called. + * @throws RelocatorException + * If the file could not be found. */ - public void relocate(INodeConfiguration config) { + public void relocate(INodeConfiguration config, URI target, + File workingDirectory) throws RelocatorException { + + String updatedLocation = location; + + // replace fixed variables in the pattern with + updatedLocation.replace(TEMP, System.getProperty("temp.dir")); + updatedLocation.replace(PWD, workingDirectory.getAbsolutePath()); + + fixBaseNames(updatedLocation); + + File fileToRelocate = new File(updatedLocation); + if (!fileToRelocate.exists()) { + throw new RelocatorException( + "Could not find file specified by this relocator: " + + location); + } + + fileToRelocate.renameTo(new File(target.getPath())); + } + private void fixBaseNames(String updatedLocation) { + // TODO implement base name updating } /** diff --git a/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/outputconverter/RelocatorException.java b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/outputconverter/RelocatorException.java new file mode 100644 index 00000000..092d3823 --- /dev/null +++ b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/outputconverter/RelocatorException.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2012, Stephan Aiche. + * + * This file is part of GenericKnimeNodes. + * + * GenericKnimeNodes is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +package com.genericworkflownodes.knime.outputconverter; + +/** + * Exception indicating an error while relocating files. + * + * @author aiche + */ +public class RelocatorException extends Exception { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = -5597320422947745165L; + + /** + * C'tor. + * + * @param message + * Description of the error that occured. + */ + public RelocatorException(String message) { + super(message); + } +} diff --git a/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/schemas/CTD.xsd b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/schemas/CTD.xsd index b866fade..67a7a6ad 100644 --- a/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/schemas/CTD.xsd +++ b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/schemas/CTD.xsd @@ -178,13 +178,16 @@ </xs:documentation> </xs:annotation> </xs:element> - <xs:element name="pattern" type="xs:string" minOccurs="1" maxOccurs="1"> + <xs:element name="location" type="xs:string" minOccurs="1" maxOccurs="1"> <xs:annotation> - <xs:documentation> - The pattern used to find the output file. + <xs:documentation>The location of the output file defined using following variables: + +%TEMP% - the temporary directory while executing +%PWD% - the working directory while executing +%BASENAME[PARAM]% - the base name of PARAM </xs:documentation> - </xs:annotation> - + </xs:annotation> + </xs:element> </xs:sequence> </xs:complexType>
b4a6e4a98e5ca16889391a5db989b151f03ed208
Valadoc
Add initial reading-support for <doc>
a
https://github.com/GNOME/vala/
diff --git a/icons/devhelpstyle.css b/icons/devhelpstyle.css index bc37d5c2b9..c52052af21 100644 --- a/icons/devhelpstyle.css +++ b/icons/devhelpstyle.css @@ -125,7 +125,6 @@ div.site_body { color: #a52a2a; } - div.main_code_definition { padding-right: 10px; padding-left: 10px; @@ -140,6 +139,30 @@ div.main_code_definition { margin: 10px; } +div.main_notification_block { + padding-right: 10px; + padding-left: 10px; + padding-bottom: 5px; + padding-top: 5px; + + border-color: #d08717; + background-color: #fbf2c3; + border-style: solid; + border-width: 1px; + margin: 10px; +} + +span.main_block_headline { + background-image:url(tip.png); + background-repeat:no-repeat; + background-position:center right; + font-weight:bold; + display:block; +} + +div.main_block_content { + margin-left:15px; +} span.leaf_code_definition { font: monospace; diff --git a/icons/style.css b/icons/style.css index ef96972475..c4b0c799be 100644 --- a/icons/style.css +++ b/icons/style.css @@ -154,6 +154,30 @@ div.main_code_definition { margin: 10px; } +div.main_notification_block { + padding-right: 10px; + padding-left: 10px; + padding-bottom: 5px; + padding-top: 5px; + + border-color: #d08717; + background-color: #fbf2c3; + border-style: solid; + border-width: 1px; + margin: 10px; +} + +span.main_block_headline { + background-image:url(tip.png); + background-repeat:no-repeat; + background-position:center right; + font-weight:bold; + display:block; +} + +div.main_block_content { + margin-left:15px; +} span.leaf_code_definition { font: monospace; diff --git a/icons/wikistyle.css b/icons/wikistyle.css index 56ca6bc73a..a3d8e4b981 100644 --- a/icons/wikistyle.css +++ b/icons/wikistyle.css @@ -32,6 +32,31 @@ ul.external_link { background-image: url(warning.png); } +div.main_notification_block { + padding-right: 10px; + padding-left: 10px; + padding-bottom: 5px; + padding-top: 5px; + + border-color: #d08717; + background-color: #fbf2c3; + border-style: solid; + border-width: 1px; + margin: 10px; +} + +span.main_block_headline { + background-image:url(tip.png); + background-repeat:no-repeat; + background-position:center right; + font-weight:bold; + display:block; +} + +div.main_block_content { + margin-left:15px; +} + .main_sourcesample { padding-right: 10px; padding-left: 5px; diff --git a/src/driver/0.10.x/driver.vala b/src/driver/0.10.x/driver.vala index 6fc87d97a3..253bc7bea5 100755 --- a/src/driver/0.10.x/driver.vala +++ b/src/driver/0.10.x/driver.vala @@ -29,11 +29,25 @@ using Gee; * Creates an simpler, minimized, more abstract AST for valacs AST. */ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver { + private Api.Tree? tree; + + public void write_gir (Settings settings, ErrorReporter reporter) { + var gir_writer = new Vala.GIRWriter (); + + // put .gir file in current directory unless -d has been explicitly specified + string gir_directory = "."; + if (settings.gir_directory != null) { + gir_directory = settings.gir_directory; + } + + gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name); + } public Api.Tree? build (Settings settings, ErrorReporter reporter) { TreeBuilder builder = new TreeBuilder (); - Api.Tree? tree = builder.build (settings, reporter); + tree = builder.build (settings, reporter); if (reporter.errors > 0) { + tree = null; return null; } diff --git a/src/driver/0.12.x/driver.vala b/src/driver/0.12.x/driver.vala index 6fc87d97a3..253bc7bea5 100755 --- a/src/driver/0.12.x/driver.vala +++ b/src/driver/0.12.x/driver.vala @@ -29,11 +29,25 @@ using Gee; * Creates an simpler, minimized, more abstract AST for valacs AST. */ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver { + private Api.Tree? tree; + + public void write_gir (Settings settings, ErrorReporter reporter) { + var gir_writer = new Vala.GIRWriter (); + + // put .gir file in current directory unless -d has been explicitly specified + string gir_directory = "."; + if (settings.gir_directory != null) { + gir_directory = settings.gir_directory; + } + + gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name); + } public Api.Tree? build (Settings settings, ErrorReporter reporter) { TreeBuilder builder = new TreeBuilder (); - Api.Tree? tree = builder.build (settings, reporter); + tree = builder.build (settings, reporter); if (reporter.errors > 0) { + tree = null; return null; } diff --git a/src/driver/0.14.x/driver.vala b/src/driver/0.14.x/driver.vala index 6fc87d97a3..253bc7bea5 100755 --- a/src/driver/0.14.x/driver.vala +++ b/src/driver/0.14.x/driver.vala @@ -29,11 +29,25 @@ using Gee; * Creates an simpler, minimized, more abstract AST for valacs AST. */ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver { + private Api.Tree? tree; + + public void write_gir (Settings settings, ErrorReporter reporter) { + var gir_writer = new Vala.GIRWriter (); + + // put .gir file in current directory unless -d has been explicitly specified + string gir_directory = "."; + if (settings.gir_directory != null) { + gir_directory = settings.gir_directory; + } + + gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name); + } public Api.Tree? build (Settings settings, ErrorReporter reporter) { TreeBuilder builder = new TreeBuilder (); - Api.Tree? tree = builder.build (settings, reporter); + tree = builder.build (settings, reporter); if (reporter.errors > 0) { + tree = null; return null; } diff --git a/src/driver/0.16.x/Makefile.am b/src/driver/0.16.x/Makefile.am index 7d5b3664c6..a48f8219ce 100755 --- a/src/driver/0.16.x/Makefile.am +++ b/src/driver/0.16.x/Makefile.am @@ -33,6 +33,7 @@ libdriver_la_VALASOURCES = \ initializerbuilder.vala \ symbolresolver.vala \ treebuilder.vala \ + girwriter.vala \ driver.vala \ $(NULL) diff --git a/src/driver/0.16.x/driver.vala b/src/driver/0.16.x/driver.vala index 6fc87d97a3..35d43d1381 100755 --- a/src/driver/0.16.x/driver.vala +++ b/src/driver/0.16.x/driver.vala @@ -29,15 +29,29 @@ using Gee; * Creates an simpler, minimized, more abstract AST for valacs AST. */ public class Valadoc.Drivers.Driver : Object, Valadoc.Driver { + private SymbolResolver resolver; + private Api.Tree? tree; + + public void write_gir (Settings settings, ErrorReporter reporter) { + var gir_writer = new Drivers.GirWriter (resolver); + + // put .gir file in current directory unless -d has been explicitly specified + string gir_directory = "."; + if (settings.gir_directory != null) { + gir_directory = settings.gir_directory; + } + + gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name); + } public Api.Tree? build (Settings settings, ErrorReporter reporter) { TreeBuilder builder = new TreeBuilder (); - Api.Tree? tree = builder.build (settings, reporter); + tree = builder.build (settings, reporter); if (reporter.errors > 0) { return null; } - SymbolResolver resolver = new SymbolResolver (builder); + resolver = new SymbolResolver (builder); tree.accept (resolver); return tree; diff --git a/src/driver/0.16.x/girwriter.vala b/src/driver/0.16.x/girwriter.vala new file mode 100644 index 0000000000..12762d14fa --- /dev/null +++ b/src/driver/0.16.x/girwriter.vala @@ -0,0 +1,203 @@ +/* girwriter.vala + * + * Copyright (C) 2011 Florian Brosch + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Florian Brosch <[email protected]> + */ + + +using Valadoc.Api; + + +/** + * Code visitor generating .gir file for the public interface. + */ +public class Valadoc.Drivers.GirWriter : Vala.GIRWriter { + private GtkdocRenderer renderer; + private SymbolResolver resolver; + + public GirWriter (SymbolResolver resolver) { + this.renderer = new GtkdocRenderer (); + this.resolver = resolver; + } + + private string? translate (Content.Comment? documentation) { + if (documentation == null) { + return null; + } + + renderer.render_symbol (documentation); + + return MarkupWriter.escape (renderer.content); + } + + private string? translate_taglet (Content.Taglet? taglet) { + if (taglet == null) { + return null; + } + + renderer.render_children (taglet); + + return MarkupWriter.escape (renderer.content); + } + + protected override string? get_interface_comment (Vala.Interface viface) { + Interface iface = resolver.resolve (viface) as Interface; + return translate (iface.documentation); + } + + protected override string? get_struct_comment (Vala.Struct vst) { + Struct st = resolver.resolve (vst) as Struct; + return translate (st.documentation); + } + + protected override string? get_enum_comment (Vala.Enum ven) { + Enum en = resolver.resolve (ven) as Enum; + return translate (en.documentation); + } + + protected override string? get_class_comment (Vala.Class vc) { + Class c = resolver.resolve (vc) as Class; + return translate (c.documentation); + } + + protected override string? get_error_code_comment (Vala.ErrorCode vecode) { + ErrorCode ecode = resolver.resolve (vecode) as ErrorCode; + return translate (ecode.documentation); + } + + protected override string? get_enum_value_comment (Vala.EnumValue vev) { + Api.EnumValue ev = resolver.resolve (vev) as Api.EnumValue; + return translate (ev.documentation); + } + + protected override string? get_constant_comment (Vala.Constant vc) { + Constant c = resolver.resolve (vc) as Constant; + return translate (c.documentation); + } + + protected override string? get_error_domain_comment (Vala.ErrorDomain vedomain) { + ErrorDomain edomain = resolver.resolve (vedomain) as ErrorDomain; + return translate (edomain.documentation); + } + + protected override string? get_field_comment (Vala.Field vf) { + Field f = resolver.resolve (vf) as Field; + return translate (f.documentation); + } + + protected override string? get_delegate_comment (Vala.Delegate vcb) { + Delegate cb = resolver.resolve (vcb) as Delegate; + return translate (cb.documentation); + } + + protected override string? get_method_comment (Vala.Method vm) { + Method m = resolver.resolve (vm) as Method; + return translate (m.documentation); + } + + protected override string? get_property_comment (Vala.Property vprop) { + Property prop = resolver.resolve (vprop) as Property; + return translate (prop.documentation); + } + + protected override string? get_delegate_return_comment (Vala.Delegate vcb) { + Delegate cb = resolver.resolve (vcb) as Delegate; + if (cb.documentation == null) { + return null; + } + + Content.Comment? documentation = cb.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (cb, typeof(Taglets.Return)); + foreach (Content.Taglet taglet in taglets) { + return translate_taglet (taglet); + } + + return null; + } + + protected override string? get_signal_return_comment (Vala.Signal vsig) { + Api.Signal sig = resolver.resolve (vsig) as Api.Signal; + if (sig.documentation == null) { + return null; + } + + Content.Comment? documentation = sig.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (sig, typeof(Taglets.Return)); + foreach (Content.Taglet taglet in taglets) { + return translate_taglet (taglet); + } + + return null; + } + + protected override string? get_method_return_comment (Vala.Method vm) { + Method m = resolver.resolve (vm) as Method; + if (m.documentation == null) { + return null; + } + + Content.Comment? documentation = m.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (m, typeof(Taglets.Return)); + foreach (Content.Taglet taglet in taglets) { + return translate_taglet (taglet); + } + + return null; + } + + protected override string? get_signal_comment (Vala.Signal vsig) { + Api.Signal sig = resolver.resolve (vsig) as Api.Signal; + return translate (sig.documentation); + } + + protected override string? get_parameter_comment (Vala.Parameter param) { + Api.Symbol symbol = resolver.resolve (((Vala.Symbol) param.parent_symbol)); + if (symbol == null) { + return null; + } + + Content.Comment? documentation = symbol.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (symbol, typeof(Taglets.Param)); + foreach (Content.Taglet _taglet in taglets) { + Taglets.Param taglet = (Taglets.Param) _taglet; + if (taglet.parameter_name == param.name) { + return translate_taglet (taglet); + } + } + + return null; + } +} + diff --git a/src/driver/0.16.x/symbolresolver.vala b/src/driver/0.16.x/symbolresolver.vala index bd3163fc04..f548f735d8 100644 --- a/src/driver/0.16.x/symbolresolver.vala +++ b/src/driver/0.16.x/symbolresolver.vala @@ -34,7 +34,7 @@ public class Valadoc.Drivers.SymbolResolver : Visitor { this.glib_error = builder.get_glib_error (); } - private Symbol? resolve (Vala.Symbol symbol) { + public Symbol? resolve (Vala.Symbol symbol) { return symbol_map.get (symbol); } diff --git a/src/driver/0.16.x/treebuilder.vala b/src/driver/0.16.x/treebuilder.vala index 3687610f28..353119eb33 100644 --- a/src/driver/0.16.x/treebuilder.vala +++ b/src/driver/0.16.x/treebuilder.vala @@ -1137,11 +1137,12 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { // public Api.Tree? build (Settings settings, ErrorReporter reporter) { - this.tree = new Api.Tree (reporter, settings); this.settings = settings; this.reporter = reporter; + this.tree = new Api.Tree (reporter, settings); var context = create_valac_tree (settings); + this.tree.data = context; reporter.warnings_offset = context.report.get_warnings (); reporter.errors_offset = context.report.get_errors (); diff --git a/src/libvaladoc/api/driver.vala b/src/libvaladoc/api/driver.vala index 8ad4a5e03a..a43abcff07 100755 --- a/src/libvaladoc/api/driver.vala +++ b/src/libvaladoc/api/driver.vala @@ -35,6 +35,7 @@ public delegate Type Valadoc.DriverRegisterFunction (ModuleLoader module_loader) public interface Valadoc.Driver : Object { + public abstract void write_gir (Settings settings, ErrorReporter reporter); public abstract Api.Tree? build (Settings settings, ErrorReporter reporter); } diff --git a/src/libvaladoc/api/tree.vala b/src/libvaladoc/api/tree.vala index 0133b0bef8..d4da906ba6 100755 --- a/src/libvaladoc/api/tree.vala +++ b/src/libvaladoc/api/tree.vala @@ -44,6 +44,11 @@ public class Valadoc.Api.Tree { this.packages.add (package); } + public void* data { + set; + get; + } + /** * The root of the wiki tree. */ @@ -196,9 +201,10 @@ public class Valadoc.Api.Tree { return params; } - public Tree (ErrorReporter reporter, Settings settings) { + public Tree (ErrorReporter reporter, Settings settings, void* data = null) { this.settings = settings; this.reporter = reporter; + this.data = data; } // copied from valacodecontext.vala diff --git a/src/libvaladoc/devhelp-markupwriter.vala b/src/libvaladoc/devhelp-markupwriter.vala index 4a0b2b55d6..2b846512fa 100755 --- a/src/libvaladoc/devhelp-markupwriter.vala +++ b/src/libvaladoc/devhelp-markupwriter.vala @@ -21,8 +21,12 @@ */ public class Valadoc.Devhelp.MarkupWriter : Valadoc.MarkupWriter { - public MarkupWriter (FileStream stream, bool xml_declaration = true) { - base (stream, xml_declaration); + + public MarkupWriter (FileStream stream, bool xml_declaration = true) { + // avoid broken implicit copy + unowned FileStream _stream = stream; + + base ((str) => { _stream.printf (str); }, xml_declaration); } protected override bool inline_element (string name) { diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index e9873e43ff..a376d400cb 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -418,7 +418,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { return item; } - private LinkedList<Block>? parse_docbook_information_box_template (string tagname) { + private BlockContent? parse_docbook_information_box_template (string tagname, BlockContent container) { if (!check_xml_open_tag (tagname)) { this.report_unexpected_token (current, "<%s>".printf (tagname)); return null; @@ -427,60 +427,39 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { next (); parse_docbook_spaces (); - LinkedList<Block> content = new LinkedList<Block> (); - - var header_run = factory.create_run (Run.Style.BOLD); - header_run.content.add (factory.create_text ("Note:")); - + Token tmp = null; while (current.type != TokenType.XML_CLOSE && current.type != TokenType.EOF) { - if (current.type == TokenType.XML_OPEN && current.content == "para") { - var paragraphs = parse_docbook_para (); - if (header_run != null) { - content.add_all (paragraphs); - } else { - Paragraph fp = paragraphs.first (); - fp.content.insert (0, factory.create_text (" ")); - fp.content.insert (0, header_run); - } - } else { - Token tmp_t = current; - - Run? inline_run = parse_inline_content (); + tmp = current; + var ic = parse_inline_content (); + if (ic != null && ic.content.size > 0) { Paragraph p = factory.create_paragraph (); - - if (content != null) { - p.content.add (header_run); - p.content.add (factory.create_text (" ")); - header_run = null; - } - - p.content.add (inline_run); - content.add (p); + p.content.add (ic); + container.content.add (p); + } - if (tmp_t == current) { - break; - } + var bc = parse_block_content (); + if (bc != null && bc.size > 0) { + container.content.add_all (bc); } } - //parse_block_content (); parse_docbook_spaces (); if (!check_xml_close_tag (tagname)) { this.report_unexpected_token (current, "</%s>".printf (tagname)); - return content; + return container; } next (); - return content; + return container; } - private LinkedList<Block>? parse_docbook_note () { - return parse_docbook_information_box_template ("note"); + private Note? parse_docbook_note () { + return (Note?) parse_docbook_information_box_template ("note", factory.create_note ()); } - private LinkedList<Block>? parse_docbook_warning () { - return parse_docbook_information_box_template ("warning"); + private Warning? parse_docbook_warning () { + return (Warning?) parse_docbook_information_box_template ("warning", factory.create_warning ()); } private Content.List? parse_docbook_itemizedlist () { @@ -871,9 +850,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { } else if (current.type == TokenType.XML_OPEN && current.content == "example") { this.append_block_content_not_null_all (content, parse_docbook_example ()); } else if (current.type == TokenType.XML_OPEN && current.content == "warning") { - this.append_block_content_not_null_all (content, parse_docbook_warning ()); + this.append_block_content_not_null (content, parse_docbook_warning ()); } else if (current.type == TokenType.XML_OPEN && current.content == "note") { - this.append_block_content_not_null_all (content, parse_docbook_note ()); + this.append_block_content_not_null (content, parse_docbook_note ()); } else if (current.type == TokenType.XML_OPEN && current.content == "refsect2") { this.append_block_content_not_null_all (content, parse_docbook_refsect2 ()); } else if (current.type == TokenType.GTKDOC_PARAGRAPH) { diff --git a/src/libvaladoc/gtkdocmarkupwriter.vala b/src/libvaladoc/gtkdocmarkupwriter.vala new file mode 100644 index 0000000000..1e72767898 --- /dev/null +++ b/src/libvaladoc/gtkdocmarkupwriter.vala @@ -0,0 +1,73 @@ +/* gtkdocmarkupwriter.vala + * + * Copyright (C) 2012 Florian Brosch + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Florian Brosch <[email protected]> + */ + + + +public class Valadoc.GtkDocMarkupWriter : Valadoc.MarkupWriter { + private unowned StringBuilder builder; + + public void reset () { + last_was_tag = true; + current_column = 0; + builder.erase (); + indent = -1; + } + + public unowned string content { + get { return builder.str; } + } + + public GtkDocMarkupWriter () { + StringBuilder builder = new StringBuilder (); + base ((str) => { builder.append (str); }, false); + this.builder = builder; + } + + protected override bool inline_element (string name) { + return name != "para" + && name != "programlisting" + && name != "table" + && name != "example" + && name != "figure" + && name != "tr" + && name != "td" + && name != "mediaobject" + && name != "imageobject" + && name != "textobject" + && name != "listitem" + && name != "orderedlist" + && name != "itemizedlist" + && name != "title"; + } + + protected override bool content_inline_element (string name) { + return name == "para" + || name == "programlisting" + || name == "emphasis" + || name == "blockquote" + || name == "ulink" + || name == "listitem" + || name == "title"; + } +} + + diff --git a/src/libvaladoc/gtkdocrenderer.vala b/src/libvaladoc/gtkdocrenderer.vala new file mode 100644 index 0000000000..a0c315627e --- /dev/null +++ b/src/libvaladoc/gtkdocrenderer.vala @@ -0,0 +1,470 @@ +/* gtkdocrenderer.vala + * + * Copyright (C) 2011 Florian Brosch + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Florian Brosch <[email protected]> + */ + +using GLib; +using Valadoc.Content; + +public class Valadoc.GtkdocRenderer : ContentRenderer { + private GtkDocMarkupWriter writer = new GtkDocMarkupWriter (); + protected Settings settings; + private bool separated; + + private string? get_cname (Api.Item item) { + if (item is Api.Method) { + return ((Api.Method)item).get_cname (); + } else if (item is Api.FormalParameter) { + return ((Api.FormalParameter)item).name; + } else if (item is Api.Constant) { + return ((Api.Constant)item).get_cname (); + } else if (item is Api.Property) { + return ((Api.Property)item).get_cname (); + } else if (item is Api.Signal) { + var name = ((Api.Signal)item).get_cname (); + return name.replace ("_", "-"); + } else if (item is Api.Class) { + return ((Api.Class)item).get_cname (); + } else if (item is Api.Struct) { + return ((Api.Struct)item).get_cname (); + } else if (item is Api.Interface) { + return ((Api.Interface)item).get_cname (); + } else if (item is Api.ErrorDomain) { + return ((Api.ErrorDomain)item).get_cname (); + } else if (item is Api.ErrorCode) { + return ((Api.ErrorCode)item).get_cname (); + } else if (item is Api.Delegate) { + return ((Api.Delegate)item).get_cname (); + } else if (item is Api.Enum) { + return ((Api.Enum)item).get_cname (); + } else if (item is Api.EnumValue) { + return ((Api.EnumValue)item).get_cname (); + } + + return null; + } + + public void write_docbook_link (Api.Item item) { + if (item is Api.Method) { + writer.start_tag ("function").text (((Api.Method)item).get_cname ()).end_tag ("function"); + } else if (item is Api.FormalParameter) { + writer.start_tag ("parameter").text (((Api.FormalParameter)item).name ?? "...").end_tag ("parameter"); + } else if (item is Api.Constant) { + writer.start_tag ("constant").text (((Api.Constant)item).get_cname ()).end_tag ("constant"); + } else if (item is Api.Property) { + // TODO: use docbook-tags instead + writer.text ("#").text (get_cname(item.parent)).text (":").text (((Api.Property)item).get_cname ().replace ("_", "-")); + } else if (item is Api.Signal) { + // TODO: use docbook-tags instead + writer.text ("#").text (get_cname(item.parent)).text ("::").text (((Api.Signal)item).get_cname ().replace ("_", "-")); + } else if (item is Api.Namespace) { + writer.text (((Api.Namespace) item).get_full_name ()); + } else { + writer.start_tag ("type").text (get_cname (item)).end_tag ("type"); + } + } + + public GtkdocRenderer () { + } + + public override void render (ContentElement element) { + reset (); + element.accept (this); + } + + public void render_symbol (Content.Comment? documentation) { + render (documentation); + + append_exceptions (documentation.find_taglets (null, typeof(Taglets.Throws))); + append_see (documentation.find_taglets (null, typeof(Taglets.See))); + append_since (documentation.find_taglets (null, typeof(Taglets.Since))); + append_deprecated (documentation.find_taglets (null, typeof(Taglets.Deprecated))); + } + + public override void render_children (ContentElement element) { + reset (); + element.accept_children (this); + } + + private void reset () { + separated = false; + writer.reset (); + } + + public unowned string content { + get { + if (writer.content.has_prefix ("\n")) { + return writer.content.next_char (); + } + + return writer.content; + } + } + + public override void visit_comment (Comment element) { + element.accept_children (this); + } + + public override void visit_embedded (Embedded element) { + writer.start_tag ("figure"); + if (element.caption != null) { + writer.start_tag ("title").text (element.caption).end_tag ("title"); + } + + writer.start_tag ("mediaobject"); + + writer.start_tag ("imageobject").simple_tag ("imagedata", {"fileref", element.url}).end_tag ("imageobject"); + + if (element.caption != null) { + writer.start_tag ("textobject").start_tag ("phrase").text (element.caption).end_tag ("phrase").end_tag ("textobject"); + } + + writer.end_tag ("mediaobject"); + writer.end_tag ("figure"); + } + + public override void visit_headline (Headline element) { + assert_not_reached (); + } + + public override void visit_wiki_link (WikiLink element) { + // wiki pages are not supported by gir + if (element.content.size > 0) { + element.accept_children (this); + } else { + write_string (element.name); + } + } + + public override void visit_link (Link element) { + writer.start_tag ("ulink", {"url", element.url}); + element.accept_children (this); + writer.end_tag ("ulink"); + } + + public override void visit_symbol_link (SymbolLink element) { + if (element.symbol == null) { + writer.text (element.label); + } else { + write_docbook_link (element.symbol); + } + } + + public override void visit_list (Content.List element) { + string tag = "orderedlist"; + switch (element.bullet) { + case Content.List.Bullet.NONE: + writer.start_tag ("itemizedlist", {"mark", "none"}); + tag = "itemizedlist"; + break; + + case Content.List.Bullet.UNORDERED: + writer.start_tag ("itemizedlist"); + tag = "itemizedlist"; + break; + + case Content.List.Bullet.ORDERED: + writer.start_tag ("orderedlist"); + break; + + case Content.List.Bullet.ORDERED_NUMBER: + writer.start_tag ("orderedlist", {"numeration", "arabic"}); + break; + + case Content.List.Bullet.ORDERED_LOWER_CASE_ALPHA: + writer.start_tag ("orderedlist", {"numeration", "loweralpha"}); + break; + + case Content.List.Bullet.ORDERED_UPPER_CASE_ALPHA: + writer.start_tag ("orderedlist", {"numeration", "upperalpha"}); + break; + + case Content.List.Bullet.ORDERED_LOWER_CASE_ROMAN: + writer.start_tag ("orderedlist", {"numeration", "lowerroman"}); + break; + + case Content.List.Bullet.ORDERED_UPPER_CASE_ROMAN: + writer.start_tag ("orderedlist", {"numeration", "upperroman"}); + break; + + default: + assert_not_reached (); + } + + element.accept_children (this); + + writer.end_tag (tag); + } + + public override void visit_list_item (ListItem element) { + writer.start_tag ("listitem"); + element.accept_children (this); + writer.end_tag ("listitem"); + } + + public override void visit_page (Page element) { + element.accept_children (this); + } + + public override void visit_paragraph (Paragraph element) { + writer.start_tag ("para"); + element.accept_children (this); + writer.end_tag ("para"); + } + + public override void visit_warning (Warning element) { + writer.start_tag ("warning"); + element.accept_children (this); + writer.end_tag ("warning"); + } + + public override void visit_note (Note element) { + writer.start_tag ("note"); + element.accept_children (this); + writer.end_tag ("note"); + } + + public override void visit_run (Run element) { + string? tag = null; + + switch (element.style) { + case Run.Style.BOLD: + writer.start_tag ("emphasis", {"role", "bold"}); + tag = "emphasis"; + break; + + case Run.Style.ITALIC: + writer.start_tag ("emphasis"); + tag = "emphasis"; + break; + + case Run.Style.UNDERLINED: + writer.start_tag ("emphasis", {"role", "underline"}); + tag = "emphasis"; + break; + + case Run.Style.MONOSPACED: + writer.start_tag ("blockquote"); + tag = "blockquote"; + break; + } + + element.accept_children (this); + + if (tag != null) { + writer.end_tag (tag); + } + } + + public override void visit_source_code (SourceCode element) { + writer.start_tag ("example").start_tag ("programlisting"); + writer.text (element.code); + writer.end_tag ("programlisting").end_tag ("example"); + } + + public override void visit_table (Table element) { + writer.start_tag ("table", {"align", "center"}); + element.accept_children (this); + writer.end_tag ("table"); + } + + public override void visit_table_cell (TableCell element) { + writer.start_tag ("td", {"colspan", element.colspan.to_string (), "rowspan", element.rowspan.to_string ()}); + element.accept_children (this); + writer.end_tag ("td"); + } + + public override void visit_table_row (TableRow element) { + writer.start_tag ("tr"); + element.accept_children (this); + writer.end_tag ("tr"); + } + + public override void visit_text (Text element) { + write_string (element.content); + } + + private void write_string (string content) { + unichar chr = content[0]; + long lpos = 0; + int i = 0; + + for (i = 0; chr != '\0' ; i++, chr = content[i]) { + switch (chr) { + case '#': + writer.text (content.substring (lpos, i-lpos)); + writer.simple_tag ("&num;"); + lpos = i+1; + break; + case '%': + writer.text (content.substring (lpos, i-lpos)); + writer.simple_tag ("&percnt;"); + lpos = i+1; + break; + case '@': + writer.text (content.substring (lpos, i-lpos)); + writer.simple_tag ("&commat;"); + lpos = i+1; + break; + case '(': + writer.text (content.substring (lpos, i-lpos)); + writer.simple_tag ("&lpar;"); + lpos = i+1; + break; + case ')': + writer.text (content.substring (lpos, i-lpos)); + writer.simple_tag ("&rpar;"); + lpos = i+1; + break; + case '"': + writer.text (content.substring (lpos, i-lpos)); + writer.simple_tag ("&quot;"); + lpos = i+1; + break; + case '\n': + writer.text (content.substring (lpos, i-lpos)); + writer.simple_tag ("br"); + lpos = i+1; + break; + case '<': + writer.text (content.substring (lpos, i-lpos)); + writer.text ("&lt;"); + lpos = i+1; + break; + case '>': + writer.text (content.substring (lpos, i-lpos)); + writer.text ("&gt;"); + lpos = i+1; + break; + case '&': + writer.text (content.substring (lpos, i-lpos)); + writer.text ("&amp;"); + lpos = i+1; + break; + } + } + writer.text (content.substring (lpos, i-lpos)); + } + + public void append_since (Gee.List<Content.Taglet> taglets) { + foreach (Content.Taglet _taglet in taglets) { + Taglets.Since taglet = _taglet as Taglets.Since; + if (taglet == null || taglet.version == null) { + // ignore unexpected taglets + continue ; + } + + if (separated == false) { + writer.text ("\n"); + } + + writer.set_wrap (false); + writer.text ("\nSince: ").text (taglet.version); + writer.set_wrap (true); + separated = true; + + // ignore multiple occurrences + return ; + } + } + + public void append_deprecated (Gee.List<Content.Taglet> taglets) { + foreach (Content.Taglet _taglet in taglets) { + Taglets.Deprecated taglet = _taglet as Taglets.Deprecated; + if (taglet == null) { + // ignore unexpected taglets + continue ; + } + + if (separated == false) { + writer.text ("\n"); + } + + writer.set_wrap (false); + writer.text ("\nDeprecated: "); + taglet.accept_children (this); + writer.text (": "); + separated = true; + writer.set_wrap (true); + + // ignore multiple occurrences + return ; + } + } + + public void append_see (Gee.List<Content.Taglet> taglets) { + bool first = true; + foreach (Content.Taglet _taglet in taglets) { + Taglets.See taglet = _taglet as Taglets.See; + if (taglet == null || taglet.symbol == null) { + // ignore unexpected taglets + continue ; + } + + if (first) { + writer.start_tag ("para").text ("See also: "); + } else { + writer.text (", "); + } + + write_docbook_link (taglet.symbol); + first = false; + } + + if (first == false) { + writer.end_tag ("para"); + } + } + + public void append_exceptions (Gee.List<Content.Taglet> taglets) { + bool first = true; + foreach (Content.Taglet _taglet in taglets) { + Taglets.Throws taglet = _taglet as Taglets.Throws; + if (taglet == null || taglet.error_domain == null) { + // ignore unexpected taglets + continue ; + } + + if (first) { + writer.start_tag ("para").text ("This function may throw:").end_tag ("para"); + writer.start_tag ("table"); + } + + writer.start_tag ("tr"); + + writer.start_tag ("td"); + write_docbook_link (taglet.error_domain); + writer.end_tag ("td"); + + writer.start_tag ("td"); + taglet.accept_children (this); + writer.end_tag ("td"); + + writer.end_tag ("tr"); + + first = false; + } + + if (first == false) { + writer.end_tag ("table"); + } + } +} + diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala index c6148ae6db..22353804d8 100755 --- a/src/libvaladoc/html/htmlrenderer.vala +++ b/src/libvaladoc/html/htmlrenderer.vala @@ -344,9 +344,9 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer { private void visit_notification_block (BlockContent element, string headline) { writer.start_tag ("div", {"class", "main_notification_block"}); writer.start_tag ("span", {"class", "main_block_headline"}).text (headline).end_tag ("span").text (" "); - writer.start_tag ("span", {"class", "main_block_content"}); + writer.start_tag ("div", {"class", "main_block_content"}); element.accept_children (this); - writer.end_tag ("span"); + writer.end_tag ("div"); writer.end_tag ("div"); } diff --git a/src/libvaladoc/markupwriter.vala b/src/libvaladoc/markupwriter.vala index 02a42cfd4b..7472d02638 100755 --- a/src/libvaladoc/markupwriter.vala +++ b/src/libvaladoc/markupwriter.vala @@ -25,22 +25,70 @@ * Writes markups and text to a file. */ public class Valadoc.MarkupWriter { - protected unowned FileStream stream; + protected WriteFunc write; protected int indent; - private long current_column = 0; - private bool last_was_tag; + + protected long current_column = 0; + protected bool last_was_tag; private bool wrap = true; + public static string escape (string txt) { + StringBuilder builder = new StringBuilder (); + unowned string start = txt; + unowned string pos; + unichar c; + + for (pos = txt; (c = pos.get_char ()) != '\0' ; pos = pos.next_char ()) { + switch (c) { + case '"': + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + builder.append ("&quot;"); + start = pos.next_char (); + break; + + case '<': + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + builder.append ("&lt;"); + start = pos.next_char (); + break; + + case '>': + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + builder.append ("&gt;"); + start = pos.next_char (); + break; + + case '&': + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + builder.append ("&amp;"); + start = pos.next_char (); + break; + } + } + + if (&txt == &start) { + return txt; + } else { + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + return (owned) builder.str; + } + } + + /** + * Writes text to a desination like a {@link StringBuilder} or a {@link FileStream} + */ + public delegate void WriteFunc (string text); + private const int MAX_COLUMN = 150; /** * Initializes a new instance of the MarkupWriter * - * @param stream a file stream + * @param stream a WriteFunc * @param xml_delcaration specifies whether this file starts with an xml-declaration */ - public MarkupWriter (FileStream stream, bool xml_declaration = true) { - this.stream = stream; + public MarkupWriter (owned WriteFunc write, bool xml_declaration = true) { + this.write = (owned) write; if (xml_declaration) { do_write ("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); } @@ -180,8 +228,8 @@ public class Valadoc.MarkupWriter { } private void break_line () { - stream.printf ("\n"); - stream.printf (string.nfill (indent * 2, ' ')); + write ("\n"); + write (string.nfill (indent * 2, ' ')); current_column = indent * 2; } @@ -189,14 +237,14 @@ public class Valadoc.MarkupWriter { if (wrap && current_column + text.length > MAX_COLUMN) { break_line (); } - stream.printf (text); + write (text); current_column += text.length; } private void check_column (string name, bool end_tag = false) { if (!wrap) { return; - } else if (!end_tag && inline_element (name) && !last_was_tag) { + } else if (!end_tag && inline_element (name) /*&& !last_was_tag*/) { return; } else if (end_tag && content_inline_element (name)) { return; diff --git a/src/libvaladoc/settings.vala b/src/libvaladoc/settings.vala index 5237fabc43..afbdbfd796 100755 --- a/src/libvaladoc/settings.vala +++ b/src/libvaladoc/settings.vala @@ -126,6 +126,15 @@ public class Valadoc.Settings : Object { */ public string[] source_files; + /** + * GObject-Introspection directory + */ + public string? gir_directory; + + /** + * GObject-Introspection repository file name + */ + public string? gir_name; /** * A list of all metadata directories @@ -136,6 +145,10 @@ public class Valadoc.Settings : Object { * A list of all gir directories. */ public string[] gir_directories; + + public string gir_namespace; + + public string gir_version; } diff --git a/src/valadoc/valadoc.vala b/src/valadoc/valadoc.vala index de99f429b1..e284e4483c 100755 --- a/src/valadoc/valadoc.vala +++ b/src/valadoc/valadoc.vala @@ -35,8 +35,12 @@ public class ValaDoc : Object { private static string docletpath = null; [CCode (array_length = false, array_null_terminated = true)] private static string[] pluginargs; + private static string gir_directory = null; private static string directory = null; private static string pkg_name = null; + private static string gir_name = null; + private static string gir_namespace = null; + private static string gir_version = null; private static string driverpath = null; private static bool add_inherited = false; @@ -102,6 +106,7 @@ public class ValaDoc : Object { { "package-name", 0, 0, OptionArg.STRING, ref pkg_name, "package name", "NAME" }, { "package-version", 0, 0, OptionArg.STRING, ref pkg_version, "package version", "VERSION" }, + { "gir", 0, 0, OptionArg.STRING, ref gir_name, "GObject-Introspection repository file name", "NAME-VERSION.gir" }, { "version", 0, 0, OptionArg.NONE, ref version, "Display version number", null }, @@ -302,6 +307,15 @@ public class ValaDoc : Object { // settings: var settings = new Valadoc.Settings (); settings.pkg_name = this.get_pkg_name (); + settings.gir_namespace = this.gir_namespace; + settings.gir_version = this.gir_version; + if (this.gir_name != null) { + settings.gir_name = GLib.Path.get_basename (this.gir_name); + settings.gir_directory = GLib.Path.get_dirname (this.gir_name); + if (settings.gir_directory == "") { + settings.gir_directory = GLib.Path.get_dirname (this.directory); + } + } settings.pkg_version = this.pkg_version; settings.add_inherited = this.add_inherited; settings._protected = this._protected; @@ -368,6 +382,13 @@ public class ValaDoc : Object { return quit (reporter); } + if (this.gir_name != null) { + driver.write_gir (settings, reporter); + if (reporter.errors > 0) { + return quit (reporter); + } + } + modules.doclet.process (settings, doctree, reporter); return quit (reporter); } @@ -421,6 +442,39 @@ public class ValaDoc : Object { } } + if (gir_name != null) { + long gir_len = gir_name.length; + int last_hyphen = gir_name.last_index_of_char ('-'); + + if (last_hyphen == -1 || !gir_name.has_suffix (".gir")) { + reporter.simple_error ("GIR file name `%s' is not well-formed, expected NAME-VERSION.gir", gir_name); + return quit (reporter); + } + + gir_namespace = gir_name.substring (0, last_hyphen); + gir_version = gir_name.substring (last_hyphen + 1, gir_len - last_hyphen - 5); + gir_version.canon ("0123456789.", '?'); + + if (gir_namespace == "" || gir_version == "" || !gir_version[0].isdigit () || gir_version.contains ("?")) { + reporter.simple_error ("GIR file name `%s' is not well-formed, expected NAME-VERSION.gir", gir_name); + return quit (reporter); + } + + + bool report_warning = true; + foreach (string source in tsources) { + if (source.has_suffix (".vala") || source.has_suffix (".gs")) { + report_warning = false; + break; + } + } + + if (report_warning == true) { + reporter.simple_error ("No source file specified to be compiled to gir."); + return quit (reporter); + } + } + var valadoc = new ValaDoc( ); return valadoc.run (reporter); }
74066765bb8ca85864f75bde6091f96207f988cf
hbase
HBASE-2889 Tool to look at HLogs -- parse and- tail -f; added part 1
a
https://github.com/apache/hbase
diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java b/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java index e32b9816a6b6..a06bd13d8da7 100644 --- a/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java @@ -1869,7 +1869,7 @@ public static void main(String[] args) throws IOException { split(conf, logPath); } } catch (Throwable t) { - t.printStackTrace(); + t.printStackTrace(System.err); System.exit(-1); } }
0856882d2ae0c8aade443918377ea2de8c3db486
hadoop
svn merge -c 1379565 FIXES: YARN-66. aggregated- logs permissions not set properly (tgraves via bobby)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1379567 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 d542069b04bd7..3515ae06c5659 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -78,3 +78,5 @@ Release 0.23.3 - Unreleased YARN-60. Fixed a bug in ResourceManager which causes all NMs to get NPEs and thus causes all containers to be rejected. (vinodkv) + + YARN-66. aggregated logs permissions not set properly (tgraves via bobby) diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java index 407fc9ca26e07..008324f013a10 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java @@ -48,6 +48,7 @@ import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.file.tfile.TFile; import org.apache.hadoop.security.UserGroupInformation; @@ -68,6 +69,13 @@ public class AggregatedLogFormat { //Maybe write out a list of containerLogs skipped by the retention policy. private static final int VERSION = 1; + /** + * Umask for the log file. + */ + private static final FsPermission APP_LOG_FILE_UMASK = FsPermission + .createImmutable((short) (0640 ^ 0777)); + + static { RESERVED_KEYS = new HashMap<String, AggregatedLogFormat.LogKey>(); RESERVED_KEYS.put(APPLICATION_ACL_KEY.toString(), APPLICATION_ACL_KEY); @@ -194,7 +202,9 @@ public LogWriter(final Configuration conf, final Path remoteAppLogFile, userUgi.doAs(new PrivilegedExceptionAction<FSDataOutputStream>() { @Override public FSDataOutputStream run() throws Exception { - return FileContext.getFileContext(conf).create( + FileContext fc = FileContext.getFileContext(conf); + fc.setUMask(APP_LOG_FILE_UMASK); + return fc.create( remoteAppLogFile, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), new Options.CreateOpts[] {}); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java index ea8c8f79c5fa5..de755a721564e 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java @@ -32,7 +32,9 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ContainerId; @@ -100,6 +102,11 @@ public void testReadAcontainerLogs1() throws Exception { logWriter.append(logKey, logValue); logWriter.closeWriter(); + // make sure permission are correct on the file + FileStatus fsStatus = fs.getFileStatus(remoteAppLogFile); + Assert.assertEquals("permissions on log aggregation file are wrong", + FsPermission.createImmutable((short) 0640), fsStatus.getPermission()); + LogReader logReader = new LogReader(conf, remoteAppLogFile); LogKey rLogKey = new LogKey(); DataInputStream dis = logReader.next(rLogKey); @@ -123,6 +130,7 @@ public void testReadAcontainerLogs1() throws Exception { Assert.assertEquals(expectedLength, s.length()); } + private void writeSrcFile(Path srcFilePath, String fileName, long length) throws IOException {
c9f93205fe8332d7b47affd53ef856abff12d64c
Vala
gnome-vfs-2.0: fix ownership and type arguments on several methods
c
https://github.com/GNOME/vala/
diff --git a/vapi/gnome-vfs-2.0.vapi b/vapi/gnome-vfs-2.0.vapi index ffa60ce846..25d8f07ea0 100644 --- a/vapi/gnome-vfs-2.0.vapi +++ b/vapi/gnome-vfs-2.0.vapi @@ -127,7 +127,7 @@ namespace GnomeVFS { public unowned string get_icon (); public ulong get_id (); public unowned GnomeVFS.Volume get_mounted_volume (); - public unowned GLib.List get_mounted_volumes (); + public GLib.List<GnomeVFS.Volume> get_mounted_volumes (); public bool is_connected (); public bool is_mounted (); public bool is_user_visible (); @@ -527,10 +527,10 @@ namespace GnomeVFS { } [CCode (type_check_function = "GNOME_IS_VFS_VOLUME_MONITOR", cheader_filename = "libgnomevfs/gnome-vfs.h")] public class VolumeMonitor : GLib.Object { - public unowned GLib.List get_connected_drives (); + public GLib.List<GnomeVFS.Drive> get_connected_drives (); public unowned GnomeVFS.Drive get_drive_by_id (ulong id); public unowned GLib.List get_mounted_volumes (); - public unowned GnomeVFS.Volume get_volume_by_id (ulong id); + public GnomeVFS.Volume get_volume_by_id (ulong id); public unowned GnomeVFS.Volume get_volume_for_path (string path); public unowned GnomeVFS.VolumeMonitor @ref (); public void unref (); diff --git a/vapi/packages/gnome-vfs-2.0/gnome-vfs-2.0.metadata b/vapi/packages/gnome-vfs-2.0/gnome-vfs-2.0.metadata index 0c552a9c9c..26165b8e05 100644 --- a/vapi/packages/gnome-vfs-2.0/gnome-vfs-2.0.metadata +++ b/vapi/packages/gnome-vfs-2.0/gnome-vfs-2.0.metadata @@ -1,6 +1,7 @@ GnomeVFS cheader_filename="libgnomevfs/gnome-vfs.h" gnome_vfs_address_new_from_sockaddr hidden="1" GnomeVFSDrive type_check_function="GNOME_IS_VFS_DRIVE" +gnome_vfs_drive_get_mounted_volumes transfer_ownership="1" type_arguments="Volume" GnomeVFSFileInfo.device hidden="1" GnomeVFSFileSize hidden="1" GnomeVFSMimeApplication cheader_filename="libgnomevfs/gnome-vfs-mime-handlers.h" @@ -9,6 +10,8 @@ GnomeVFSMimeApplication.requires_terminal hidden="1" gnome_vfs_mime_application_copy transfer_ownership="1" GnomeVFSVolume type_check_function="GNOME_IS_VFS_VOLUME" GnomeVFSVolumeMonitor type_check_function="GNOME_IS_VFS_VOLUME_MONITOR" +gnome_vfs_volume_monitor_get_connected_drives transfer_ownership="1" type_arguments="Drive" +gnome_vfs_volume_monitor_get_volume_by_id transfer_ownership="1" gnome_vfs_async_xfer.update_callback_data hidden="1" gnome_vfs_async_xfer.progress_sync_callback nullable="1" gnome_vfs_async_xfer.sync_callback_data hidden="1"
c3885bf7e7db0720fa884618e5d8f60ce3a6ef9d
Vala
Do not add extra argument to unref functions Fixes bug 615481.
c
https://github.com/GNOME/vala/
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala index dc558c7303..48d859faf6 100644 --- a/codegen/valaccodebasemodule.vala +++ b/codegen/valaccodebasemodule.vala @@ -2945,10 +2945,11 @@ public class Vala.CCodeBaseModule : CCodeModule { var ccomma = new CCodeCommaExpression (); if (context.profile == Profile.GOBJECT) { - if (type.data_type == gstringbuilder_type - || type.data_type == garray_type - || type.data_type == gbytearray_type - || type.data_type == gptrarray_type) { + if (type.data_type != null && !type.data_type.is_reference_counting () && + (type.data_type == gstringbuilder_type + || type.data_type == garray_type + || type.data_type == gbytearray_type + || type.data_type == gptrarray_type)) { ccall.add_argument (new CCodeConstant ("TRUE")); } else if (type.data_type == gthreadpool_type) { ccall.add_argument (new CCodeConstant ("FALSE"));
f932807d5c49548c1bbbdc6df1e949fe196e6cc5
tapiji
adds the plug-ins and
a
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.tools.core.ui/.classpath b/org.eclipselabs.tapiji.tools.core.ui/.classpath new file mode 100644 index 00000000..8a8f1668 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core.ui/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/org.eclipselabs.tapiji.tools.core.ui/.project b/org.eclipselabs.tapiji.tools.core.ui/.project new file mode 100644 index 00000000..a0f892f4 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core.ui/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipselabs.tapiji.tools.core.ui</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipselabs.tapiji.tools.core.ui/.settings/org.eclipse.jdt.core.prefs b/org.eclipselabs.tapiji.tools.core.ui/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..8fba0220 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core.ui/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Mar 16 22:52:15 CET 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF new file mode 100644 index 00000000..719731b9 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF @@ -0,0 +1,33 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Ui +Bundle-SymbolicName: org.eclipselabs.tapiji.tools.core.ui;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.eclipselabs.tapiji.tools.core.ui.Activator +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.jdt.ui;bundle-version="3.6.2", + org.eclipselabs.tapiji.tools.core;bundle-version="0.0.2";visibility:=reexport, + org.eclipse.ui.ide;bundle-version="3.6.2", + org.eclipse.jface.text;bundle-version="3.6.1", + org.eclipse.jdt.core;bundle-version="3.6.2", + org.eclipse.core.resources;bundle-version="3.6.1" +Bundle-ActivationPolicy: lazy +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Export-Package: org.eclipselabs.tapiji.tools.core.ui, + org.eclipselabs.tapiji.tools.core.ui.decorators, + org.eclipselabs.tapiji.tools.core.ui.dialogs, + org.eclipselabs.tapiji.tools.core.ui.filters, + org.eclipselabs.tapiji.tools.core.ui.markers, + org.eclipselabs.tapiji.tools.core.ui.menus, + org.eclipselabs.tapiji.tools.core.ui.prefrences, + org.eclipselabs.tapiji.tools.core.ui.quickfix, + org.eclipselabs.tapiji.tools.core.ui.views.messagesview, + org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd, + org.eclipselabs.tapiji.tools.core.ui.widgets, + org.eclipselabs.tapiji.tools.core.ui.widgets.event, + org.eclipselabs.tapiji.tools.core.ui.widgets.filter, + org.eclipselabs.tapiji.tools.core.ui.widgets.listener, + org.eclipselabs.tapiji.tools.core.ui.widgets.provider, + org.eclipselabs.tapiji.tools.core.ui.widgets.sorter +Import-Package: org.eclipse.core.filebuffers diff --git a/org.eclipselabs.tapiji.tools.core.ui/build.properties b/org.eclipselabs.tapiji.tools.core.ui/build.properties new file mode 100644 index 00000000..6f20375d --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core.ui/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml diff --git a/org.eclipselabs.tapiji.tools.core.ui/plugin.xml b/org.eclipselabs.tapiji.tools.core.ui/plugin.xml new file mode 100644 index 00000000..88b66b2c --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core.ui/plugin.xml @@ -0,0 +1,116 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?eclipse version="3.4"?> +<plugin> + <extension + point="org.eclipse.ui.views"> + <category + id="org.eclipselabs.tapiji" + name="Internationalization"> + </category> + <view + category="org.eclipselabs.tapiji" + class="org.eclipselabs.tapiji.tools.core.ui.views.messagesview.MessagesView" + icon="icons/resourcebundle.gif" + id="org.eclipselabs.tapiji.tools.core.views.MessagesView" + name="Resource-Bundle"> + </view> + </extension> + <extension + point="org.eclipse.ui.perspectiveExtensions"> + <perspectiveExtension + targetID="org.eclipse.jdt.ui.JavaPerspective"> + <view + id="org.eclipselabs.tapiji.tools.core.views.MessagesView" + ratio="0.5" + relationship="right" + relative="org.eclipse.ui.views.TaskList"> + </view> + </perspectiveExtension> + </extension> + <extension + point="org.eclipse.ui.menus"> + <menuContribution + locationURI="popup:org.eclipse.ui.popup.any?before=additions"> + <menu + id="org.eclipselabs.tapiji.tools.core.ui.menus.Internationalization" + label="Internationalization" + tooltip="Java Internationalization assistance"> + </menu> + </menuContribution> + <menuContribution + locationURI="popup:org.eclipselabs.tapiji.tools.core.ui.menus.Internationalization?after=additions"> + <dynamic + class="org.eclipselabs.tapiji.tools.core.ui.menus.InternationalizationMenu" + id="org.eclipselabs.tapiji.tools.core.ui.menus.ExcludeResource"> + </dynamic> + </menuContribution> + </extension> + <extension + point="org.eclipse.ui.ide.markerResolution"> + <markerResolutionGenerator + class="org.eclipselabs.tapiji.tools.core.builder.ViolationResolutionGenerator" + markerType="org.eclipselabs.tapiji.tools.core.StringLiteralAuditMarker"> + </markerResolutionGenerator> + <markerResolutionGenerator + class="org.eclipselabs.tapiji.tools.core.builder.ViolationResolutionGenerator" + markerType="org.eclipselabs.tapiji.tools.core.ResourceBundleAuditMarker"> + </markerResolutionGenerator> + </extension> + <extension + point="org.eclipse.jdt.ui.javaElementFilters"> + <filter + class="org.eclipselabs.tapiji.tools.core.ui.filters.PropertiesFileFilter" + description="Filters only resource bundles" + enabled="false" + id="ResourceBundleFilter" + name="ResourceBundleFilter"> + </filter> + </extension> + <extension + point="org.eclipse.ui.decorators"> + <decorator + adaptable="true" + class="org.eclipselabs.tapiji.tools.core.ui.decorators.ExcludedResource" + id="org.eclipselabs.tapiji.tools.core.decorators.ExcludedResource" + label="Resource is excluded from Internationalization" + lightweight="false" + state="true"> + <enablement> + <and> + <objectClass + name="org.eclipse.core.resources.IResource"> + </objectClass> + <or> + <objectClass + name="org.eclipse.core.resources.IFolder"> + </objectClass> + <objectClass + name="org.eclipse.core.resources.IFile"> + </objectClass> + </or> + </and> + </enablement> + </decorator> + </extension> + <extension + point="org.eclipse.ui.preferencePages"> + <page + class="org.eclipselabs.tapiji.tools.core.ui.prefrences.TapiHomePreferencePage" + id="org.eclipselabs.tapiji.tools.core.TapiJIGeneralPrefPage" + name="TapiJI"> + </page> + <page + category="org.eclipselabs.tapiji.tools.core.TapiJIGeneralPrefPage" + class="org.eclipselabs.tapiji.tools.core.ui.prefrences.FilePreferencePage" + id="org.eclipselabs.tapiji.tools.core.FilePrefPage" + name="File Settings"> + </page> + <page + category="org.eclipselabs.tapiji.tools.core.TapiJIGeneralPrefPage" + class="org.eclipselabs.tapiji.tools.core.ui.prefrences.BuilderPreferencePage" + id="org.eclipselabs.tapiji.tools.core.BuilderPrefPage" + name="Builder Settings"> + </page> + </extension> + +</plugin> diff --git a/org.eclipselabs.tapiji.tools.core/.classpath b/org.eclipselabs.tapiji.tools.core/.classpath new file mode 100644 index 00000000..8a8f1668 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/org.eclipselabs.tapiji.tools.core/.project b/org.eclipselabs.tapiji.tools.core/.project new file mode 100644 index 00000000..cbf1d6df --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipselabs.tapiji.tools.core</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.jdt.core.prefs b/org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..a28e1c9f --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Mon Aug 23 17:53:06 CEST 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.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.core/.settings/org.eclipse.pde.core.prefs b/org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 00000000..5186f827 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,3 @@ +#Sat Jan 01 13:54:32 CET 2011 +eclipse.preferences.version=1 +resolve.requirebundle=false diff --git a/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF new file mode 100644 index 00000000..86880392 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF @@ -0,0 +1,36 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: TapiJI Tools +Bundle-SymbolicName: org.eclipselabs.tapiji.tools.core;singleton:=true +Bundle-Version: 0.0.2.qualifier +Bundle-Activator: org.eclipselabs.tapiji.tools.core.Activator +Bundle-Vendor: Vienna University of Technology +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.jdt.ui;bundle-version="3.5.2", + org.eclipse.ui.ide, + org.eclipse.jdt.core;bundle-version="3.5.2", + org.eclipse.core.resources, + org.eclipse.jface.text;bundle-version="3.5.2", + org.eclipselabs.tapiji.translator.rbe;bundle-version="0.0.2", + org.eclipse.babel.editor;bundle-version="0.8.0";visibility:=reexport +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-ActivationPolicy: lazy +Import-Package: org.eclipse.core.filebuffers, + org.eclipse.core.resources, + org.eclipse.jdt.core, + org.eclipse.jdt.core.dom, + org.eclipse.jface.text, + org.eclipse.jface.text.contentassist, + org.eclipse.ui.ide +Export-Package: org.eclipselabs.tapiji.tools.core, + org.eclipselabs.tapiji.tools.core.builder, + org.eclipselabs.tapiji.tools.core.builder.analyzer, + org.eclipselabs.tapiji.tools.core.builder.quickfix, + org.eclipselabs.tapiji.tools.core.extensions, + org.eclipselabs.tapiji.tools.core.model, + org.eclipselabs.tapiji.tools.core.model.exception, + org.eclipselabs.tapiji.tools.core.model.manager, + org.eclipselabs.tapiji.tools.core.model.preferences, + org.eclipselabs.tapiji.tools.core.model.view, + org.eclipselabs.tapiji.tools.core.util diff --git a/org.eclipselabs.tapiji.tools.core/Splash.bmp b/org.eclipselabs.tapiji.tools.core/Splash.bmp new file mode 100644 index 00000000..9283331e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/Splash.bmp differ diff --git a/org.eclipselabs.tapiji.tools.core/TapiJI.png b/org.eclipselabs.tapiji.tools.core/TapiJI.png new file mode 100644 index 00000000..3984eba6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/TapiJI.png differ diff --git a/org.eclipselabs.tapiji.tools.core/about.html b/org.eclipselabs.tapiji.tools.core/about.html new file mode 100644 index 00000000..72adbd84 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/about.html @@ -0,0 +1,16 @@ +<html> +<head> +<title>TapiJI - Tooling for agile and process integrated Java +Internationalization</title> +</head> +<body> +<p><img src="TapiJI.gif"></img> +<h3>TapiJI - Tooling for agile and process integrated Java +Internationalization</h3> +</p> +<p>Version: 0.0.1</p> +<p>Copyright (c) 2011 Stefan Strobl and Martin Reiterer 2011. All +rights reserved.<br /> +Visit http://code.google.com/a/eclipselabs.org/p/tapiji/</p> +</body> +</html> \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.core/about.ini b/org.eclipselabs.tapiji.tools.core/about.ini new file mode 100644 index 00000000..39ee76a2 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/about.ini @@ -0,0 +1,2 @@ +aboutText=%about_text +featureImage=TapiJI.png \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.core/about.mappings b/org.eclipselabs.tapiji.tools.core/about.mappings new file mode 100644 index 00000000..e69de29b diff --git a/org.eclipselabs.tapiji.tools.core/about.properties b/org.eclipselabs.tapiji.tools.core/about.properties new file mode 100644 index 00000000..81ec9222 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/about.properties @@ -0,0 +1,5 @@ +about_text=TapiJI - Tooling for agile and process integrated Java Internationalization\n\ +\n\ +Version: 0.0.1\n\ +\n\ +(c) Stefan Strobl and Martin Reiterer 2011. All rights reserved.\n\ \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.core/build.properties b/org.eclipselabs.tapiji.tools.core/build.properties new file mode 100644 index 00000000..f163057e --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/build.properties @@ -0,0 +1,48 @@ +source.. = src/,\ + schema/,\ + META-INF/,\ + icons/,\ + bin/ +output.. = bin/ +bin.includes = plugin.xml,\ + META-INF/,\ + .,\ + icons/,\ + schema/,\ + about.html,\ + about.ini,\ + about.mappings,\ + about.properties,\ + TapiJI.png,\ + Splash.bmp,\ + TapiJI.gif,\ + epl-v10.html,\ + bin/,\ + src/,\ + resourcebundle.jar +bin.excludes = icons/original/,\ + icons/photoshop/ +src.excludes = icons/original/,\ + icons/photoshop/ +src.includes = src/,\ + schema/,\ + icons/,\ + about.html,\ + about.ini,\ + about.mappings,\ + about.properties,\ + META-INF/,\ + TapiJI.png,\ + Splash.bmp,\ + TapiJI.gif,\ + plugin.xml,\ + epl-v10.html +jars.compile.order = .,\ + resourcebundle.jar +output.resourcebundle.jar = bin/ +source.resourcebundle.jar = bin/,\ + src/,\ + schema/,\ + META-INF/,\ + icons/,\ + .settings/ diff --git a/org.eclipselabs.tapiji.tools.core/epl-v10.html b/org.eclipselabs.tapiji.tools.core/epl-v10.html new file mode 100644 index 00000000..ed4b1966 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/epl-v10.html @@ -0,0 +1,328 @@ +<html xmlns:o="urn:schemas-microsoft-com:office:office" +xmlns:w="urn:schemas-microsoft-com:office:word" +xmlns="http://www.w3.org/TR/REC-html40"> + +<head> +<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> +<meta name=ProgId content=Word.Document> +<meta name=Generator content="Microsoft Word 9"> +<meta name=Originator content="Microsoft Word 9"> +<link rel=File-List +href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> +<title>Eclipse Public License - Version 1.0</title> +<!--[if gte mso 9]><xml> + <o:DocumentProperties> + <o:Revision>2</o:Revision> + <o:TotalTime>3</o:TotalTime> + <o:Created>2004-03-05T23:03:00Z</o:Created> + <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> + <o:Pages>4</o:Pages> + <o:Words>1626</o:Words> + <o:Characters>9270</o:Characters> + <o:Lines>77</o:Lines> + <o:Paragraphs>18</o:Paragraphs> + <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> + <o:Version>9.4402</o:Version> + </o:DocumentProperties> +</xml><![endif]--><!--[if gte mso 9]><xml> + <w:WordDocument> + <w:TrackRevisions/> + </w:WordDocument> +</xml><![endif]--> +<style> +<!-- + /* Font Definitions */ +@font-face + {font-family:Tahoma; + panose-1:2 11 6 4 3 5 4 4 2 4; + mso-font-charset:0; + mso-generic-font-family:swiss; + mso-font-pitch:variable; + mso-font-signature:553679495 -2147483648 8 0 66047 0;} + /* Style Definitions */ +p.MsoNormal, li.MsoNormal, div.MsoNormal + {mso-style-parent:""; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p + {margin-right:0in; + mso-margin-top-alt:auto; + mso-margin-bottom-alt:auto; + margin-left:0in; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p.BalloonText, li.BalloonText, div.BalloonText + {mso-style-name:"Balloon Text"; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:8.0pt; + font-family:Tahoma; + mso-fareast-font-family:"Times New Roman";} +@page Section1 + {size:8.5in 11.0in; + margin:1.0in 1.25in 1.0in 1.25in; + mso-header-margin:.5in; + mso-footer-margin:.5in; + mso-paper-source:0;} +div.Section1 + {page:Section1;} +--> +</style> +</head> + +<body lang=EN-US style='tab-interval:.5in'> + +<div class=Section1> + +<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> +</p> + +<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER +THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, +REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE +OF THIS AGREEMENT.</span> </p> + +<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> + +<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +in the case of the initial Contributor, the initial code and documentation +distributed under this Agreement, and<br clear=left> +b) in the case of each subsequent Contributor:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +changes to the Program, and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +additions to the Program;</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where +such changes and/or additions to the Program originate from and are distributed +by that particular Contributor. A Contribution 'originates' from a Contributor +if it was added to the Program by such Contributor itself or anyone acting on +such Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in conjunction +with the Program under their own license agreement, and (ii) are not derivative +works of the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or +entity that distributes the Program.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Licensed Patents &quot; mean patent +claims licensable by a Contributor which are necessarily infringed by the use +or sale of its Contribution alone or when combined with the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions +distributed in accordance with this Agreement.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who +receives the Program under this Agreement, including all Contributors.</span> </p> + +<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +Subject to the terms of this Agreement, each Contributor hereby grants Recipient +a non-exclusive, worldwide, royalty-free copyright license to<span +style='color:red'> </span>reproduce, prepare derivative works of, publicly +display, publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and object code +form.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free +patent license under Licensed Patents to make, use, sell, offer to sell, import +and otherwise transfer the Contribution of such Contributor, if any, in source +code and object code form. This patent license shall apply to the combination +of the Contribution and the Program if, at the time the Contribution is added +by the Contributor, such addition of the Contribution causes such combination +to be covered by the Licensed Patents. The patent license shall not apply to +any other combinations which include the Contribution. No hardware per se is +licensed hereunder. </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c) +Recipient understands that although each Contributor grants the licenses to its +Contributions set forth herein, no assurances are provided by any Contributor +that the Program does not infringe the patent or other intellectual property +rights of any other entity. Each Contributor disclaims any liability to Recipient +for claims brought by any other entity based on infringement of intellectual +property rights or otherwise. As a condition to exercising the rights and +licenses granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For example, +if a third party patent license is required to allow Recipient to distribute +the Program, it is Recipient's responsibility to acquire that license before +distributing the Program.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d) +Each Contributor represents that to its knowledge it has sufficient copyright +rights in its Contribution, if any, to grant the copyright license set forth in +this Agreement. </span></p> + +<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> + +<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the +Program in object code form under its own license agreement, provided that:</span> +</p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it complies with the terms and conditions of this Agreement; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +its license agreement:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +effectively excludes on behalf of all Contributors all liability for damages, +including direct, indirect, special, incidental and consequential damages, such +as lost profits; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) +states that any provisions which differ from this Agreement are offered by that +Contributor alone and not by any other party; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv) +states that source code for the Program is available from such Contributor, and +informs licensees how to obtain it in a reasonable manner on or through a +medium customarily used for software exchange.<span style='color:blue'> </span></span></p> + +<p><span style='font-size:10.0pt'>When the Program is made available in source +code form:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it must be made available under this Agreement; and </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a +copy of this Agreement must be included with each copy of the Program. </span></p> + +<p><span style='font-size:10.0pt'>Contributors may not remove or alter any +copyright notices contained within the Program. </span></p> + +<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the +originator of its Contribution, if any, in a manner that reasonably allows +subsequent Recipients to identify the originator of the Contribution. </span></p> + +<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> + +<p><span style='font-size:10.0pt'>Commercial distributors of software may +accept certain responsibilities with respect to end users, business partners +and the like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes the +Program in a commercial product offering, such Contributor (&quot;Commercial +Contributor&quot;) hereby agrees to defend and indemnify every other +Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and +costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to +the extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may participate +in any such claim at its own expense.</span> </p> + +<p><span style='font-size:10.0pt'>For example, a Contributor might include the +Program in a commercial product offering, Product X. That Contributor is then a +Commercial Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance claims and +warranties are such Commercial Contributor's responsibility alone. Under this +section, the Commercial Contributor would have to defend claims against the +other Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages.</span> </p> + +<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, +WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and distributing the +Program and assumes all risks associated with its exercise of rights under this +Agreement , including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs or +equipment, and unavailability or interruption of operations. </span></p> + +<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF +THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES.</span> </p> + +<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> + +<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid +or unenforceable under applicable law, it shall not affect the validity or +enforceability of the remainder of the terms of this Agreement, and without +further action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable.</span> </p> + +<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Program itself (excluding combinations of the Program with +other software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the date +such litigation is filed. </span></p> + +<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement +shall terminate if it fails to comply with any of the material terms or +conditions of this Agreement and does not cure such failure in a reasonable +period of time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive. </span></p> + +<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute +copies of this Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The Agreement +Steward reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the initial +Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved.</span> </p> + +<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the +State of New York and the intellectual property laws of the United States of +America. No party to this Agreement will bring a legal action under this +Agreement more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation.</span> </p> + +<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> + +</div> + +</body> + +</html> \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.core/icons/Folder.png b/org.eclipselabs.tapiji.tools.core/icons/Folder.png new file mode 100644 index 00000000..a699bfc6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/Folder.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/Glossary.psd b/org.eclipselabs.tapiji.tools.core/icons/Glossary.psd new file mode 100644 index 00000000..9da95ac3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/Glossary.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/NewGlossary.png b/org.eclipselabs.tapiji.tools.core/icons/NewGlossary.png new file mode 100644 index 00000000..ac91bf14 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/NewGlossary.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary.png b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary.png new file mode 100644 index 00000000..85917f41 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary2.png b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary2.png new file mode 100644 index 00000000..e02b952f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary2.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary3.png b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary3.png new file mode 100644 index 00000000..e8a0b0a4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary3.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary4.png b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary4.png new file mode 100644 index 00000000..7a2ddc74 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary4.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary5.png b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary5.png new file mode 100644 index 00000000..020c1adf Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/OpenGlossary5.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/Resource16.png b/org.eclipselabs.tapiji.tools.core/icons/Resource16.png new file mode 100644 index 00000000..1b0966cb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/Resource16.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/Resource16_small.png b/org.eclipselabs.tapiji.tools.core/icons/Resource16_small.png new file mode 100644 index 00000000..da9f603a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/Resource16_small.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/Resource16_warning_small.png b/org.eclipselabs.tapiji.tools.core/icons/Resource16_warning_small.png new file mode 100644 index 00000000..ec47a9ac Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/Resource16_warning_small.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI.png b/org.eclipselabs.tapiji.tools.core/icons/TapiJI.png new file mode 100644 index 00000000..e274c0cd Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/TapiJI.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png new file mode 100644 index 00000000..98514e0e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_128.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png new file mode 100644 index 00000000..73b82c2f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_16.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_32.png b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_32.png new file mode 100644 index 00000000..3984eba6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_32.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png new file mode 100644 index 00000000..190a92e4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_48.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png new file mode 100644 index 00000000..89988073 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/TapiJI_64.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/.cvsignore b/org.eclipselabs.tapiji.tools.core/icons/countries/.cvsignore new file mode 100644 index 00000000..f47afba9 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/icons/countries/.cvsignore @@ -0,0 +1 @@ +Thumbs.db diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/__.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/__.gif new file mode 100644 index 00000000..65167847 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/__.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/_f.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/_f.gif new file mode 100644 index 00000000..a5f340d4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/_f.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ad.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ad.gif new file mode 100644 index 00000000..0b240549 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ad.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ae.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ae.gif new file mode 100644 index 00000000..a4a82ff8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ae.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/af.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/af.gif new file mode 100644 index 00000000..70e1a15b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/af.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ag.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ag.gif new file mode 100644 index 00000000..2dc04e5e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ag.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/al.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/al.gif new file mode 100644 index 00000000..1384f59b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/al.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/am.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/am.gif new file mode 100644 index 00000000..eda901ed Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/am.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ao.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ao.gif new file mode 100644 index 00000000..56f02bbc Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ao.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/aq.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/aq.gif new file mode 100644 index 00000000..d8e99da6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/aq.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ar.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ar.gif new file mode 100644 index 00000000..0231d503 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ar.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/at.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/at.gif new file mode 100644 index 00000000..ecf48b9b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/at.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/au.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/au.gif new file mode 100644 index 00000000..77761249 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/au.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/az.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/az.gif new file mode 100644 index 00000000..bc77ff24 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/az.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ba.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ba.gif new file mode 100644 index 00000000..8e4e5499 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ba.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bb.gif new file mode 100644 index 00000000..54928a68 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bd.gif new file mode 100644 index 00000000..25890b90 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/be.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/be.gif new file mode 100644 index 00000000..f917f396 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/be.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bf.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bf.gif new file mode 100644 index 00000000..53afd44c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bf.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bg.gif new file mode 100644 index 00000000..5ce1db10 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bh.gif new file mode 100644 index 00000000..ba39230e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bi.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bi.gif new file mode 100644 index 00000000..ee3d6a48 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bi.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bj.gif new file mode 100644 index 00000000..55463ef0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/blank.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/blank.gif new file mode 100644 index 00000000..314b8633 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/blank.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bn.gif new file mode 100644 index 00000000..ed11638b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bo.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bo.gif new file mode 100644 index 00000000..f1796980 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bo.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/br.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/br.gif new file mode 100644 index 00000000..e1069e08 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/br.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bs.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bs.gif new file mode 100644 index 00000000..30c32c32 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bs.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bt.gif new file mode 100644 index 00000000..b53dddfb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bw.gif new file mode 100644 index 00000000..d73ad712 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/by.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/by.gif new file mode 100644 index 00000000..3335ae02 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/by.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/bz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/bz.gif new file mode 100644 index 00000000..ec056372 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/bz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ca.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ca.gif new file mode 100644 index 00000000..547011ac Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ca.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cd.gif new file mode 100644 index 00000000..44fa4411 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cf.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cf.gif new file mode 100644 index 00000000..41405ce0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cf.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cg.gif new file mode 100644 index 00000000..00fa29c0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ch.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ch.gif new file mode 100644 index 00000000..b0dc176e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ch.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ci.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ci.gif new file mode 100644 index 00000000..b1167c0d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ci.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cl.gif new file mode 100644 index 00000000..31dcb03e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cm.gif new file mode 100644 index 00000000..f361dbd7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cn.gif new file mode 100644 index 00000000..f12f17d1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/co.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/co.gif new file mode 100644 index 00000000..d9f14e79 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/co.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cr.gif new file mode 100644 index 00000000..2a5f0b93 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cs.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cs.gif new file mode 100644 index 00000000..580d26f5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cs.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cu.gif new file mode 100644 index 00000000..823befcc Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cv.gif new file mode 100644 index 00000000..d21a45cb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cy.gif new file mode 100644 index 00000000..1a332d90 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/cz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/cz.gif new file mode 100644 index 00000000..2faee5e1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/cz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/dd.gif new file mode 100644 index 00000000..99eda38f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/dd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/de.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/de.gif new file mode 100644 index 00000000..c7b28406 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/de.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/dj.gif new file mode 100644 index 00000000..94fc2eb3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/dj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/dk.gif new file mode 100644 index 00000000..4f01ec95 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/dk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/dm.gif new file mode 100644 index 00000000..b4fed906 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/dm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/do.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/do.gif new file mode 100644 index 00000000..85d7be8b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/do.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/dz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/dz.gif new file mode 100644 index 00000000..622ff6ba Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/dz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ec.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ec.gif new file mode 100644 index 00000000..5d1641b1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ec.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ee.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ee.gif new file mode 100644 index 00000000..c678c73c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ee.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/eg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/eg.gif new file mode 100644 index 00000000..a740c668 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/eg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/eh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/eh.gif new file mode 100644 index 00000000..6a75cc3c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/eh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/er.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/er.gif new file mode 100644 index 00000000..71297d62 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/er.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/es.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/es.gif new file mode 100644 index 00000000..6dee15c1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/es.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/et.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/et.gif new file mode 100644 index 00000000..4188e4ff Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/et.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/eu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/eu.gif new file mode 100644 index 00000000..45caabf2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/eu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fi.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/fi.gif new file mode 100644 index 00000000..b8311cac Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/fi.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/fj.gif new file mode 100644 index 00000000..f5481b79 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/fj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/fm.gif new file mode 100644 index 00000000..050eca09 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/fm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/fr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/fr.gif new file mode 100644 index 00000000..a2a2354d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/fr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ga.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ga.gif new file mode 100644 index 00000000..54fb2514 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ga.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gb.gif new file mode 100644 index 00000000..4ae2d0f8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gd.gif new file mode 100644 index 00000000..0095032c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ge.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ge.gif new file mode 100644 index 00000000..f3927c8a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ge.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gh.gif new file mode 100644 index 00000000..6d3b6142 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gm.gif new file mode 100644 index 00000000..2ecf0b0b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gn.gif new file mode 100644 index 00000000..83179352 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gq.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gq.gif new file mode 100644 index 00000000..6c2bc475 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gq.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gr.gif new file mode 100644 index 00000000..1599add4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gt.gif new file mode 100644 index 00000000..c306f25d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gw.gif new file mode 100644 index 00000000..6cba5901 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/gy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/gy.gif new file mode 100644 index 00000000..a4b4da97 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/gy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/hk.gif new file mode 100644 index 00000000..230723af Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/hk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/hn.gif new file mode 100644 index 00000000..05501572 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/hn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/hr.gif new file mode 100644 index 00000000..893778a1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/hr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ht.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ht.gif new file mode 100644 index 00000000..e5cf7803 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ht.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/hu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/hu.gif new file mode 100644 index 00000000..07778839 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/hu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/id.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/id.gif new file mode 100644 index 00000000..9fed7642 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/id.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ie.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ie.gif new file mode 100644 index 00000000..82ec5535 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ie.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/il.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/il.gif new file mode 100644 index 00000000..554a7612 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/il.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/in.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/in.gif new file mode 100644 index 00000000..430b37b9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/in.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/iq.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/iq.gif new file mode 100644 index 00000000..dae4d593 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/iq.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ir.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ir.gif new file mode 100644 index 00000000..50f5432a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ir.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/is.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/is.gif new file mode 100644 index 00000000..e9580e07 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/is.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/it.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/it.gif new file mode 100644 index 00000000..4256b464 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/it.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/jm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/jm.gif new file mode 100644 index 00000000..f1459feb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/jm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/jo.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/jo.gif new file mode 100644 index 00000000..a9d36128 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/jo.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/jp.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/jp.gif new file mode 100644 index 00000000..ddad6e3b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/jp.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ke.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ke.gif new file mode 100644 index 00000000..6e06f4a7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ke.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/kg.gif new file mode 100644 index 00000000..e47fb0f2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/kg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/kh.gif new file mode 100644 index 00000000..31f5be16 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/kh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ki.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ki.gif new file mode 100644 index 00000000..9f12bb0d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ki.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/km.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/km.gif new file mode 100644 index 00000000..027276bf Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/km.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/kn.gif new file mode 100644 index 00000000..f690875e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/kn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kp.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/kp.gif new file mode 100644 index 00000000..42584efa Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/kp.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/kr.gif new file mode 100644 index 00000000..800c6cdd Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/kr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/kw.gif new file mode 100644 index 00000000..ff083b5e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/kw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/kz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/kz.gif new file mode 100644 index 00000000..9b13afe0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/kz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/la.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/la.gif new file mode 100644 index 00000000..3c6f2f15 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/la.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/lb.gif new file mode 100644 index 00000000..f3c45527 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/lb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/lc.gif new file mode 100644 index 00000000..fdcbd97f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/lc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/li.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/li.gif new file mode 100644 index 00000000..eb9d9384 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/li.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/lk.gif new file mode 100644 index 00000000..3aa25aa8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/lk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/lr.gif new file mode 100644 index 00000000..f54468fc Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/lr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ls.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ls.gif new file mode 100644 index 00000000..c1ad8d2f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ls.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/lt.gif new file mode 100644 index 00000000..78447f07 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/lt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/lu.gif new file mode 100644 index 00000000..d74df5ab Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/lu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/lv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/lv.gif new file mode 100644 index 00000000..5f7419c6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/lv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ly.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ly.gif new file mode 100644 index 00000000..8ca9e0a0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ly.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ma.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ma.gif new file mode 100644 index 00000000..3aab8cbb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ma.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mc.gif new file mode 100644 index 00000000..c22c1717 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/md.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/md.gif new file mode 100644 index 00000000..4951b21a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/md.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mg.gif new file mode 100644 index 00000000..24281d87 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mh.gif new file mode 100644 index 00000000..c472aee6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mk.gif new file mode 100644 index 00000000..88c077fa Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ml.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ml.gif new file mode 100644 index 00000000..4eb75ae1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ml.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mm.gif new file mode 100644 index 00000000..bd378555 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mn.gif new file mode 100644 index 00000000..de3029b3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mr.gif new file mode 100644 index 00000000..d7cbb38a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mt.gif new file mode 100644 index 00000000..677969a7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mu.gif new file mode 100644 index 00000000..d102ab7e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mv.gif new file mode 100644 index 00000000..69ac6863 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mw.gif new file mode 100644 index 00000000..a0f0320b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mx.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mx.gif new file mode 100644 index 00000000..bbcb376b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mx.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/my.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/my.gif new file mode 100644 index 00000000..8874751b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/my.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/mz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/mz.gif new file mode 100644 index 00000000..b63af289 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/mz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/na.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/na.gif new file mode 100644 index 00000000..bee7072e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/na.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ne.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ne.gif new file mode 100644 index 00000000..fc1b74b8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ne.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ng.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ng.gif new file mode 100644 index 00000000..43af12c9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ng.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ni.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ni.gif new file mode 100644 index 00000000..cac0042d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ni.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/nl.gif new file mode 100644 index 00000000..c4258e62 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/nl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/no.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/no.gif new file mode 100644 index 00000000..873baca1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/no.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/np.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/np.gif new file mode 100644 index 00000000..f01f2f9e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/np.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/nr.gif new file mode 100644 index 00000000..d485c4b1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/nr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/nu.gif new file mode 100644 index 00000000..73177056 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/nu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/nz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/nz.gif new file mode 100644 index 00000000..49f8464e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/nz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/om.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/om.gif new file mode 100644 index 00000000..d90ca333 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/om.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pa.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/pa.gif new file mode 100644 index 00000000..cae5432f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/pa.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pe.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/pe.gif new file mode 100644 index 00000000..e6cc7348 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/pe.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/pg.gif new file mode 100644 index 00000000..108204f3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/pg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ph.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ph.gif new file mode 100644 index 00000000..b141cd81 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ph.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/pk.gif new file mode 100644 index 00000000..f612b977 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/pk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/pl.gif new file mode 100644 index 00000000..6ff3ba6f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/pl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ps.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ps.gif new file mode 100644 index 00000000..71717cc9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ps.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/pt.gif new file mode 100644 index 00000000..9bfc8ca4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/pt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/pw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/pw.gif new file mode 100644 index 00000000..0a520911 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/pw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/py.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/py.gif new file mode 100644 index 00000000..b52de243 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/py.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/qa.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/qa.gif new file mode 100644 index 00000000..e078e46c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/qa.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ro.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ro.gif new file mode 100644 index 00000000..6bdbad14 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ro.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ru.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ru.gif new file mode 100644 index 00000000..cf4d30c8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ru.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/rw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/rw.gif new file mode 100644 index 00000000..02cf0cb1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/rw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sa.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sa.gif new file mode 100644 index 00000000..4b7632ee Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sa.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sb.gif new file mode 100644 index 00000000..eb8acc08 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sc.gif new file mode 100644 index 00000000..4324c21f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sd.gif new file mode 100644 index 00000000..2d74f622 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/se.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/se.gif new file mode 100644 index 00000000..9bbcb1fa Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/se.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sg.gif new file mode 100644 index 00000000..b81f461e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/si.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/si.gif new file mode 100644 index 00000000..f6afb67d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/si.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sk.gif new file mode 100644 index 00000000..b0c4ab19 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sl.gif new file mode 100644 index 00000000..00d59d3b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sm.gif new file mode 100644 index 00000000..8d9d76b3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/__.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/__.gif new file mode 100644 index 00000000..e077f110 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/__.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/_f.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/_f.gif new file mode 100644 index 00000000..06c11464 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/_f.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ad.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ad.gif new file mode 100644 index 00000000..578acbb7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ad.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ae.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ae.gif new file mode 100644 index 00000000..9e6f62a1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ae.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/af.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/af.gif new file mode 100644 index 00000000..9fe39759 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/af.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ag.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ag.gif new file mode 100644 index 00000000..dff85d5f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ag.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/al.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/al.gif new file mode 100644 index 00000000..3cd0dbc6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/al.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/am.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/am.gif new file mode 100644 index 00000000..b5968d0e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/am.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ao.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ao.gif new file mode 100644 index 00000000..cf5f1bb4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ao.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/aq.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/aq.gif new file mode 100644 index 00000000..8394537d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/aq.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ar.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ar.gif new file mode 100644 index 00000000..7101d184 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ar.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/at.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/at.gif new file mode 100644 index 00000000..b302cb90 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/at.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/au.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/au.gif new file mode 100644 index 00000000..1e7d95c2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/au.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/az.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/az.gif new file mode 100644 index 00000000..02d9ee9b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/az.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ba.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ba.gif new file mode 100644 index 00000000..1007efd2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ba.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bb.gif new file mode 100644 index 00000000..29a51f96 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bd.gif new file mode 100644 index 00000000..e6f4dc5e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/be.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/be.gif new file mode 100644 index 00000000..55ec17f4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/be.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bf.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bf.gif new file mode 100644 index 00000000..fc26ebbf Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bf.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bg.gif new file mode 100644 index 00000000..04664c06 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bh.gif new file mode 100644 index 00000000..9dc18e6b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bi.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bi.gif new file mode 100644 index 00000000..6aed0376 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bi.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bj.gif new file mode 100644 index 00000000..c4d0f869 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/blank.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/blank.gif new file mode 100644 index 00000000..93f91133 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/blank.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bn.gif new file mode 100644 index 00000000..e9481fe7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bo.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bo.gif new file mode 100644 index 00000000..f083da32 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bo.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/br.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/br.gif new file mode 100644 index 00000000..b44b8570 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/br.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bs.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bs.gif new file mode 100644 index 00000000..dd013c4a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bs.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bt.gif new file mode 100644 index 00000000..c12cc451 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bw.gif new file mode 100644 index 00000000..0bd4935a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/by.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/by.gif new file mode 100644 index 00000000..495e17a1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/by.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/bz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bz.gif new file mode 100644 index 00000000..ebc5a1f2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/bz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ca.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ca.gif new file mode 100644 index 00000000..111f6b54 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ca.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cd.gif new file mode 100644 index 00000000..48a5d4b1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cf.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cf.gif new file mode 100644 index 00000000..82dfeb88 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cf.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cg.gif new file mode 100644 index 00000000..bc4ce41a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ch.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ch.gif new file mode 100644 index 00000000..c1daa8c3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ch.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ci.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ci.gif new file mode 100644 index 00000000..01ce79fb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ci.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cl.gif new file mode 100644 index 00000000..579c7377 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cm.gif new file mode 100644 index 00000000..5093f621 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cn.gif new file mode 100644 index 00000000..e0644265 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/co.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/co.gif new file mode 100644 index 00000000..ea33538a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/co.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cr.gif new file mode 100644 index 00000000..1c3175b4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cs.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cs.gif new file mode 100644 index 00000000..88b65987 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cs.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cu.gif new file mode 100644 index 00000000..33334341 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cv.gif new file mode 100644 index 00000000..9b13e53b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cy.gif new file mode 100644 index 00000000..249719a2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/cz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cz.gif new file mode 100644 index 00000000..0ae066ca Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/cz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dd.gif new file mode 100644 index 00000000..4a47e19e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/de.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/de.gif new file mode 100644 index 00000000..6cc466d3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/de.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dj.gif new file mode 100644 index 00000000..e62e277d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dk.gif new file mode 100644 index 00000000..f3803a0b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dm.gif new file mode 100644 index 00000000..69f80797 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/do.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/do.gif new file mode 100644 index 00000000..4b9a2695 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/do.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/dz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dz.gif new file mode 100644 index 00000000..e88ec913 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/dz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ec.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ec.gif new file mode 100644 index 00000000..7060478f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ec.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ee.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ee.gif new file mode 100644 index 00000000..1eb10798 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ee.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/eg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/eg.gif new file mode 100644 index 00000000..4efa2884 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/eg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/eh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/eh.gif new file mode 100644 index 00000000..9acceed3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/eh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/er.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/er.gif new file mode 100644 index 00000000..30550a36 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/er.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/es.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/es.gif new file mode 100644 index 00000000..9d01bd4d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/es.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/et.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/et.gif new file mode 100644 index 00000000..7352fcaa Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/et.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/eu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/eu.gif new file mode 100644 index 00000000..1eadf213 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/eu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fi.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fi.gif new file mode 100644 index 00000000..d61952f4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fi.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fj.gif new file mode 100644 index 00000000..2bcd330f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fm.gif new file mode 100644 index 00000000..7f5dbf18 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/fr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fr.gif new file mode 100644 index 00000000..5b9680b6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/fr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ga.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ga.gif new file mode 100644 index 00000000..10322d22 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ga.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gb.gif new file mode 100644 index 00000000..03a74145 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gd.gif new file mode 100644 index 00000000..69e2b79d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ge.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ge.gif new file mode 100644 index 00000000..daeade34 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ge.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gh.gif new file mode 100644 index 00000000..b1ee6cc8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gm.gif new file mode 100644 index 00000000..0540321d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gn.gif new file mode 100644 index 00000000..18c92115 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gq.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gq.gif new file mode 100644 index 00000000..21b35aa6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gq.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gr.gif new file mode 100644 index 00000000..e6905195 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gt.gif new file mode 100644 index 00000000..5c3d0618 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gw.gif new file mode 100644 index 00000000..5d8901f5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/gy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gy.gif new file mode 100644 index 00000000..42483db9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/gy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hk.gif new file mode 100644 index 00000000..c745c141 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hn.gif new file mode 100644 index 00000000..e43bd5e5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hr.gif new file mode 100644 index 00000000..a6f704ca Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ht.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ht.gif new file mode 100644 index 00000000..854c9698 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ht.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/hu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hu.gif new file mode 100644 index 00000000..04ddf9f4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/hu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/id.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/id.gif new file mode 100644 index 00000000..dcc678e9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/id.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ie.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ie.gif new file mode 100644 index 00000000..b82a61bf Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ie.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/il.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/il.gif new file mode 100644 index 00000000..e53b0625 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/il.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/in.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/in.gif new file mode 100644 index 00000000..929e0c25 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/in.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/iq.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/iq.gif new file mode 100644 index 00000000..f0845872 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/iq.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ir.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ir.gif new file mode 100644 index 00000000..fbfdf319 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ir.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/is.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/is.gif new file mode 100644 index 00000000..3f490ab7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/is.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/it.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/it.gif new file mode 100644 index 00000000..5bc1bb2c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/it.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/jm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/jm.gif new file mode 100644 index 00000000..6e97f20d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/jm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/jo.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/jo.gif new file mode 100644 index 00000000..8dfb7143 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/jo.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/jp.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/jp.gif new file mode 100644 index 00000000..6ecf4ff2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/jp.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ke.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ke.gif new file mode 100644 index 00000000..742aab84 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ke.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kg.gif new file mode 100644 index 00000000..88608a30 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kh.gif new file mode 100644 index 00000000..ee7ec64b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ki.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ki.gif new file mode 100644 index 00000000..5eab4ed6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ki.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/km.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/km.gif new file mode 100644 index 00000000..f529c42d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/km.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kn.gif new file mode 100644 index 00000000..20f55e9b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kp.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kp.gif new file mode 100644 index 00000000..2c99418b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kp.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kr.gif new file mode 100644 index 00000000..139cf5c8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kw.gif new file mode 100644 index 00000000..27a43e4c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/kz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kz.gif new file mode 100644 index 00000000..81cc714a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/kz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/la.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/la.gif new file mode 100644 index 00000000..86dc6af2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/la.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lb.gif new file mode 100644 index 00000000..f39803f6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lc.gif new file mode 100644 index 00000000..95f6ba69 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/li.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/li.gif new file mode 100644 index 00000000..cdfe54c6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/li.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lk.gif new file mode 100644 index 00000000..5486bf0b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lr.gif new file mode 100644 index 00000000..a70179ad Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ls.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ls.gif new file mode 100644 index 00000000..e4611d05 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ls.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lt.gif new file mode 100644 index 00000000..eca2f152 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lu.gif new file mode 100644 index 00000000..c8e2e76f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/lv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lv.gif new file mode 100644 index 00000000..8e2cabee Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/lv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ly.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ly.gif new file mode 100644 index 00000000..b31fbec6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ly.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ma.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ma.gif new file mode 100644 index 00000000..c9829260 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ma.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mc.gif new file mode 100644 index 00000000..6bd1424a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/md.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/md.gif new file mode 100644 index 00000000..a19ff5cb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/md.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mg.gif new file mode 100644 index 00000000..a0bed496 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mh.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mh.gif new file mode 100644 index 00000000..b5f879a9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mh.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mk.gif new file mode 100644 index 00000000..776a1a6b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ml.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ml.gif new file mode 100644 index 00000000..7ea931ab Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ml.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mm.gif new file mode 100644 index 00000000..2f8adbd7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mn.gif new file mode 100644 index 00000000..4d812a01 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mr.gif new file mode 100644 index 00000000..d92a4643 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mt.gif new file mode 100644 index 00000000..aa5a7298 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mu.gif new file mode 100644 index 00000000..98d3bd9a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mv.gif new file mode 100644 index 00000000..dbd75919 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mw.gif new file mode 100644 index 00000000..9ba7c7ba Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mx.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mx.gif new file mode 100644 index 00000000..e5e70bb0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mx.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/my.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/my.gif new file mode 100644 index 00000000..4bb4e268 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/my.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/mz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mz.gif new file mode 100644 index 00000000..fe3df698 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/mz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/na.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/na.gif new file mode 100644 index 00000000..e4c953a4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/na.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ne.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ne.gif new file mode 100644 index 00000000..dd616577 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ne.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ng.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ng.gif new file mode 100644 index 00000000..498b3d59 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ng.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ni.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ni.gif new file mode 100644 index 00000000..b6c8e208 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ni.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nl.gif new file mode 100644 index 00000000..9053bfc3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/no.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/no.gif new file mode 100644 index 00000000..8ca359a7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/no.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/np.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/np.gif new file mode 100644 index 00000000..d0fd2f7a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/np.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nr.gif new file mode 100644 index 00000000..d82bc57d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nu.gif new file mode 100644 index 00000000..755c1b33 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/nz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nz.gif new file mode 100644 index 00000000..2ebcec83 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/nz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/om.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/om.gif new file mode 100644 index 00000000..9984131b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/om.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pa.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pa.gif new file mode 100644 index 00000000..016a2274 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pa.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pe.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pe.gif new file mode 100644 index 00000000..b8f37c68 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pe.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pg.gif new file mode 100644 index 00000000..fffb3517 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ph.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ph.gif new file mode 100644 index 00000000..1b126944 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ph.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pk.gif new file mode 100644 index 00000000..9f5ca278 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pl.gif new file mode 100644 index 00000000..e4252c5d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ps.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ps.gif new file mode 100644 index 00000000..31d1aefd Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ps.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pt.gif new file mode 100644 index 00000000..2614c827 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/pw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pw.gif new file mode 100644 index 00000000..8da1b47b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/pw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/py.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/py.gif new file mode 100644 index 00000000..23738a4e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/py.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/qa.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/qa.gif new file mode 100644 index 00000000..b4f9f55e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/qa.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ro.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ro.gif new file mode 100644 index 00000000..94c6ade2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ro.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ru.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ru.gif new file mode 100644 index 00000000..a6e78729 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ru.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/rw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/rw.gif new file mode 100644 index 00000000..a925bee8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/rw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sa.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sa.gif new file mode 100644 index 00000000..afcb768a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sa.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sb.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sb.gif new file mode 100644 index 00000000..d2f20798 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sb.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sc.gif new file mode 100644 index 00000000..815a8cec Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sd.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sd.gif new file mode 100644 index 00000000..47b2e6a4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sd.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/se.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/se.gif new file mode 100644 index 00000000..333f7f18 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/se.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sg.gif new file mode 100644 index 00000000..ad264e45 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/si.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/si.gif new file mode 100644 index 00000000..ebc6c9b6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/si.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sk.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sk.gif new file mode 100644 index 00000000..78e654b0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sk.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sl.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sl.gif new file mode 100644 index 00000000..dacd1f09 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sl.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sm.gif new file mode 100644 index 00000000..c12e13aa Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sn.gif new file mode 100644 index 00000000..c6ffb1d1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/so.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/so.gif new file mode 100644 index 00000000..7bec9284 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/so.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sr.gif new file mode 100644 index 00000000..ba6269f9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/st.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/st.gif new file mode 100644 index 00000000..d29916f3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/st.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/su.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/su.gif new file mode 100644 index 00000000..c64c7b6b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/su.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sv.gif new file mode 100644 index 00000000..199699ea Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sy.gif new file mode 100644 index 00000000..56d81175 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/sz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sz.gif new file mode 100644 index 00000000..9a7f9aa1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/sz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/td.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/td.gif new file mode 100644 index 00000000..be3c4e49 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/td.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tg.gif new file mode 100644 index 00000000..d15557fa Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/th.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/th.gif new file mode 100644 index 00000000..f6b68f6d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/th.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tj.gif new file mode 100644 index 00000000..26c9c6a0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tm.gif new file mode 100644 index 00000000..09a0f66f Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tn.gif new file mode 100644 index 00000000..ff2ce465 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/to.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/to.gif new file mode 100644 index 00000000..eb45eaf4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/to.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tp.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tp.gif new file mode 100644 index 00000000..fd588323 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tp.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tr.gif new file mode 100644 index 00000000..a8d150a4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tt.gif new file mode 100644 index 00000000..bbf1729b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tv.gif new file mode 100644 index 00000000..df58585d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tw.gif new file mode 100644 index 00000000..01f360e5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/tz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tz.gif new file mode 100644 index 00000000..ae33cb9a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/tz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ua.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ua.gif new file mode 100644 index 00000000..1666575a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ua.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ug.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ug.gif new file mode 100644 index 00000000..6a8f9df8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ug.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/un.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/un.gif new file mode 100644 index 00000000..683897e4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/un.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/us.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/us.gif new file mode 100644 index 00000000..12739673 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/us.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/uy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/uy.gif new file mode 100644 index 00000000..2339df56 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/uy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/uz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/uz.gif new file mode 100644 index 00000000..96d13fd9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/uz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/va.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/va.gif new file mode 100644 index 00000000..2e4757ec Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/va.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/vc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/vc.gif new file mode 100644 index 00000000..5e2edfb1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/vc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ve.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ve.gif new file mode 100644 index 00000000..f4d14918 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ve.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/vn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/vn.gif new file mode 100644 index 00000000..527ab1e5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/vn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/vu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/vu.gif new file mode 100644 index 00000000..38dca348 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/vu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ws.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ws.gif new file mode 100644 index 00000000..af159f3c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ws.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ya.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ya.gif new file mode 100644 index 00000000..07bad2d4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ya.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye.gif new file mode 100644 index 00000000..b5fbb0f5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye0.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye0.gif new file mode 100644 index 00000000..aa1942ee Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/ye0.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/yu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/yu.gif new file mode 100644 index 00000000..d127d277 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/yu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/za.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/za.gif new file mode 100644 index 00000000..9554d129 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/za.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/zm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/zm.gif new file mode 100644 index 00000000..ff76b8dd Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/zm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/small/zw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/small/zw.gif new file mode 100644 index 00000000..571bac88 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/small/zw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sn.gif new file mode 100644 index 00000000..1a541741 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/so.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/so.gif new file mode 100644 index 00000000..7f1dba35 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/so.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sr.gif new file mode 100644 index 00000000..de781c13 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/st.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/st.gif new file mode 100644 index 00000000..cd9036fb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/st.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/su.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/su.gif new file mode 100644 index 00000000..23e162a1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/su.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sv.gif new file mode 100644 index 00000000..bef488e2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sy.gif new file mode 100644 index 00000000..a3a53cd4 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/sz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/sz.gif new file mode 100644 index 00000000..b3a20ba5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/sz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/td.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/td.gif new file mode 100644 index 00000000..3ccc8dff Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/td.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tg.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tg.gif new file mode 100644 index 00000000..674e68f0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tg.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/th.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/th.gif new file mode 100644 index 00000000..83318c0c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/th.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tj.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tj.gif new file mode 100644 index 00000000..1f44255c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tm.gif new file mode 100644 index 00000000..a603afd2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tn.gif new file mode 100644 index 00000000..083238da Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/to.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/to.gif new file mode 100644 index 00000000..603aa8e3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/to.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tp.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tp.gif new file mode 100644 index 00000000..40599d56 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tp.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tr.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tr.gif new file mode 100644 index 00000000..2eac7305 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tr.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tt.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tt.gif new file mode 100644 index 00000000..f7154195 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tt.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tv.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tv.gif new file mode 100644 index 00000000..9b018e87 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tv.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tw.gif new file mode 100644 index 00000000..57a04829 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/tz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/tz.gif new file mode 100644 index 00000000..6d28d408 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/tz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ua.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ua.gif new file mode 100644 index 00000000..bebd6705 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ua.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ug.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ug.gif new file mode 100644 index 00000000..151e3037 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ug.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/un.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/un.gif new file mode 100644 index 00000000..135b5281 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/un.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/us.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/us.gif new file mode 100644 index 00000000..850094ea Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/us.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/uy.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/uy.gif new file mode 100644 index 00000000..4d129fc5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/uy.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/uz.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/uz.gif new file mode 100644 index 00000000..d9cc88eb Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/uz.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/va.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/va.gif new file mode 100644 index 00000000..5db146d6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/va.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/vc.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/vc.gif new file mode 100644 index 00000000..6519018d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/vc.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ve.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ve.gif new file mode 100644 index 00000000..4abf999b Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ve.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/vn.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/vn.gif new file mode 100644 index 00000000..e7d1e5b9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/vn.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/vu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/vu.gif new file mode 100644 index 00000000..f8736a18 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/vu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ws.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ws.gif new file mode 100644 index 00000000..b2bc2f76 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ws.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ya.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ya.gif new file mode 100644 index 00000000..91536134 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ya.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ye.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ye.gif new file mode 100644 index 00000000..f183847c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ye.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/ye0.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/ye0.gif new file mode 100644 index 00000000..b9c28b30 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/ye0.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/yu.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/yu.gif new file mode 100644 index 00000000..c91bf1ef Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/yu.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/za.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/za.gif new file mode 100644 index 00000000..8579793e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/za.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/zm.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/zm.gif new file mode 100644 index 00000000..fc686bb8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/zm.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/countries/zw.gif b/org.eclipselabs.tapiji.tools.core/icons/countries/zw.gif new file mode 100644 index 00000000..9821c41c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/countries/zw.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/duplicate.gif b/org.eclipselabs.tapiji.tools.core/icons/duplicate.gif new file mode 100644 index 00000000..3366a273 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/duplicate.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/entry.gif b/org.eclipselabs.tapiji.tools.core/icons/entry.gif new file mode 100644 index 00000000..442539fc Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/entry.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/exclude.png b/org.eclipselabs.tapiji.tools.core/icons/exclude.png new file mode 100644 index 00000000..d1105295 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/exclude.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/file_obj.gif b/org.eclipselabs.tapiji.tools.core/icons/file_obj.gif new file mode 100644 index 00000000..7ccc6a70 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/file_obj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/flatLayout.gif b/org.eclipselabs.tapiji.tools.core/icons/flatLayout.gif new file mode 100644 index 00000000..1ef74cf9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/flatLayout.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/fldr_obj.gif b/org.eclipselabs.tapiji.tools.core/icons/fldr_obj.gif new file mode 100644 index 00000000..51e703b1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/fldr_obj.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/hierarchicalLayout.gif b/org.eclipselabs.tapiji.tools.core/icons/hierarchicalLayout.gif new file mode 100644 index 00000000..23448617 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/hierarchicalLayout.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/icon_new_memory_view.png b/org.eclipselabs.tapiji.tools.core/icons/icon_new_memory_view.png new file mode 100644 index 00000000..2ceac484 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/icon_new_memory_view.png differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/incomplete.gif b/org.eclipselabs.tapiji.tools.core/icons/incomplete.gif new file mode 100644 index 00000000..6583d366 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/incomplete.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/int.gif b/org.eclipselabs.tapiji.tools.core/icons/int.gif new file mode 100644 index 00000000..7d24707e Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/int.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/key.gif b/org.eclipselabs.tapiji.tools.core/icons/key.gif new file mode 100644 index 00000000..bdb8e971 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/key.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/keyCommented.gif b/org.eclipselabs.tapiji.tools.core/icons/keyCommented.gif new file mode 100644 index 00000000..869eb6bd Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/keyCommented.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/keyNone.gif b/org.eclipselabs.tapiji.tools.core/icons/keyNone.gif new file mode 100644 index 00000000..dd1bd7c2 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/keyNone.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/newpropertiesfile.gif b/org.eclipselabs.tapiji.tools.core/icons/newpropertiesfile.gif new file mode 100644 index 00000000..11e436b8 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/newpropertiesfile.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/no_int1.gif b/org.eclipselabs.tapiji.tools.core/icons/no_int1.gif new file mode 100644 index 00000000..a1b17488 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/no_int1.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/no_int2.gif b/org.eclipselabs.tapiji.tools.core/icons/no_int2.gif new file mode 100644 index 00000000..98a2dbc6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/no_int2.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/original/entry.gif b/org.eclipselabs.tapiji.tools.core/icons/original/entry.gif new file mode 100644 index 00000000..d26afe53 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/original/entry.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/original/entry.psd b/org.eclipselabs.tapiji.tools.core/icons/original/entry.psd new file mode 100644 index 00000000..eaa418a1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/original/entry.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/IconResource.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/IconResource.psd new file mode 100644 index 00000000..7ec466a3 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/IconResource.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/NewGlossary.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/NewGlossary.psd new file mode 100644 index 00000000..ad9a7ecd Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/NewGlossary.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/OpenGlossary.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/OpenGlossary.psd new file mode 100644 index 00000000..19bf4b32 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/OpenGlossary.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16.psd new file mode 100644 index 00000000..ddcb2c3a Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_small.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_small.psd new file mode 100644 index 00000000..4130d8e1 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_small.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_warning_small.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_warning_small.psd new file mode 100644 index 00000000..2ca84a23 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Resource16_warning_small.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/Splash.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Splash.psd new file mode 100644 index 00000000..1ef85f27 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/Splash.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/TJ.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/TJ.psd new file mode 100644 index 00000000..2763b3f7 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/TJ.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/TapiJI.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/TapiJI.psd new file mode 100644 index 00000000..2330c969 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/TapiJI.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude.psd new file mode 100644 index 00000000..cd8664f9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude2.psd b/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude2.psd new file mode 100644 index 00000000..30e0d7e0 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/photoshop/exclude2.psd differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/propertiesfile.gif b/org.eclipselabs.tapiji.tools.core/icons/propertiesfile.gif new file mode 100644 index 00000000..9090c04d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/propertiesfile.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/read_only.gif b/org.eclipselabs.tapiji.tools.core/icons/read_only.gif new file mode 100644 index 00000000..dde3cbd6 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/read_only.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/resourcebundle.gif b/org.eclipselabs.tapiji.tools.core/icons/resourcebundle.gif new file mode 100644 index 00000000..fe05bad9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/resourcebundle.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/sample.gif b/org.eclipselabs.tapiji.tools.core/icons/sample.gif new file mode 100644 index 00000000..34fb3c9d Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/sample.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/similar.gif b/org.eclipselabs.tapiji.tools.core/icons/similar.gif new file mode 100644 index 00000000..74cf98e5 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/similar.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/toc_open.gif b/org.eclipselabs.tapiji.tools.core/icons/toc_open.gif new file mode 100644 index 00000000..9e665d5c Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/toc_open.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/warning.gif b/org.eclipselabs.tapiji.tools.core/icons/warning.gif new file mode 100644 index 00000000..801a1f81 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/warning.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/icons/warningGrey.gif b/org.eclipselabs.tapiji.tools.core/icons/warningGrey.gif new file mode 100644 index 00000000..e11147e9 Binary files /dev/null and b/org.eclipselabs.tapiji.tools.core/icons/warningGrey.gif differ diff --git a/org.eclipselabs.tapiji.tools.core/plugin.xml b/org.eclipselabs.tapiji.tools.core/plugin.xml new file mode 100644 index 00000000..0e682620 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/plugin.xml @@ -0,0 +1,121 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?eclipse version="3.4"?> +<plugin> + <extension-point id="org.eclipselabs.tapiji.tools.core.builderExtension" name="BuilderExtension" schema="schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd"/> + + + <extension + id="I18NBuilder" + point="org.eclipse.core.resources.builders"> + <builder hasNature="true"> + <run class="org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor" /> + </builder> + </extension> + + <extension + id="org.eclipselabs.tapiji.tools.core.nature" + name="Internationalization Nature" + point="org.eclipse.core.resources.natures"> + <runtime> + <run class="org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature" /> + </runtime> + <builder id="org.eclipselabs.tapiji.tools.core.I18NBuilder" /> +<!-- <requires-nature id="org.eclipse.jdt.core.javanature"/> --> + </extension> + + <extension + id="StringLiteralAuditMarker" + name="String Literal Audit Marker" + point="org.eclipse.core.resources.markers"> + <super + type="org.eclipse.core.resources.problemmarker"> + </super> + <super + type="org.eclipse.core.resources.textmarker"> + </super> + <persistent + value="true"> + </persistent> + <attribute + name="stringLiteral"> + </attribute> + <attribute + name="violation"> + </attribute> + <attribute + name="context"> + </attribute> + <attribute + name="cause"> + </attribute> + <attribute + name="key"> + </attribute> + <attribute + name="location"> + </attribute> + <attribute + name="bundleName"> + </attribute> + <attribute + name="bundleStart"> + </attribute> + <attribute + name="bundleEnd"> + </attribute> + </extension> + <extension + id="ResourceBundleAuditMarker" + name="Resource-Bundle Audit Marker" + point="org.eclipse.core.resources.markers"> + <super + type="org.eclipse.core.resources.problemmarker"> + </super> + <super + type="org.eclipse.core.resources.textmarker"> + </super> + <persistent + value="true"> + </persistent> + <attribute + name="stringLiteral"> + </attribute> + <attribute + name="violation"> + </attribute> + <attribute + name="context"> + </attribute> + <attribute + name="cause"> + </attribute> + <attribute + name="key"> + </attribute> + <attribute + name="location"> + </attribute> + <attribute + name="language"> + </attribute> + <attribute + name="bundleLine"> + </attribute> + <attribute + name="problemPartner"> + </attribute> + </extension> + <extension + point="org.eclipse.core.runtime.preferences"> + <initializer + class="org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferenceInitializer"> + </initializer> + </extension> + <extension + point="org.eclipse.babel.core.babelConfiguration"> + <IConfiguration + class="org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences"> + </IConfiguration> + </extension> + +</plugin> diff --git a/org.eclipselabs.tapiji.tools.core/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd b/org.eclipselabs.tapiji.tools.core/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd new file mode 100644 index 00000000..d348d874 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd @@ -0,0 +1,222 @@ +<?xml version='1.0' encoding='UTF-8'?> +<!-- Schema file written by PDE --> +<schema targetNamespace="org.eclipselabs.tapiji.tools.core" xmlns="http://www.w3.org/2001/XMLSchema"> +<annotation> + <appinfo> + <meta.schema plugin="org.eclipselabs.tapiji.tools.core" id="builderExtension" name="BuilderExtension"/> + </appinfo> + <documentation> + The TapiJI core plug-in does not contribute any coding assistances into the source code editor. Analogically, it does not provide logic for finding Internationalization problems within sources resources. Moreover, it offers a platform for contributing source code analysis and problem resolution proposals for Internationalization problems in a uniform way. For this purpose, the TapiJI core plug-in provides the extension point org.eclipselabs.tapiji.tools.core.builderExtension that allows other plug-ins to register Internationalization related coding assistances. This concept realizes a loose coupling between basic Internationalization functionality and coding dialect specific help. Once the TapiJI core plug-in is installed, it allows an arbitrary number of extensions to provide their own assistances based on the TapiJI Tools suite. + </documentation> + </annotation> + + <element name="extension"> + <annotation> + <appinfo> + <meta.element /> + </appinfo> + </annotation> + <complexType> + <choice minOccurs="0" maxOccurs="unbounded"> + <element ref="i18nAuditor"/> + </choice> + <attribute name="point" type="string" use="required"> + <annotation> + <documentation> + + </documentation> + </annotation> + </attribute> + <attribute name="id" type="string"> + <annotation> + <documentation> + + </documentation> + </annotation> + </attribute> + <attribute name="name" type="string"> + <annotation> + <documentation> + + </documentation> + <appinfo> + <meta.attribute translatable="true"/> + </appinfo> + </annotation> + </attribute> + </complexType> + </element> + + <element name="i18nAuditor"> + <complexType> + <attribute name="class" type="string" use="required"> + <annotation> + <documentation> + + </documentation> + <appinfo> + <meta.attribute kind="java" basedOn="org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor:"/> + </appinfo> + </annotation> + </attribute> + </complexType> + </element> + + <annotation> + <appinfo> + <meta.section type="since"/> + </appinfo> + <documentation> + 0.0.1 + </documentation> + </annotation> + + <annotation> + <appinfo> + <meta.section type="examples"/> + </appinfo> + <documentation> + The following example demonstrates registration of Java Programming dialect specific Internationalization assistance. + +&lt;pre&gt; +&lt;extension point=&quot;org.eclipselabs.tapiji.tools.core.builderExtension&quot;&gt; + &lt;i18nResourceAuditor + class=&quot;auditor.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.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Activator.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Activator.java new file mode 100644 index 00000000..ae587f38 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Activator.java @@ -0,0 +1,141 @@ +package org.eclipselabs.tapiji.tools.core; + +import java.text.MessageFormat; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.osgi.framework.BundleContext; + + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipselabs.tapiji.tools.core"; + + // The builder extension id + public static final String BUILDER_EXTENSION_ID = "org.eclipselabs.tapiji.tools.core.builderExtension"; + + // The shared instance + private static Activator plugin; + + //Resource bundle. + private ResourceBundle resourceBundle; + + /** + * The constructor + */ + public Activator() { + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) + */ + public void stop(BundleContext context) throws Exception { + // save state of ResourceBundleManager + ResourceBundleManager.saveManagerState(); + + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + + /** + * Returns an image descriptor for the image file at the given + * plug-in relative path + * + * @param path the path + * @return the image descriptor + */ + public static ImageDescriptor getImageDescriptor(String path) { + if (path.indexOf("icons/") < 0) + path = "icons/" + path; + + return imageDescriptorFromPlugin(PLUGIN_ID, path); + } + + /** + * Returns the string from the plugin's resource bundle, + * or 'key' if not found. + * @param key the key for which to fetch a localized text + * @return localized string corresponding to key + */ + public static String getString(String key) { + ResourceBundle bundle = + Activator.getDefault().getResourceBundle(); + try { + return (bundle != null) ? bundle.getString(key) : key; + } catch (MissingResourceException e) { + return key; + } + } + + /** + * Returns the string from the plugin's resource bundle, + * or 'key' if not found. + * @param key the key for which to fetch a localized text + * @param arg1 runtime argument to replace in key value + * @return localized string corresponding to key + */ + public static String getString(String key, String arg1) { + return MessageFormat.format(getString(key), new String[]{arg1}); + } + /** + * Returns the string from the plugin's resource bundle, + * or 'key' if not found. + * @param key the key for which to fetch a localized text + * @param arg1 runtime first argument to replace in key value + * @param arg2 runtime second argument to replace in key value + * @return localized string corresponding to key + */ + public static String getString(String key, String arg1, String arg2) { + return MessageFormat.format( + getString(key), new String[]{arg1, arg2}); + } + /** + * Returns the string from the plugin's resource bundle, + * or 'key' if not found. + * @param key the key for which to fetch a localized text + * @param arg1 runtime argument to replace in key value + * @param arg2 runtime second argument to replace in key value + * @param arg3 runtime third argument to replace in key value + * @return localized string corresponding to key + */ + public static String getString( + String key, String arg1, String arg2, String arg3) { + return MessageFormat.format( + getString(key), new String[]{arg1, arg2, arg3}); + } + + /** + * Returns the plugin's resource bundle. + * @return resource bundle + */ + protected ResourceBundle getResourceBundle() { + return resourceBundle; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Logger.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Logger.java new file mode 100644 index 00000000..c6660809 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/Logger.java @@ -0,0 +1,31 @@ +package org.eclipselabs.tapiji.tools.core; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; + +public class Logger { + + public static void logInfo (String message) { + log(IStatus.INFO, IStatus.OK, message, null); + } + + public static void logError (Throwable exception) { + logError("Unexpected Exception", exception); + } + + public static void logError(String message, Throwable exception) { + log(IStatus.ERROR, IStatus.OK, message, exception); + } + + public static void log(int severity, int code, String message, Throwable exception) { + log(createStatus(severity, code, message, exception)); + } + + public static IStatus createStatus(int severity, int code, String message, Throwable exception) { + return new Status(severity, Activator.PLUGIN_ID, code, message, exception); + } + + public static void log(IStatus status) { + Activator.getDefault().getLog().log(status); + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/BuilderPropertyChangeListener.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/BuilderPropertyChangeListener.java new file mode 100644 index 00000000..c259653b --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/BuilderPropertyChangeListener.java @@ -0,0 +1,117 @@ +package org.eclipselabs.tapiji.tools.core.builder; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.widgets.Display; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants; +import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences; +import org.eclipselabs.tapiji.tools.core.util.EditorUtils; + + +public class BuilderPropertyChangeListener implements IPropertyChangeListener { + + + @Override + public void propertyChange(PropertyChangeEvent event) { + if (event.getNewValue().equals(true) && isTapiPropertyp(event)) + rebuild(); + + if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) + rebuild(); + + if (event.getNewValue().equals(false)){ + if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)){ + removeProperty(EditorUtils.MARKER_ID, -1); + } + if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)){ + removeProperty(EditorUtils.RB_MARKER_ID, -1); + } + if (event.getProperty().equals(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)){ + removeProperty(EditorUtils.RB_MARKER_ID, IMarkerConstants.CAUSE_UNSPEZIFIED_KEY); + } + if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)){ + removeProperty(EditorUtils.RB_MARKER_ID, IMarkerConstants.CAUSE_SAME_VALUE); + } + if (event.getProperty().equals(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)){ + removeProperty(EditorUtils.RB_MARKER_ID, IMarkerConstants.CAUSE_MISSING_LANGUAGE); + } + } + + } + + private boolean isTapiPropertyp(PropertyChangeEvent event) { + if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE) || + event.getProperty().equals(TapiJIPreferences.AUDIT_RB) || + event.getProperty().equals(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY) || + event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE) || + event.getProperty().equals(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) + return true; + else return false; + } + + /* + * cause == -1 ignores the attribute 'case' + */ + private void removeProperty(final String markertpye, final int cause){ + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { + @Override + public void run() { + IMarker[] marker; + try { + marker = workspace.getRoot().findMarkers(markertpye, true, IResource.DEPTH_INFINITE); + + for (IMarker m : marker){ + if (m.exists()){ + if (m.getAttribute("cause", -1) == cause) + m.delete(); + if (cause == -1) + m.getResource().deleteMarkers(markertpye, true, IResource.DEPTH_INFINITE); + } + } + } catch (CoreException e) { + } + } + }); + } + + private void rebuild(){ + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + + new Job ("Audit source files") { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + for (IResource res : workspace.getRoot().members()){ + final IProject p = (IProject) res; + try { + p.build ( StringLiteralAuditor.FULL_BUILD, + StringLiteralAuditor.BUILDER_ID, + null, + monitor); + } catch (CoreException e) { + Logger.logError(e); + } + } + } catch (CoreException e) { + Logger.logError(e); + } + return Status.OK_STATUS; + } + + }.schedule(); + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java new file mode 100644 index 00000000..85287854 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java @@ -0,0 +1,134 @@ +package org.eclipselabs.tapiji.tools.core.builder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IProjectNature; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipselabs.tapiji.tools.core.Activator; +import org.eclipselabs.tapiji.tools.core.Logger; + + +public class InternationalizationNature implements IProjectNature { + + private static final String NATURE_ID = Activator.PLUGIN_ID + ".nature"; + private IProject project; + + @Override + public void configure() throws CoreException { + StringLiteralAuditor.addBuilderToProject(project); + new Job ("Audit source files") { + + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + project.build ( StringLiteralAuditor.FULL_BUILD, + StringLiteralAuditor.BUILDER_ID, + null, + monitor); + } catch (CoreException e) { + Logger.logError(e); + } + return Status.OK_STATUS; + } + + }.schedule(); + } + + @Override + public void deconfigure() throws CoreException { + StringLiteralAuditor.removeBuilderFromProject(project); + } + + @Override + public IProject getProject() { + return project; + } + + @Override + public void setProject(IProject project) { + this.project = project; + } + + public static void addNature(IProject project) { + if (!project.isOpen()) + return; + + IProjectDescription description = null; + + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; + } + + // Check if the project has already this nature + List<String> newIds = new ArrayList<String> (); + newIds.addAll (Arrays.asList(description.getNatureIds())); + int index = newIds.indexOf (NATURE_ID); + if (index != -1) + return; + + // Add the nature + newIds.add (NATURE_ID); + description.setNatureIds (newIds.toArray (new String[newIds.size()])); + + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); + } + } + + public static boolean supportsNature (IProject project) { + return project.isOpen(); + } + + public static boolean hasNature (IProject project) { + try { + return project.isOpen () && project.hasNature(NATURE_ID); + } catch (CoreException e) { + Logger.logError(e); + return false; + } + } + + public static void removeNature (IProject project) { + if (!project.isOpen()) + return; + + IProjectDescription description = null; + + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; + } + + // Check if the project has already this nature + List<String> newIds = new ArrayList<String> (); + newIds.addAll (Arrays.asList(description.getNatureIds())); + int index = newIds.indexOf (NATURE_ID); + if (index == -1) + return; + + // remove the nature + newIds.remove (NATURE_ID); + description.setNatureIds (newIds.toArray (new String[newIds.size()])); + + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); + } + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java new file mode 100644 index 00000000..b9b1d367 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java @@ -0,0 +1,458 @@ +package org.eclipselabs.tapiji.tools.core.builder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.babel.core.configuration.ConfigurationManager; +import org.eclipse.babel.core.configuration.IConfiguration; +import org.eclipse.core.resources.ICommand; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Platform; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipselabs.tapiji.tools.core.Activator; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.builder.analyzer.RBAuditor; +import org.eclipselabs.tapiji.tools.core.builder.analyzer.ResourceFinder; +import org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor; +import org.eclipselabs.tapiji.tools.core.extensions.I18nRBAuditor; +import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor; +import org.eclipselabs.tapiji.tools.core.extensions.ILocation; +import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants; +import org.eclipselabs.tapiji.tools.core.model.exception.NoSuchResourceAuditorException; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences; +import org.eclipselabs.tapiji.tools.core.util.EditorUtils; +import org.eclipselabs.tapiji.tools.core.util.RBFileUtils; + + +public class StringLiteralAuditor extends IncrementalProjectBuilder{ + + public static final String BUILDER_ID = Activator.PLUGIN_ID + + ".I18NBuilder"; + + private static I18nAuditor[] resourceAuditors; + private static Set<String> supportedFileEndings; + private static IPropertyChangeListener listner; + + + static { + List<I18nAuditor> auditors = new ArrayList<I18nAuditor>(); + supportedFileEndings = new HashSet<String>(); + + // init default auditors + auditors.add(new RBAuditor()); + + // lookup registered auditor extensions + IConfigurationElement[] config = Platform.getExtensionRegistry() + .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID); + + try { + for (IConfigurationElement e : config) { + I18nAuditor a = (I18nAuditor) e.createExecutableExtension("class"); + auditors.add(a); + supportedFileEndings.addAll(Arrays.asList(a.getFileEndings())); + } + } catch (CoreException ex) { + Logger.logError(ex); + } + + resourceAuditors = auditors.toArray(new I18nAuditor[auditors.size()]); + + listner = new BuilderPropertyChangeListener(); + TapiJIPreferences.addPropertyChangeListener(listner); + } + + public StringLiteralAuditor() { + } + + public static I18nAuditor getI18nAuditorByContext(String contextId) + throws NoSuchResourceAuditorException { + for (I18nAuditor auditor : resourceAuditors) { + if (auditor.getContextId().equals(contextId)) + return auditor; + } + throw new NoSuchResourceAuditorException(); + } + + private Set<String> getSupportedFileExt() { + return supportedFileEndings; + } + + public static boolean isResourceAuditable(IResource resource, + Set<String> supportedExtensions) { + for (String ext : supportedExtensions) { + if (resource.getType() == IResource.FILE && !resource.isDerived() && resource.getFileExtension() != null + && (resource.getFileExtension().equalsIgnoreCase(ext))) { + return true; + } + } + return false; + } + + @Override + protected IProject[] build(final int kind, Map args, IProgressMonitor monitor) + throws CoreException { + + ResourcesPlugin.getWorkspace().run( + new IWorkspaceRunnable() { + public void run(IProgressMonitor monitor) throws CoreException { + if (kind == FULL_BUILD) { + fullBuild(monitor); + } else { + // only perform audit if the resource delta is not empty + IResourceDelta resDelta = getDelta(getProject()); + + if (resDelta == null) + return; + + if (resDelta.getAffectedChildren() == null) + return; + + incrementalBuild(monitor, resDelta); + } + } + }, + monitor); + + return null; + } + + private void incrementalBuild(IProgressMonitor monitor, + IResourceDelta resDelta) throws CoreException { + try { + // inspect resource delta + ResourceFinder csrav = new ResourceFinder(getSupportedFileExt()); + resDelta.accept(csrav); + auditResources(csrav.getResources(), monitor, getProject()); + } catch (CoreException e) { + Logger.logError(e); + } + } + + public void buildResource(IResource resource, IProgressMonitor monitor) { + if (isResourceAuditable(resource, getSupportedFileExt())) { + List<IResource> resources = new ArrayList<IResource>(); + resources.add(resource); + // TODO: create instance of progressmonitor and hand it over to + // auditResources + try { + auditResources(resources, monitor, getProject()); + } catch (Exception e) { + Logger.logError(e); + } + } + } + + public void buildProject(IProgressMonitor monitor, IProject proj) { + try { + ResourceFinder csrav = new ResourceFinder(getSupportedFileExt()); + proj.accept(csrav); + auditResources(csrav.getResources(), monitor, proj); + } catch (CoreException e) { + Logger.logError(e); + } + } + + private void fullBuild(IProgressMonitor monitor) { + buildProject(monitor, getProject()); + } + + private void auditResources(List<IResource> resources, + IProgressMonitor monitor, IProject project) { + IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration(); + + int work = resources.size(); + int actWork = 0; + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + + monitor.beginTask("Audit resource file for Internationalization problems", + work); + + for (IResource resource : resources) { + monitor.subTask("'" + resource.getFullPath().toOSString() + "'"); + if (monitor.isCanceled()) + throw new OperationCanceledException(); + + if (!EditorUtils.deleteAuditMarkersForResource(resource)) + continue; + + if (ResourceBundleManager.isResourceExcluded(resource)) + continue; + + if (!resource.exists()) + continue; + + for (I18nAuditor ra : resourceAuditors) { + if (ra instanceof I18nResourceAuditor && !(configuration.getAuditResource())) + continue; + if (ra instanceof I18nRBAuditor && !(configuration.getAuditRb())) + continue; + + try { + if (monitor.isCanceled()) { + monitor.done(); + break; + } + + if (ra.isResourceOfType(resource)) { + ra.audit(resource); + } + } catch (Exception e) { + Logger.logError("Error during auditing '" + resource.getFullPath() + "'", e); + } + } + + if (monitor != null) + monitor.worked(1); + } + + for (I18nAuditor a : resourceAuditors) { + if (a instanceof I18nResourceAuditor){ + handleI18NAuditorMarkers((I18nResourceAuditor)a); + } + if (a instanceof I18nRBAuditor){ + handleI18NAuditorMarkers((I18nRBAuditor)a); + ((I18nRBAuditor)a).resetProblems(); + } + } + + monitor.done(); + } + + private void handleI18NAuditorMarkers(I18nResourceAuditor ra){ + try { + for (ILocation problem : ra.getConstantStringLiterals()) { + EditorUtils + .reportToMarker( + EditorUtils + .getFormattedMessage( + EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL, + new String[] { problem + .getLiteral() }), + problem, + IMarkerConstants.CAUSE_CONSTANT_LITERAL, + "", (ILocation) problem.getData(), + ra.getContextId()); + } + + // Report all broken Resource-Bundle references + for (ILocation brokenLiteral : ra + .getBrokenResourceReferences()) { + EditorUtils + .reportToMarker( + EditorUtils + .getFormattedMessage( + EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE, + new String[] { + brokenLiteral + .getLiteral(), + ((ILocation) brokenLiteral + .getData()) + .getLiteral() }), + brokenLiteral, + IMarkerConstants.CAUSE_BROKEN_REFERENCE, + brokenLiteral.getLiteral(), + (ILocation) brokenLiteral.getData(), + ra.getContextId()); + } + + // Report all broken definitions to Resource-Bundle + // references + for (ILocation brokenLiteral : ra + .getBrokenBundleReferences()) { + EditorUtils + .reportToMarker( + EditorUtils + .getFormattedMessage( + EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE, + new String[] { brokenLiteral + .getLiteral() }), + brokenLiteral, + IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE, + brokenLiteral.getLiteral(), + (ILocation) brokenLiteral.getData(), + ra.getContextId()); + } + } catch (Exception e) { + Logger.logError("Exception during reporting of Internationalization errors", e); + } + } + + private void handleI18NAuditorMarkers(I18nRBAuditor ra){ + IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration(); + try { + //Report all unspecified keys + if (configuration.getAuditMissingValue()) + for (ILocation problem : ra.getUnspecifiedKeyReferences()) { + EditorUtils.reportToRBMarker( + EditorUtils.getFormattedMessage( + EditorUtils.MESSAGE_UNSPECIFIED_KEYS, + new String[] {problem.getLiteral(), problem.getFile().getName()}), + problem, + IMarkerConstants.CAUSE_UNSPEZIFIED_KEY, + problem.getLiteral(),"", + (ILocation) problem.getData(), + ra.getContextId()); + } + + //Report all same values + if(configuration.getAuditSameValue()){ + Map<ILocation,ILocation> sameValues = ra.getSameValuesReferences(); + for (ILocation problem : sameValues.keySet()) { + EditorUtils.reportToRBMarker( + EditorUtils.getFormattedMessage( + EditorUtils.MESSAGE_SAME_VALUE, + new String[] {problem.getFile().getName(), + sameValues.get(problem).getFile().getName(), + problem.getLiteral()}), + problem, + IMarkerConstants.CAUSE_SAME_VALUE, + problem.getLiteral(), + sameValues.get(problem).getFile().getName(), + (ILocation) problem.getData(), + ra.getContextId()); + } + } + // Report all missing languages + if (configuration.getAuditMissingLanguage()) + for (ILocation problem : ra.getMissingLanguageReferences()) { + EditorUtils.reportToRBMarker( + EditorUtils.getFormattedMessage( + EditorUtils.MESSAGE_MISSING_LANGUAGE, + new String[] {RBFileUtils.getCorrespondingResourceBundleId(problem.getFile()), + problem.getLiteral()}), + problem, + IMarkerConstants.CAUSE_MISSING_LANGUAGE, + problem.getLiteral(),"", + (ILocation) problem.getData(), + ra.getContextId()); + } + } catch (Exception e) { + Logger.logError("Exception during reporting of Internationalization errors", e); + } + } + + + + @SuppressWarnings("unused") + private void setProgress(IProgressMonitor monitor, int progress) + throws InterruptedException { + monitor.worked(progress); + + if (monitor.isCanceled()) + throw new OperationCanceledException(); + + if (isInterrupted()) + throw new InterruptedException(); + } + + @Override + protected void clean(IProgressMonitor monitor) throws CoreException { + // TODO Auto-generated method stub + super.clean(monitor); + } + + public static void addBuilderToProject(IProject project) { + Logger.logInfo("Internationalization-Builder registered for '" + project.getName() + "'"); + + // Only for open projects + if (!project.isOpen()) + return; + + IProjectDescription description = null; + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; + } + + // Check if the builder is already associated to the specified project + ICommand[] commands = description.getBuildSpec(); + for (ICommand command : commands) { + if (command.getBuilderName().equals(BUILDER_ID)) + return; + } + + // Associate the builder with the project + ICommand builderCmd = description.newCommand(); + builderCmd.setBuilderName(BUILDER_ID); + List<ICommand> newCommands = new ArrayList<ICommand>(); + newCommands.addAll(Arrays.asList(commands)); + newCommands.add(builderCmd); + description.setBuildSpec((ICommand[]) newCommands + .toArray(new ICommand[newCommands.size()])); + + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); + } + } + + public static void removeBuilderFromProject(IProject project) { + // Only for open projects + if (!project.isOpen()) + return; + + try { + project.deleteMarkers(EditorUtils.MARKER_ID, false, + IResource.DEPTH_INFINITE); + project.deleteMarkers(EditorUtils.RB_MARKER_ID, false, + IResource.DEPTH_INFINITE); + } catch (CoreException e1) { + Logger.logError(e1); + } + + IProjectDescription description = null; + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; + } + + // remove builder from project + int idx = -1; + ICommand[] commands = description.getBuildSpec(); + for (int i = 0; i < commands.length; i++) { + if (commands[i].getBuilderName().equals(BUILDER_ID)) { + idx = i; + break; + } + } + if (idx == -1) + return; + + List<ICommand> newCommands = new ArrayList<ICommand>(); + newCommands.addAll(Arrays.asList(commands)); + newCommands.remove(idx); + description.setBuildSpec((ICommand[]) newCommands + .toArray(new ICommand[newCommands.size()])); + + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); + } + + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java new file mode 100644 index 00000000..aebd445d --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java @@ -0,0 +1,34 @@ +package org.eclipselabs.tapiji.tools.core.builder; + +import java.util.List; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.ui.IMarkerResolution; +import org.eclipse.ui.IMarkerResolutionGenerator2; +import org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor; +import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor; +import org.eclipselabs.tapiji.tools.core.model.exception.NoSuchResourceAuditorException; + + +public class ViolationResolutionGenerator implements IMarkerResolutionGenerator2 { + + @Override + public boolean hasResolutions(IMarker marker) { + return true; + } + + @Override + public IMarkerResolution[] getResolutions(IMarker marker) { + String contextId = marker.getAttribute("context", ""); + + // find resolution generator for the given context + try { + I18nAuditor auditor = StringLiteralAuditor.getI18nAuditorByContext(contextId); + List<IMarkerResolution> resolutions = auditor.getMarkerResolutions(marker); + return resolutions.toArray(new IMarkerResolution[resolutions.size()]); + } catch (NoSuchResourceAuditorException e) {} + + return new IMarkerResolution[0]; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java new file mode 100644 index 00000000..187bc2c9 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java @@ -0,0 +1,51 @@ +package org.eclipselabs.tapiji.tools.core.builder.analyzer; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.ui.IMarkerResolution; +import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor; +import org.eclipselabs.tapiji.tools.core.extensions.ILocation; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; + + +public class RBAuditor extends I18nResourceAuditor { + + @Override + public void audit(IResource resource) { + ResourceBundleManager.getManager(resource.getProject()).addBundleResource (resource); + } + + @Override + public String[] getFileEndings() { + return new String [] { "properties" }; + } + + @Override + public List<ILocation> getConstantStringLiterals() { + return new ArrayList<ILocation>(); + } + + @Override + public List<ILocation> getBrokenResourceReferences() { + return new ArrayList<ILocation>(); + } + + @Override + public List<ILocation> getBrokenBundleReferences() { + return new ArrayList<ILocation>(); + } + + @Override + public String getContextId() { + return "resource_bundle"; + } + + @Override + public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { + return null; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java new file mode 100644 index 00000000..583f1d51 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java @@ -0,0 +1,50 @@ +package org.eclipselabs.tapiji.tools.core.builder.analyzer; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.resources.IResourceVisitor; +import org.eclipse.core.runtime.CoreException; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.util.RBFileUtils; +import org.eclipselabs.tapiji.tools.core.util.ResourceUtils; + + +public class ResourceBundleDetectionVisitor implements IResourceVisitor, + IResourceDeltaVisitor { + + private ResourceBundleManager manager = null; + + public ResourceBundleDetectionVisitor(ResourceBundleManager manager) { + this.manager = manager; + } + + @Override + public boolean visit(IResource resource) throws CoreException { + try { + if (RBFileUtils.isResourceBundleFile(resource)) { + Logger.logInfo("Loading Resource-Bundle file '" + resource.getName() + "'"); + if (!ResourceBundleManager.isResourceExcluded(resource)) + manager.addBundleResource(resource); + return false; + } else + return true; + } catch (Exception e) { + return false; + } + } + + @Override + public boolean visit(IResourceDelta delta) throws CoreException { + IResource resource = delta.getResource(); + + if (RBFileUtils.isResourceBundleFile(resource)) { +// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); + return false; + } + + return true; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java new file mode 100644 index 00000000..98e0af7b --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java @@ -0,0 +1,47 @@ +package org.eclipselabs.tapiji.tools.core.builder.analyzer; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.resources.IResourceVisitor; +import org.eclipse.core.runtime.CoreException; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor; + + +public class ResourceFinder implements IResourceVisitor, + IResourceDeltaVisitor { + + List<IResource> javaResources = null; + Set<String> supportedExtensions = null; + + public ResourceFinder(Set<String> ext) { + javaResources = new ArrayList<IResource>(); + supportedExtensions = ext; + } + + @Override + public boolean visit(IResource resource) throws CoreException { + if (StringLiteralAuditor.isResourceAuditable(resource, supportedExtensions)) { + Logger.logInfo("Audit necessary for resource '" + resource.getFullPath().toOSString() + "'"); + javaResources.add(resource); + return false; + } else + return true; + } + + public List<IResource> getResources() { + return javaResources; + } + + @Override + public boolean visit(IResourceDelta delta) throws CoreException { + visit (delta.getResource()); + return true; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java new file mode 100644 index 00000000..a5f9af76 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java @@ -0,0 +1,175 @@ +package org.eclipselabs.tapiji.tools.core.builder.quickfix; + +import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.core.filebuffers.ITextFileBuffer; +import org.eclipse.core.filebuffers.ITextFileBufferManager; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +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.IMarkerResolution2; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.wizards.IWizardDescriptor; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.util.ResourceUtils; +import org.eclipselabs.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard; + +public class CreateResourceBundle implements IMarkerResolution2 { + + private IResource resource; + private int start; + private int end; + private String key; + private boolean jsfContext; + private final String newBunldeWizard = "com.essiembre.eclipse.rbe.ui.wizards.ResourceBundleWizard"; + + public CreateResourceBundle(String key, IResource resource, int start, int end) { + this.key = ResourceUtils.deriveNonExistingRBName(key, ResourceBundleManager.getManager( resource.getProject() )); + this.resource = resource; + this.start = start; + this.end = end; + this.jsfContext = jsfContext; + } + + @Override + public String getDescription() { + return "Creates a new Resource-Bundle with the id '" + key + "'"; + } + + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getLabel() { + return "Create Resource-Bundle '" + key + "'"; + } + + @Override + public void run(IMarker marker) { + runAction(); + } + + protected void runAction () { + // First see if this is a "new wizard". + IWizardDescriptor descriptor = PlatformUI.getWorkbench() + .getNewWizardRegistry().findWizard(newBunldeWizard); + // If not check if it is an "import wizard". + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() + .findWizard(newBunldeWizard); + } + // Or maybe an export wizard + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() + .findWizard(newBunldeWizard); + } + try { + // Then if we have a wizard, open it. + if (descriptor != null) { + IWizard wizard = descriptor.createWizard(); + if (!(wizard instanceof IResourceBundleWizard)) + return; + + IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; + String[] keySilbings = key.split("\\."); + String rbName = keySilbings[keySilbings.length-1]; + String packageName = ""; + + rbw.setBundleId(rbName); + + // Set the default path according to the specified package name + String pathName = ""; + if (keySilbings.length > 1) { + try { + IJavaProject jp = JavaCore.create(resource.getProject()); + packageName = key.substring(0, key.lastIndexOf(".")); + + for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) { + IPackageFragment pf = fr.getPackageFragment(packageName); + if (pf.exists()) { + pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString(); + break; + } + } + } catch (Exception e) { + pathName = ""; + } + } + + try { + IJavaProject jp = JavaCore.create(resource.getProject()); + if (pathName.trim().equals("")) { + for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) { + if (!fr.isReadOnly()) { + pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString(); + break; + } + } + } + } catch (Exception e) { + pathName = ""; + } + + rbw.setDefaultPath (pathName); + + WizardDialog wd = new WizardDialog(Display.getDefault() + .getActiveShell(), wizard); + wd.setTitle(wizard.getWindowTitle()); + if (wd.open() == WizardDialog.OK) { + (new StringLiteralAuditor()).buildProject(null, resource.getProject()); + (new StringLiteralAuditor()).buildResource(resource, null); + + ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); + + if (document.get().charAt(start-1) == '"' && document.get().charAt(start) != '"') { + start --; + end ++; + } + if (document.get().charAt(end+1) == '"' && document.get().charAt(end) != '"') + end ++; + + document.replace(start, end-start, + "\"" + + (packageName.equals("") ? "" : packageName + ".") + rbName + + "\""); + + textFileBuffer.commit(null, false); + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + Logger.logError(e); + } + } + } + } + } catch (CoreException e) { + Logger.logError(e); + } + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java new file mode 100644 index 00000000..85d59483 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java @@ -0,0 +1,65 @@ +package org.eclipselabs.tapiji.tools.core.builder.quickfix; + +import java.util.Set; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.swt.graphics.Image; +import org.eclipse.ui.IMarkerResolution2; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.progress.IProgressService; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; + + +public class IncludeResource implements IMarkerResolution2 { + + private String bundleName; + private Set<IResource> bundleResources; + + public IncludeResource (String bundleName, Set<IResource> bundleResources) { + this.bundleResources = bundleResources; + this.bundleName = bundleName; + } + + @Override + public String getDescription() { + return "The Resource-Bundle with id '" + bundleName + "' has been " + + "excluded from Internationalization. Based on this fact, no internationalization " + + "supoort is provided for this Resource-Bundle. Performing this action, internationalization " + + "support for '" + bundleName + "' will be enabled"; + } + + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getLabel() { + return "Include excluded Resource-Bundle '" + bundleName + "'"; + } + + @Override + public void run(final IMarker marker) { + IWorkbench wb = PlatformUI.getWorkbench(); + IProgressService ps = wb.getProgressService(); + try { + ps.busyCursorWhile(new IRunnableWithProgress() { + public void run(IProgressMonitor pm) { + ResourceBundleManager manager = ResourceBundleManager.getManager(marker.getResource().getProject()); + pm.beginTask("Including resources to Internationalization", bundleResources.size()); + for (IResource resource : bundleResources) { + manager.includeResource(resource, pm); + pm.worked(1); + } + pm.done(); + } + }); + } catch (Exception e) {} + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nAuditor.java new file mode 100644 index 00000000..d6d6d6c4 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nAuditor.java @@ -0,0 +1,65 @@ +package org.eclipselabs.tapiji.tools.core.extensions; + +import java.util.List; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.ui.IMarkerResolution; + +public abstract class I18nAuditor { + + /** + * Audits a project resource for I18N problems. This method is triggered + * during the project's build process. + * + * @param resource + * The project resource + */ + public abstract void audit(IResource resource); + + /** + * Returns a characterizing identifier of the implemented auditing + * functionality. The specified identifier is used for discriminating + * registered builder extensions. + * + * @return The String id of the implemented auditing functionality + */ + public abstract String getContextId(); + + /** + * Returns a list of supported file endings. + * + * @return The supported file endings + */ + public abstract String[] getFileEndings(); + + + /** + * Returns a list of quick fixes of a reported Internationalization problem. + * + * @param marker + * The warning marker of the Internationalization problem + * @param cause + * The problem type + * @return The list of marker resolution proposals + */ + public abstract List<IMarkerResolution> getMarkerResolutions( + IMarker marker); + + /** + * Checks if the provided resource auditor is responsible for a particular + * resource. + * + * @param resource + * The resource reference + * @return True if the resource auditor is responsible for the referenced + * resource + */ + public boolean isResourceOfType(IResource resource) { + for (String ending : getFileEndings()) { + if (resource.getFileExtension().equalsIgnoreCase(ending)) + return true; + } + return false; + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nRBAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nRBAuditor.java new file mode 100644 index 00000000..03ba0050 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nRBAuditor.java @@ -0,0 +1,46 @@ +package org.eclipselabs.tapiji.tools.core.extensions; + +import java.util.List; +import java.util.Map; + +import org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor; +import org.eclipselabs.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.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java new file mode 100644 index 00000000..6dddcc32 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java @@ -0,0 +1,97 @@ +package org.eclipselabs.tapiji.tools.core.extensions; + +import java.util.List; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.ui.IMarkerResolution; + +/** + * Auditor class for finding I18N problems within source code resources. The + * objects audit method is called for a particular resource. Found errors are + * stored within the object's internal data structure and can be queried with + * the help of problem categorized getter methods. + */ +public abstract class I18nResourceAuditor extends I18nAuditor{ + /** + * Audits a project resource for I18N problems. This method is triggered + * during the project's build process. + * + * @param resource + * The project resource + */ + public abstract void audit(IResource resource); + + /** + * Returns a list of supported file endings. + * + * @return The supported file endings + */ + public abstract String[] getFileEndings(); + + /** + * Returns the list of found need-to-translate string literals. Each list + * entry describes the textual position on which this type of error has been + * detected. + * + * @return The list of need-to-translate string literal positions + */ + public abstract List<ILocation> getConstantStringLiterals(); + + /** + * Returns the list of broken Resource-Bundle references. Each list entry + * describes the textual position on which this type of error has been + * detected. + * + * @return The list of positions of broken Resource-Bundle references + */ + public abstract List<ILocation> getBrokenResourceReferences(); + + /** + * Returns the list of broken references to Resource-Bundle entries. Each + * list entry describes the textual position on which this type of error has + * been detected + * + * @return The list of positions of broken references to locale-sensitive + * resources + */ + public abstract List<ILocation> getBrokenBundleReferences(); + + /** + * Returns a characterizing identifier of the implemented auditing + * functionality. The specified identifier is used for discriminating + * registered builder extensions. + * + * @return The String id of the implemented auditing functionality + */ + public abstract String getContextId(); + + /** + * Returns a list of quick fixes of a reported Internationalization problem. + * + * @param marker + * The warning marker of the Internationalization problem + * @param cause + * The problem type + * @return The list of marker resolution proposals + */ + public abstract List<IMarkerResolution> getMarkerResolutions( + IMarker marker); + + /** + * Checks if the provided resource auditor is responsible for a particular + * resource. + * + * @param resource + * The resource reference + * @return True if the resource auditor is responsible for the referenced + * resource + */ + public boolean isResourceOfType(IResource resource) { + for (String ending : getFileEndings()) { + if (resource.getFileExtension().equalsIgnoreCase(ending)) + return true; + } + return false; + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java new file mode 100644 index 00000000..7d567598 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java @@ -0,0 +1,50 @@ +package org.eclipselabs.tapiji.tools.core.extensions; + +import java.io.Serializable; + +import org.eclipse.core.resources.IFile; + +/** + * Describes a text fragment within a source resource. + * + * @author Martin Reiterer + */ +public interface ILocation { + + /** + * Returns the source resource's physical location. + * + * @return The file within the text fragment is located + */ + public IFile getFile(); + + /** + * Returns the position of the text fragments starting character. + * + * @return The position of the first character + */ + public int getStartPos(); + + /** + * Returns the position of the text fragments last character. + * + * @return The position of the last character + */ + public int getEndPos(); + + /** + * Returns the text fragment. + * + * @return The text fragment + */ + public String getLiteral(); + + /** + * Returns additional metadata. The type and content of this property is not + * specified and can be used to marshal additional data for the computation + * of resolution proposals. + * + * @return The metadata associated with the text fragment + */ + public Serializable getData(); +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java new file mode 100644 index 00000000..03dd6535 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java @@ -0,0 +1,11 @@ +package org.eclipselabs.tapiji.tools.core.extensions; + +public interface IMarkerConstants { + public static final int CAUSE_BROKEN_REFERENCE = 0; + public static final int CAUSE_CONSTANT_LITERAL = 1; + public static final int CAUSE_BROKEN_RB_REFERENCE = 2; + + public static final int CAUSE_UNSPEZIFIED_KEY = 3; + public static final int CAUSE_SAME_VALUE = 4; + public static final int CAUSE_MISSING_LANGUAGE = 5; +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java new file mode 100644 index 00000000..576d65af --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java @@ -0,0 +1,9 @@ +package org.eclipselabs.tapiji.tools.core.model; + +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent; + +public interface IResourceBundleChangedListener { + + public void resourceBundleChanged (ResourceBundleChangedEvent event); + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java new file mode 100644 index 00000000..8fda62ba --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java @@ -0,0 +1,21 @@ +package org.eclipselabs.tapiji.tools.core.model; + +public interface IResourceDescriptor { + + public void setProjectName (String projName); + + public void setRelativePath (String relPath); + + public void setAbsolutePath (String absPath); + + public void setBundleId (String bundleId); + + public String getProjectName (); + + public String getRelativePath (); + + public String getAbsolutePath (); + + public String getBundleId (); + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java new file mode 100644 index 00000000..881cacb5 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java @@ -0,0 +1,9 @@ +package org.eclipselabs.tapiji.tools.core.model; + +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceExclusionEvent; + +public interface IResourceExclusionListener { + + public void exclusionChanged(ResourceExclusionEvent event); + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java new file mode 100644 index 00000000..32fc17f9 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java @@ -0,0 +1,75 @@ +package org.eclipselabs.tapiji.tools.core.model; + +import org.eclipse.core.resources.IResource; + +public class ResourceDescriptor implements IResourceDescriptor { + + private String projectName; + private String relativePath; + private String absolutePath; + private String bundleId; + + public ResourceDescriptor (IResource resource) { + projectName = resource.getProject().getName(); + relativePath = resource.getProjectRelativePath().toString(); + absolutePath = resource.getRawLocation().toString(); + } + + public ResourceDescriptor() { + } + + @Override + public String getAbsolutePath() { + return absolutePath; + } + + @Override + public String getProjectName() { + return projectName; + } + + @Override + public String getRelativePath() { + return relativePath; + } + + @Override + public int hashCode() { + return projectName.hashCode() + relativePath.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof ResourceDescriptor)) + return false; + + return absolutePath.equals(absolutePath); + } + + @Override + public void setAbsolutePath(String absPath) { + this.absolutePath = absPath; + } + + @Override + public void setProjectName(String projName) { + this.projectName = projName; + } + + @Override + public void setRelativePath(String relPath) { + this.relativePath = relPath; + } + + @Override + public String getBundleId() { + return this.bundleId; + } + + @Override + public void setBundleId(String bundleId) { + this.bundleId = bundleId; + } + + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java new file mode 100644 index 00000000..cb633c54 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java @@ -0,0 +1,53 @@ +package org.eclipselabs.tapiji.tools.core.model; + +import java.io.Serializable; + +import org.eclipse.core.resources.IFile; +import org.eclipselabs.tapiji.tools.core.extensions.ILocation; + + +public class SLLocation implements Serializable, ILocation { + + private static final long serialVersionUID = 1L; + private IFile file = null; + private int startPos = -1; + private int endPos = -1; + private String literal; + private Serializable data; + + public SLLocation(IFile file, int startPos, int endPos, String literal) { + super(); + this.file = file; + this.startPos = startPos; + this.endPos = endPos; + this.literal = literal; + } + public IFile getFile() { + return file; + } + public void setFile(IFile file) { + this.file = file; + } + public int getStartPos() { + return startPos; + } + public void setStartPos(int startPos) { + this.startPos = startPos; + } + public int getEndPos() { + return endPos; + } + public void setEndPos(int endPos) { + this.endPos = endPos; + } + public String getLiteral() { + return literal; + } + public Serializable getData () { + return data; + } + public void setData (Serializable data) { + this.data = data; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java new file mode 100644 index 00000000..08f79a7e --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java @@ -0,0 +1,5 @@ +package org.eclipselabs.tapiji.tools.core.model.exception; + +public class NoSuchResourceAuditorException extends Exception { + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java new file mode 100644 index 00000000..93b43daf --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java @@ -0,0 +1,15 @@ +package org.eclipselabs.tapiji.tools.core.model.exception; + +public class ResourceBundleException extends Exception { + + private static final long serialVersionUID = -2039182473628481126L; + + public ResourceBundleException (String msg) { + super (msg); + } + + public ResourceBundleException () { + super(); + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/RBChangeListner.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/RBChangeListner.java new file mode 100644 index 00000000..4433a825 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/RBChangeListner.java @@ -0,0 +1,32 @@ +package org.eclipselabs.tapiji.tools.core.model.manager; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.runtime.CoreException; +import org.eclipselabs.tapiji.tools.core.util.RBFileUtils; + +public class RBChangeListner implements IResourceChangeListener { + + @Override + public void resourceChanged(IResourceChangeEvent event) { + try { + event.getDelta().accept(new IResourceDeltaVisitor() { + @Override + public boolean visit(IResourceDelta delta) throws CoreException { + IResource resource = delta.getResource(); + if (RBFileUtils.isResourceBundleFile(resource)) { +// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); + return false; + } + return true; + } + }); + } catch (CoreException e) { + e.printStackTrace(); + } + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java new file mode 100644 index 00000000..73d90d42 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java @@ -0,0 +1,46 @@ +package org.eclipselabs.tapiji.tools.core.model.manager; + +import org.eclipse.core.resources.IProject; + +public class ResourceBundleChangedEvent { + + public final static int ADDED = 0; + public final static int DELETED = 1; + public final static int MODIFIED = 2; + public final static int EXCLUDED = 3; + public final static int INCLUDED = 4; + + private IProject project; + private String bundle = ""; + private int type = -1; + + public ResourceBundleChangedEvent (int type, String bundle, IProject project) { + this.type = type; + this.bundle = bundle; + this.project = project; + } + + public IProject getProject() { + return project; + } + + public void setProject(IProject project) { + this.project = project; + } + + public String getBundle() { + return bundle; + } + + public void setBundle(String bundle) { + this.bundle = bundle; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java new file mode 100644 index 00000000..c275308e --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java @@ -0,0 +1,5 @@ +package org.eclipselabs.tapiji.tools.core.model.manager; + +public class ResourceBundleDetector { + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java new file mode 100644 index 00000000..93e37ff2 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java @@ -0,0 +1,755 @@ +package org.eclipselabs.tapiji.tools.core.model.manager; + +import java.io.FileReader; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import org.eclipse.babel.core.message.manager.RBManager; +import org.eclipse.babel.editor.api.MessagesBundleFactory; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceVisitor; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.ui.IMemento; +import org.eclipse.ui.XMLMemento; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature; +import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor; +import org.eclipselabs.tapiji.tools.core.builder.analyzer.ResourceBundleDetectionVisitor; +import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener; +import org.eclipselabs.tapiji.tools.core.model.IResourceDescriptor; +import org.eclipselabs.tapiji.tools.core.model.IResourceExclusionListener; +import org.eclipselabs.tapiji.tools.core.model.ResourceDescriptor; +import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException; +import org.eclipselabs.tapiji.tools.core.util.EditorUtils; +import org.eclipselabs.tapiji.tools.core.util.FileUtils; +import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils; +import org.eclipselabs.tapiji.tools.core.util.RBFileUtils; +import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage; +import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle; +import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup; + + +public class ResourceBundleManager { + + public static String defaultLocaleTag = "[default]"; // TODO externalize + + /*** CONFIG SECTION ***/ + private static boolean checkResourceExclusionRoot = false; + + /*** MEMBER SECTION ***/ + private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>(); + + public static final String RESOURCE_BUNDLE_EXTENSION = ".properties"; + + //project-specific + private Map<String, Set<IResource>> resources = + new HashMap<String, Set<IResource>> (); + + private Map<String, String> bundleNames = new HashMap<String, String> (); + + private Map<String, List<IResourceBundleChangedListener>> listeners = + new HashMap<String, List<IResourceBundleChangedListener>> (); + + private List<IResourceExclusionListener> exclusionListeners = + new ArrayList<IResourceExclusionListener> (); + + //global + private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor> (); + + private static Map<String, Set<IResource>> allBundles = + new HashMap<String, Set<IResource>> (); + + private static IResourceChangeListener changelistener; + + /*Host project*/ + private IProject project = null; + + /** State-Serialization Information **/ + private static boolean state_loaded = false; + private static final String TAG_INTERNATIONALIZATION = "Internationalization"; + private static final String TAG_EXCLUDED = "Excluded"; + private static final String TAG_RES_DESC = "ResourceDescription"; + private static final String TAG_RES_DESC_ABS = "AbsolutePath"; + private static final String TAG_RES_DESC_REL = "RelativePath"; + private static final String TAB_RES_DESC_PRO = "ProjectName"; + private static final String TAB_RES_DESC_BID = "BundleId"; + + // Define private constructor + private ResourceBundleManager () { + } + + public static ResourceBundleManager getManager (IProject project) { + // check if persistant state has been loaded + if (!state_loaded) + loadManagerState(); + + // set host-project + if (FragmentProjectUtils.isFragment(project)) + project = FragmentProjectUtils.getFragmentHost(project); + + + ResourceBundleManager manager = rbmanager.get(project); + if (manager == null) { + manager = new ResourceBundleManager(); + manager.project = project; + manager.detectResourceBundles(); + rbmanager.put(project, manager); + + } + return manager; + } + + public Set<Locale> getProvidedLocales (String bundleName) { + RBManager instance = RBManager.getInstance(project); + + Set<Locale> locales = new HashSet<Locale>(); + IMessagesBundleGroup group = instance.getMessagesBundleGroup(bundleName); + if (group == null) + return locales; + + for (IMessagesBundle bundle : group.getMessagesBundles()) { + locales.add(bundle.getLocale()); + } + return locales; + } + + public static String getResourceBundleName(IResource res) { + String name = res.getName(); + String regex = "^(.*?)" //$NON-NLS-1$ + + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ + + res.getFileExtension() + ")$"; //$NON-NLS-1$ + return name.replaceFirst(regex, "$1"); //$NON-NLS-1$ + } + + protected boolean isResourceBundleLoaded (String bundleName) { + return RBManager.getInstance(project).containsMessagesBundleGroup(bundleName); + } + + protected Locale getLocaleByName (String bundleName, String localeID) { + // Check locale + Locale locale = null; + bundleName = bundleNames.get(bundleName); + localeID = localeID.substring(0, localeID.length() - "properties".length() - 1); + if (localeID.length() == bundleName.length()) { + // default locale + return null; + } else { + localeID = localeID.substring(bundleName.length() + 1); + String[] localeTokens = localeID.split("_"); + + switch (localeTokens.length) { + case 1: + locale = new Locale(localeTokens[0]); + break; + case 2: + locale = new Locale(localeTokens[0], localeTokens[1]); + break; + case 3: + locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]); + break; + default: + locale = null; + break; + } + } + + return locale; + } + + protected void unloadResource (String bundleName, IResource resource) { + // TODO implement more efficient + unloadResourceBundle(bundleName); +// loadResourceBundle(bundleName); + } + + public static String getResourceBundleId (IResource resource) { + String packageFragment = ""; + + IJavaElement propertyFile = JavaCore.create(resource.getParent()); + if (propertyFile != null && propertyFile instanceof IPackageFragment) + packageFragment = ((IPackageFragment) propertyFile).getElementName(); + + return (packageFragment.length() > 0 ? packageFragment + "." : "") + + getResourceBundleName(resource); + } + + public void addBundleResource (IResource resource) { + if (resource.isDerived()) + return; + + String bundleName = getResourceBundleId(resource); + Set<IResource> res; + + if (!resources.containsKey(bundleName)) + res = new HashSet<IResource> (); + else + res = resources.get(bundleName); + + res.add(resource); + resources.put(bundleName, res); + allBundles.put(bundleName, new HashSet<IResource>(res)); + bundleNames.put(bundleName, getResourceBundleName(resource)); + + // Fire resource changed event + ResourceBundleChangedEvent event = new ResourceBundleChangedEvent( + ResourceBundleChangedEvent.ADDED, + bundleName, + resource.getProject()); + this.fireResourceBundleChangedEvent(bundleName, event); + } + + protected void removeAllBundleResources(String bundleName) { + unloadResourceBundle(bundleName); + resources.remove(bundleName); + //allBundles.remove(bundleName); + listeners.remove(bundleName); + } + + public void unloadResourceBundle (String name) { + RBManager instance = RBManager.getInstance(project); + instance.deleteMessagesBundle(name); + } + + public IMessagesBundleGroup getResourceBundle (String name) { + RBManager instance = RBManager.getInstance(project); + return instance.getMessagesBundleGroup(name); + } + + public Collection<IResource> getResourceBundles (String bundleName) { + return resources.get(bundleName); + } + + public List<String> getResourceBundleNames () { + List<String> returnList = new ArrayList<String>(); + + Iterator<String> it = resources.keySet().iterator(); + while (it.hasNext()) { + returnList.add(it.next()); + } + return returnList; + } + + public IResource getResourceFile (String file) { + String regex = "^(.*?)" + + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + + "properties" + ")$"; + String bundleName = file.replaceFirst(regex, "$1"); + IResource resource = null; + + for (IResource res : resources.get(bundleName)) { + if (res.getName().equalsIgnoreCase(file)) { + resource = res; + break; + } + } + + return resource; + } + + public void fireResourceBundleChangedEvent (String bundleName, ResourceBundleChangedEvent event) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + + if (l == null) + return; + + for (IResourceBundleChangedListener listener : l) { + listener.resourceBundleChanged(event); + } + } + + public void registerResourceBundleChangeListener (String bundleName, IResourceBundleChangedListener listener) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + if (l == null) + l = new ArrayList<IResourceBundleChangedListener>(); + l.add(listener); + listeners.put(bundleName, l); + } + + public void unregisterResourceBundleChangeListener (String bundleName, IResourceBundleChangedListener listener) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + if (l == null) + return; + l.remove(listener); + listeners.put(bundleName, l); + } + + protected void detectResourceBundles () { + try { + project.accept(new ResourceBundleDetectionVisitor(this)); + + IProject[] fragments = FragmentProjectUtils.lookupFragment(project); + if (fragments != null){ + for (IProject p : fragments){ + p.accept(new ResourceBundleDetectionVisitor(this)); + } + } + } catch (CoreException e) { + } + } + + public IProject getProject () { + return project; + } + + public List<String> getResourceBundleIdentifiers () { + List<String> returnList = new ArrayList<String>(); + + // TODO check other resource bundles that are available on the curren class path + Iterator<String> it = this.resources.keySet().iterator(); + while (it.hasNext()) { + returnList.add(it.next()); + } + + return returnList; + } + + public static List<String> getAllResourceBundleNames() { + List<String> returnList = new ArrayList<String>(); + + for (IProject p : getAllSupportedProjects()) { + if (!FragmentProjectUtils.isFragment(p)){ + Iterator<String> it = getManager(p).resources.keySet().iterator(); + while (it.hasNext()) { + returnList.add(p.getName() + "/" + it.next()); + } + } + } + return returnList; + } + + public static Set<IProject> getAllSupportedProjects () { + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); + Set<IProject> projs = new HashSet<IProject>(); + + for (IProject p : projects) { + if (InternationalizationNature.hasNature(p)) + projs.add(p); + } + return projs; + } + + public String getKeyHoverString(String rbName, String key) { + try { + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup bundleGroup = instance + .getMessagesBundleGroup(rbName); + if (!bundleGroup.containsKey(key)) + return null; + + String hoverText = "<html><head></head><body>"; + + for (IMessage message : bundleGroup.getMessages(key)) { + String displayName = message.getLocale() == null ? "Default" + : message.getLocale().getDisplayName(); + String value = message.getValue(); + hoverText += "<b><i>" + displayName + "</i></b><br/>" + + value.replace("\n", "<br/>") + "<br/><br/>"; + } + return hoverText + "</body></html>"; + } catch (Exception e) { + // silent catch + return ""; + } + } + + public boolean isKeyBroken (String rbName, String key) { + IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(project).getMessagesBundleGroup(rbName); + if (messagesBundleGroup == null) { + return true; + } else { + return !messagesBundleGroup.containsKey(key); + } + +// if (!resourceBundles.containsKey(rbName)) +// return true; +// return !this.isResourceExisting(rbName, key); + } + + protected void excludeSingleResource (IResource res) { + IResourceDescriptor rd = new ResourceDescriptor(res); + EditorUtils.deleteAuditMarkersForResource(res); + + // exclude resource + excludedResources.add(rd); + Collection<Object> changedExclusoins = new HashSet<Object>(); + changedExclusoins.add(res); + fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins)); + + // Check if the excluded resource represents a resource-bundle + if (RBFileUtils.isResourceBundleFile(res)) { + String bundleName = getResourceBundleId(res); + Set<IResource> resSet = resources.remove(bundleName); + if (resSet != null) { + resSet.remove(res); + + if (!resSet.isEmpty()) { + resources.put(bundleName, resSet); + unloadResource(bundleName, res); + } else { + rd.setBundleId(bundleName); + unloadResourceBundle(bundleName); + (new StringLiteralAuditor()).buildProject(null, res.getProject()); + } + + fireResourceBundleChangedEvent(getResourceBundleId(res), + new ResourceBundleChangedEvent(ResourceBundleChangedEvent.EXCLUDED, bundleName, + res.getProject())); + } + } + } + + public void excludeResource (IResource res, IProgressMonitor monitor) { + try { + if (monitor == null) + monitor = new NullProgressMonitor(); + + final List<IResource> resourceSubTree = new ArrayList<IResource> (); + res.accept(new IResourceVisitor () { + + @Override + public boolean visit(IResource resource) throws CoreException { + Logger.logInfo("Excluding resource '" + resource.getFullPath().toOSString() + "'"); + resourceSubTree.add(resource); + return true; + } + + }); + + // Iterate previously retrieved resource and exclude them from Internationalization + monitor.beginTask("Exclude resources from Internationalization context", resourceSubTree.size()); + try { + for (IResource resource : resourceSubTree) { + excludeSingleResource (resource); + EditorUtils.deleteAuditMarkersForResource(resource); + monitor.worked(1); + } + } catch (Exception e) { + Logger.logError(e); + } finally { + monitor.done(); + } + } catch (CoreException e) { + Logger.logError(e); + } + } + + public void includeResource (IResource res, IProgressMonitor monitor) { + if (monitor == null) + monitor = new NullProgressMonitor(); + + final Collection<Object> changedResources = new HashSet<Object>(); + IResource resource = res; + + if (!excludedResources.contains(new ResourceDescriptor(res))) { + while (!(resource instanceof IProject || + resource instanceof IWorkspaceRoot)) { + if (excludedResources.contains(new ResourceDescriptor(resource))) { + excludeResource(resource, monitor); + changedResources.add(resource); + break; + } else + resource = resource.getParent(); + } + } + + try { + res.accept(new IResourceVisitor() { + + @Override + public boolean visit(IResource resource) throws CoreException { + changedResources.add(resource); + return true; + } + }); + + monitor.beginTask("Add resources to Internationalization context", changedResources.size()); + try { + for (Object r : changedResources) { + excludedResources.remove(new ResourceDescriptor((IResource)r)); + monitor.worked(1); + } + + } catch (Exception e) { + Logger.logError(e); + } finally { + monitor.done(); + } + } catch (Exception e) { + Logger.logError(e); + } + + (new StringLiteralAuditor()).buildResource(res, null); + + // Check if the included resource represents a resource-bundle + if (RBFileUtils.isResourceBundleFile(res)) { + String bundleName = getResourceBundleId(res); + boolean newRB = resources.containsKey(bundleName); + + this.addBundleResource(res); + this.unloadResourceBundle(bundleName); +// this.loadResourceBundle(bundleName); + + if (newRB) + (new StringLiteralAuditor()).buildProject(null, res.getProject()); + fireResourceBundleChangedEvent(getResourceBundleId(res), + new ResourceBundleChangedEvent(ResourceBundleChangedEvent.INCLUDED, bundleName, + res.getProject())); + } + + fireResourceExclusionEvent (new ResourceExclusionEvent(changedResources)); + } + + protected void fireResourceExclusionEvent (ResourceExclusionEvent event) { + for (IResourceExclusionListener listener : exclusionListeners) + listener.exclusionChanged (event); + } + + public static boolean isResourceExcluded (IResource res) { + IResource resource = res; + + if (!state_loaded) + loadManagerState(); + + boolean isExcluded = false; + + do { + if (excludedResources.contains(new ResourceDescriptor(resource))) { + if (RBFileUtils.isResourceBundleFile(resource)) { + Set<IResource> resources = allBundles.remove(getResourceBundleName(resource)); + if (resources == null) + resources = new HashSet<IResource> (); + resources.add(resource); + allBundles.put(getResourceBundleName(resource), resources); + } + + isExcluded = true; + break; + } + resource = resource.getParent(); + } while (resource != null && + !(resource instanceof IProject || + resource instanceof IWorkspaceRoot) && + checkResourceExclusionRoot); + + return isExcluded; //excludedResources.contains(new ResourceDescriptor(res)); + } + + public IFile getRandomFile(String bundleName) { + try { + IResource res = (resources.get(bundleName)).iterator().next(); + return res.getProject().getFile(res.getProjectRelativePath()); + } catch (Exception e) {} + return null; + } + + private static void loadManagerState () { + excludedResources = new HashSet<IResourceDescriptor>(); + FileReader reader = null; + try { + reader = new FileReader (FileUtils.getRBManagerStateFile()); + loadManagerState (XMLMemento.createReadRoot(reader)); + state_loaded = true; + } catch (Exception e) { + // do nothing + } + + changelistener = new RBChangeListner(); + ResourcesPlugin.getWorkspace().addResourceChangeListener(changelistener, IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE); + } + + private static void loadManagerState(XMLMemento memento) { + IMemento excludedChild = memento.getChild(TAG_EXCLUDED); + for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) { + IResourceDescriptor descriptor = new ResourceDescriptor(); + descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS)); + descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL)); + descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO)); + descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID)); + excludedResources.add(descriptor); + } + } + + public static void saveManagerState () { + if (excludedResources == null) + return; + XMLMemento memento = XMLMemento.createWriteRoot(TAG_INTERNATIONALIZATION); + IMemento exclChild = memento.createChild(TAG_EXCLUDED); + + Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); + while (itExcl.hasNext()) { + IResourceDescriptor desc = itExcl.next(); + IMemento resDesc = exclChild.createChild(TAG_RES_DESC); + resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName()); + resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath()); + resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath()); + resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId()); + } + FileWriter writer = null; + try { + writer = new FileWriter(FileUtils.getRBManagerStateFile()); + memento.save(writer); + } catch (Exception e) { + // do nothing + } finally { + try { + if (writer != null) + writer.close(); + } catch (Exception e) { + // do nothing + } + } + } + + @Deprecated + protected static boolean isResourceExcluded(IProject project, String bname) { + Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); + while (itExcl.hasNext()) { + IResourceDescriptor rd = itExcl.next(); + if (project.getName().equals(rd.getProjectName()) && bname.equals(rd.getBundleId())) + return true; + } + return false; + } + + public static ResourceBundleManager getManager(String projectName) { + for (IProject p : getAllSupportedProjects()) { + if (p.getName().equalsIgnoreCase(projectName)){ + //check if the projectName is a fragment and return the manager for the host + if(FragmentProjectUtils.isFragment(p)) + return getManager(FragmentProjectUtils.getFragmentHost(p)); + else return getManager(p); + } + } + return null; + } + + public IFile getResourceBundleFile(String resourceBundle, Locale l) { + IFile res = null; + Set<IResource> resSet = resources.get(resourceBundle); + + if ( resSet != null ) { + for (IResource resource : resSet) { + Locale refLoc = getLocaleByName(resourceBundle, resource.getName()); + if (refLoc == null && l == null || (refLoc != null && refLoc.equals(l) || l != null && l.equals(refLoc))) { + res = resource.getProject().getFile(resource.getProjectRelativePath()); + break; + } + } + } + + return res; + } + + public Set<IResource> getAllResourceBundleResources(String resourceBundle) { + return allBundles.get(resourceBundle); + } + + public void registerResourceExclusionListener (IResourceExclusionListener listener) { + exclusionListeners.add(listener); + } + + public void unregisterResourceExclusionListener (IResourceExclusionListener listener) { + exclusionListeners.remove(listener); + } + + public boolean isResourceExclusionListenerRegistered (IResourceExclusionListener listener) { + return exclusionListeners.contains(listener); + } + + public static void unregisterResourceExclusionListenerFromAllManagers( + IResourceExclusionListener excludedResource) { + for (ResourceBundleManager mgr : rbmanager.values()) { + mgr.unregisterResourceExclusionListener(excludedResource); + } + } + + public void addResourceBundleEntry(String resourceBundleId, String key, + Locale locale, String message) throws ResourceBundleException { + + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup bundleGroup = instance.getMessagesBundleGroup(resourceBundleId); + IMessage entry = bundleGroup.getMessage(key, locale); + + if (entry == null) { + IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(locale); + IMessage m = MessagesBundleFactory.createMessage(key, locale); + m.setText(message); + messagesBundle.addMessage(m); + } + + // 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); + for (String key : keys) { + messagesBundleGroup.removeMessages(key); + } + + // notify the PropertyKeySelectionTree + instance.fireEditorChanged(); + } + + public boolean isResourceExisting (String bundleId, String key) { + boolean keyExists = false; + IMessagesBundleGroup bGroup = getResourceBundle(bundleId); + + if (bGroup != null) { + keyExists = bGroup.isKey(key); + } + + return keyExists; + } + + public static void refreshResource(IResource resource) { + (new StringLiteralAuditor()).buildProject(null, resource.getProject()); + (new StringLiteralAuditor()).buildResource(resource, null); + } + + public Set<Locale> getProjectProvidedLocales() { + Set<Locale> locales = new HashSet<Locale>(); + + for (String bundleId : getResourceBundleNames()) { + Set<Locale> rb_l = getProvidedLocales(bundleId); + if (!rb_l.isEmpty()){ + Object[] bundlelocales = rb_l.toArray(); + for (Object l : bundlelocales) { + /* TODO check if useful to add the default */ + if (!locales.contains(l)) + locales.add((Locale) l); + } + } + } + return locales; + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java new file mode 100644 index 00000000..0cda211c --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java @@ -0,0 +1,22 @@ +package org.eclipselabs.tapiji.tools.core.model.manager; + +import java.util.Collection; + +public class ResourceExclusionEvent { + + private Collection<Object> changedResources; + + public ResourceExclusionEvent(Collection<Object> changedResources) { + super(); + this.changedResources = changedResources; + } + + public void setChangedResources(Collection<Object> changedResources) { + this.changedResources = changedResources; + } + + public Collection<Object> getChangedResources() { + return changedResources; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/CheckItem.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/CheckItem.java new file mode 100644 index 00000000..44c2401f --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/CheckItem.java @@ -0,0 +1,34 @@ +package org.eclipselabs.tapiji.tools.core.model.preferences; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableItem; + +public class CheckItem{ + boolean checked; + String name; + + public CheckItem(String item, boolean checked) { + this.name = item; + this.checked = checked; + } + + public String getName() { + return name; + } + + public boolean getChecked() { + return checked; + } + + public TableItem toTableItem(Table table){ + TableItem item = new TableItem(table, SWT.NONE); + item.setText(name); + item.setChecked(checked); + return item; + } + + public boolean equals(CheckItem item){ + return name.equals(item.getName()); + } +} \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java new file mode 100644 index 00000000..532b5ff0 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java @@ -0,0 +1,36 @@ +package org.eclipselabs.tapiji.tools.core.model.preferences; + +import java.io.File; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipselabs.tapiji.tools.core.Activator; + +public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer { + + public TapiJIPreferenceInitializer() { + // TODO Auto-generated constructor stub + } + + @Override + public void initializeDefaultPreferences() { + IPreferenceStore prefs = Activator.getDefault().getPreferenceStore(); + + //ResourceBundle-Settings + List<CheckItem> patterns = new LinkedList<CheckItem>(); + patterns.add(new CheckItem("^(.)*/build\\.properties", true)); + patterns.add(new CheckItem("^(.)*/config\\.properties", true)); + patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true)); + prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns)); + + // Builder + prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true); + prefs.setDefault(TapiJIPreferences.AUDIT_RB, true); + prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true); + prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false); + prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true); + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferences.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferences.java new file mode 100644 index 00000000..83f9e2a3 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/preferences/TapiJIPreferences.java @@ -0,0 +1,102 @@ +package org.eclipselabs.tapiji.tools.core.model.preferences; + +import java.util.LinkedList; +import java.util.List; +import java.util.StringTokenizer; + +import org.eclipse.babel.core.configuration.IConfiguration; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipselabs.tapiji.tools.core.Activator; + +public class TapiJIPreferences implements IConfiguration { + + public static final String AUDIT_SAME_VALUE = "auditSameValue"; + public static final String AUDIT_UNSPEZIFIED_KEY = "auditMissingValue"; + public static final String AUDIT_MISSING_LANGUAGE = "auditMissingLanguage"; + public static final String AUDIT_RB = "auditResourceBundle"; + public static final String AUDIT_RESOURCE = "auditResource"; + + public static final String NON_RB_PATTERN = "NoRBPattern"; + + private static final IPreferenceStore PREF = Activator.getDefault().getPreferenceStore(); + + private static final String DELIMITER = ";"; + private static final String ATTRIBUTE_DELIMITER = ":"; + + public boolean getAuditSameValue() { + return PREF.getBoolean(AUDIT_SAME_VALUE); + } + + + public boolean getAuditMissingValue() { + return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY); + } + + + public boolean getAuditMissingLanguage() { + return PREF.getBoolean(AUDIT_MISSING_LANGUAGE); + } + + + public boolean getAuditRb() { + return PREF.getBoolean(AUDIT_RB); + } + + + public boolean getAuditResource() { + return PREF.getBoolean(AUDIT_RESOURCE); + } + + public String getNonRbPattern() { + return PREF.getString(NON_RB_PATTERN); + } + + public static List<CheckItem> getNonRbPatternAsList() { + return convertStringToList(PREF.getString(NON_RB_PATTERN)); + } + + public static List<CheckItem> convertStringToList(String string) { + StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER); + int tokenCount = tokenizer.countTokens(); + List<CheckItem> elements = new LinkedList<CheckItem>(); + + for (int i = 0; i < tokenCount; i++) { + StringTokenizer attribute = new StringTokenizer(tokenizer.nextToken(), ATTRIBUTE_DELIMITER); + String name = attribute.nextToken(); + boolean checked; + if (attribute.nextToken().equals("true")) checked = true; + else checked = false; + + elements.add(new CheckItem(name, checked)); + } + return elements; + } + + + public static String convertListToString(List<CheckItem> patterns) { + StringBuilder sb = new StringBuilder(); + int tokenCount = 0; + + for (CheckItem s : patterns){ + sb.append(s.getName()); + sb.append(ATTRIBUTE_DELIMITER); + if(s.checked) sb.append("true"); + else sb.append("false"); + + if (++tokenCount!=patterns.size()) + sb.append(DELIMITER); + } + return sb.toString(); + } + + + public static void addPropertyChangeListener(IPropertyChangeListener listener){ + Activator.getDefault().getPreferenceStore().addPropertyChangeListener(listener); + } + + + public static void removePropertyChangeListener(IPropertyChangeListener listener) { + Activator.getDefault().getPreferenceStore().removePropertyChangeListener(listener); + } +} \ No newline at end of file diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java new file mode 100644 index 00000000..1d1dd945 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java @@ -0,0 +1,205 @@ +package org.eclipselabs.tapiji.tools.core.model.view; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.eclipse.ui.IMemento; + +public class MessagesViewState { + + private static final String TAG_VISIBLE_LOCALES = "visible_locales"; + private static final String TAG_LOCALE = "locale"; + private static final String TAG_LOCALE_LANGUAGE = "language"; + private static final String TAG_LOCALE_COUNTRY = "country"; + private static final String TAG_LOCALE_VARIANT = "variant"; + private static final String TAG_FUZZY_MATCHING = "fuzzy_matching"; + private static final String TAG_MATCHING_PRECISION= "matching_precision"; + private static final String TAG_SELECTED_PROJECT = "selected_project"; + private static final String TAG_SELECTED_BUNDLE = "selected_bundle"; + private static final String TAG_ENABLED = "enabled"; + private static final String TAG_VALUE = "value"; + private static final String TAG_SEARCH_STRING = "search_string"; + private static final String TAG_EDITABLE = "editable"; + + private List<Locale> visibleLocales; + private SortInfo sortings; + private boolean fuzzyMatchingEnabled; + private float matchingPrecision = .75f; + private String selectedProjectName; + private String selectedBundleId; + private String searchString; + private boolean editable; + + public void saveState (IMemento memento) { + try { + if (memento == null) + return; + + if (visibleLocales != null) { + IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES); + for (Locale loc : visibleLocales) { + IMemento memLoc = memVL.createChild(TAG_LOCALE); + memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage()); + memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry()); + memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant()); + } + } + + if (sortings != null) { + sortings.saveState(memento); + } + + IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING); + memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled); + + IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION); + memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision); + + selectedProjectName = selectedProjectName != null ? selectedProjectName : ""; + selectedBundleId = selectedBundleId != null ? selectedBundleId : ""; + + IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT); + memSP.putString(TAG_VALUE, selectedProjectName); + + IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE); + memSB.putString(TAG_VALUE, selectedBundleId); + + IMemento memSStr = memento.createChild(TAG_SEARCH_STRING); + memSStr.putString(TAG_VALUE, searchString); + + IMemento memEditable = memento.createChild(TAG_EDITABLE); + memEditable.putBoolean(TAG_ENABLED, editable); + } catch (Exception e) { + + } + } + + public void init (IMemento memento) { + if (memento == null) + return; + + + if (memento.getChild(TAG_VISIBLE_LOCALES) != null) { + if (visibleLocales == null) + visibleLocales = new ArrayList<Locale>(); + IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES).getChildren(TAG_LOCALE); + for (IMemento mLocale : mLocales) { + if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null && mLocale.getString(TAG_LOCALE_COUNTRY) == null + && mLocale.getString(TAG_LOCALE_VARIANT) == null) { + continue; + } + Locale newLocale = new Locale ( + mLocale.getString(TAG_LOCALE_LANGUAGE), + mLocale.getString(TAG_LOCALE_COUNTRY), + mLocale.getString(TAG_LOCALE_VARIANT)); + if (!this.visibleLocales.contains(newLocale)) { + visibleLocales.add(newLocale); + } + } + } + + if (sortings == null) + sortings = new SortInfo(); + sortings.init(memento); + + IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING); + if (mFuzzyMatching != null) + fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED); + + IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION); + if (mMP != null) + matchingPrecision = mMP.getFloat(TAG_VALUE); + + IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT); + if (mSelProj != null) + selectedProjectName = mSelProj.getString(TAG_VALUE); + + IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE); + if (mSelBundle != null) + selectedBundleId = mSelBundle.getString(TAG_VALUE); + + IMemento mSStr = memento.getChild(TAG_SEARCH_STRING); + if (mSStr != null) + searchString = mSStr.getString(TAG_VALUE); + + IMemento mEditable = memento.getChild(TAG_EDITABLE); + if (mEditable != null) + editable = mEditable.getBoolean(TAG_ENABLED); + } + + public MessagesViewState(List<Locale> visibleLocales, + SortInfo sortings, boolean fuzzyMatchingEnabled, + String selectedBundleId) { + super(); + this.visibleLocales = visibleLocales; + this.sortings = sortings; + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + this.selectedBundleId = selectedBundleId; + } + + public List<Locale> getVisibleLocales() { + return visibleLocales; + } + + public void setVisibleLocales(List<Locale> visibleLocales) { + this.visibleLocales = visibleLocales; + } + + public SortInfo getSortings() { + return sortings; + } + + public void setSortings(SortInfo sortings) { + this.sortings = sortings; + } + + public boolean isFuzzyMatchingEnabled() { + return fuzzyMatchingEnabled; + } + + public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) { + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + } + + public void setSelectedBundleId(String selectedBundleId) { + this.selectedBundleId = selectedBundleId; + } + + public void setSelectedProjectName(String selectedProjectName) { + this.selectedProjectName = selectedProjectName; + } + + public void setSearchString(String searchString) { + this.searchString = searchString; + } + + public String getSelectedBundleId() { + return selectedBundleId; + } + + public String getSelectedProjectName() { + return selectedProjectName; + } + + public String getSearchString() { + return searchString; + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + this.editable = editable; + } + + public float getMatchingPrecision() { + return matchingPrecision; + } + + public void setMatchingPrecision (float value) { + this.matchingPrecision = value; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java new file mode 100644 index 00000000..cc521b9f --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java @@ -0,0 +1,56 @@ +package org.eclipselabs.tapiji.tools.core.model.view; + +import java.util.List; +import java.util.Locale; + +import org.eclipse.ui.IMemento; + + +public class SortInfo { + + public static final String TAG_SORT_INFO = "sort_info"; + public static final String TAG_COLUMN_INDEX = "col_idx"; + public static final String TAG_ORDER = "order"; + + private int colIdx; + private boolean DESC; + private List<Locale> visibleLocales; + + public void setDESC(boolean dESC) { + DESC = dESC; + } + + public boolean isDESC() { + return DESC; + } + + public void setColIdx(int colIdx) { + this.colIdx = colIdx; + } + + public int getColIdx() { + return colIdx; + } + + public void setVisibleLocales(List<Locale> visibleLocales) { + this.visibleLocales = visibleLocales; + } + + public List<Locale> getVisibleLocales() { + return visibleLocales; + } + + public void saveState (IMemento memento) { + IMemento mCI = memento.createChild(TAG_SORT_INFO); + mCI.putInteger(TAG_COLUMN_INDEX, colIdx); + mCI.putBoolean(TAG_ORDER, DESC); + } + + public void init (IMemento memento) { + IMemento mCI = memento.getChild(TAG_SORT_INFO); + if (mCI == null) + return; + colIdx = mCI.getInteger(TAG_COLUMN_INDEX); + DESC = mCI.getBoolean(TAG_ORDER); + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java new file mode 100644 index 00000000..32d33bd1 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java @@ -0,0 +1,144 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import java.text.MessageFormat; + +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.IWorkbenchPage; +import org.eclipse.ui.ide.IDE; +import org.eclipselabs.tapiji.tools.core.Activator; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.extensions.ILocation; +import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; + + +public class EditorUtils { + + /** Marker constants **/ + public static final String MARKER_ID = Activator.PLUGIN_ID + + ".StringLiteralAuditMarker"; + public static final String RB_MARKER_ID = Activator.PLUGIN_ID + ".ResourceBundleAuditMarker"; + + /** Error messages **/ + public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found"; + public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''"; + public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found"; + + public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''"; + public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''"; + public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''"; + + /** Editor ids **/ + public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor"; + + public static String getFormattedMessage (String pattern, Object[] arguments) { + String formattedMessage = ""; + + MessageFormat formatter = new MessageFormat(pattern); + formattedMessage = formatter.format(arguments); + + return formattedMessage; + } + + public static void openEditor (IWorkbenchPage page, IFile file, String editor) { + // open the default-editor for this file type + try { + // TODO open resourcebundleeditor + IDE.openEditor(page, file, editor); + } catch (Exception e) { + Logger.logError(e); + } + } + + public static void reportToMarker(String string, ILocation problem, int cause, String key, ILocation data, String context) { + try { + IMarker marker = problem.getFile().createMarker(MARKER_ID); + marker.setAttribute(IMarker.MESSAGE, string); + marker.setAttribute(IMarker.CHAR_START, problem.getStartPos()); + marker.setAttribute(IMarker.CHAR_END, problem.getEndPos()); + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); + marker.setAttribute("cause", cause); + marker.setAttribute("key", key); + marker.setAttribute("context", context); + if (data != null) { + marker.setAttribute("bundleName", data.getLiteral()); + marker.setAttribute("bundleStart", data.getStartPos()); + marker.setAttribute("bundleEnd", data.getEndPos()); + } + + // TODO: init attributes + marker.setAttribute("stringLiteral", string); + } catch (CoreException e) { + Logger.logError(e); + return; + } + + Logger.logInfo(string); + } + + public static void reportToRBMarker(String string, ILocation problem, int cause, String key, String problemPartnerFile, ILocation data, String context) { + try { + if (!problem.getFile().exists()) return; + IMarker marker = problem.getFile().createMarker(RB_MARKER_ID); + marker.setAttribute(IMarker.MESSAGE, string); + marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); //TODO better-dirty implementation + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); + marker.setAttribute("cause", cause); + marker.setAttribute("key", key); + marker.setAttribute("context", context); + if (data != null) { + marker.setAttribute("language", data.getLiteral()); + marker.setAttribute("bundleLine", data.getStartPos()); + } + marker.setAttribute("stringLiteral", string); + marker.setAttribute("problemPartner", problemPartnerFile); + } catch (CoreException e) { + Logger.logError(e); + return; + } + + Logger.logInfo(string); + } + + public static boolean deleteAuditMarkersForResource(IResource resource) { + try { + if (resource != null && resource.exists()) { + resource.deleteMarkers(MARKER_ID, false, IResource.DEPTH_INFINITE); + deleteAllAuditRBMarkersFromRB(resource); + } + } catch (CoreException e) { + Logger.logError(e); + return false; + } + return true; + } + + /* + * Delete all RB_MARKER from the hole resourcebundle + */ + private static boolean deleteAllAuditRBMarkersFromRB(IResource resource) throws CoreException{ +// if (resource.findMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE).length > 0) + if (RBFileUtils.isResourceBundleFile(resource)){ + String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile)resource); + if (rbId==null) return true; //file in no resourcebundle + + ResourceBundleManager rbmanager = ResourceBundleManager.getManager(resource.getProject()); + for(IResource r : rbmanager.getResourceBundles(rbId)) + r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE); + } + return true; + } + + public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add){ + IMarker[] old_ms = ms; + ms = new IMarker[old_ms.length + ms_to_add.length]; + + System.arraycopy(old_ms, 0, ms, 0, old_ms.length); + System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length); + + return ms; + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java new file mode 100644 index 00000000..3da2b38d --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java @@ -0,0 +1,67 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileReader; + +import org.eclipse.core.internal.resources.ResourceException; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipselabs.tapiji.tools.core.Activator; +import org.eclipselabs.tapiji.tools.core.Logger; + + +public class FileUtils { + + public static String readFile (IResource resource) { + return readFileAsString(resource.getRawLocation().toFile()); + } + + protected static String readFileAsString(File filePath) { + String content = ""; + + if (!filePath.exists()) return content; + try { + BufferedReader fileReader = new BufferedReader(new FileReader(filePath)); + String line = ""; + + while ((line = fileReader.readLine()) != null) { + content += line + "\n"; + } + + // close filereader + fileReader.close(); + } catch (Exception e) { + // TODO log error output + Logger.logError(e); + } + + return content; + } + + public static File getRBManagerStateFile() { + return Activator.getDefault().getStateLocation().append("internationalization.xml").toFile(); + } + + /** + * Don't use that -> causes {@link ResourceException} -> because File out of sync + * @param file + * @param editorContent + * @throws CoreException + * @throws OperationCanceledException + */ + public synchronized void saveTextFile(IFile file, String editorContent) + throws CoreException, OperationCanceledException { + try { + file.setContents(new ByteArrayInputStream(editorContent.getBytes()), + false, true, null); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java new file mode 100644 index 00000000..5dc4382a --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java @@ -0,0 +1,80 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipselabs.tapiji.tools.core.Activator; + + +public class FontUtils { + + /** + * Gets a system color. + * @param colorId SWT constant + * @return system color + */ + public static Color getSystemColor(int colorId) { + return Activator.getDefault().getWorkbench() + .getDisplay().getSystemColor(colorId); + } + + /** + * Creates a font by altering the font associated with the given control + * and applying the provided style (size is unaffected). + * @param control control we base our font data on + * @param style style to apply to the new font + * @return newly created font + */ + public static Font createFont(Control control, int style) { + //TODO consider dropping in favor of control-less version? + return createFont(control, style, 0); + } + + + /** + * Creates a font by altering the font associated with the given control + * and applying the provided style and relative size. + * @param control control we base our font data on + * @param style style to apply to the new font + * @param relSize size to add or remove from the control size + * @return newly created font + */ + public static Font createFont(Control control, int style, int relSize) { + //TODO consider dropping in favor of control-less version? + FontData[] fontData = control.getFont().getFontData(); + for (int i = 0; i < fontData.length; i++) { + fontData[i].setHeight(fontData[i].getHeight() + relSize); + fontData[i].setStyle(style); + } + return new Font(control.getDisplay(), fontData); + } + + /** + * Creates a font by altering the system font + * and applying the provided style and relative size. + * @param style style to apply to the new font + * @return newly created font + */ + public static Font createFont(int style) { + return createFont(style, 0); + } + + /** + * Creates a font by altering the system font + * and applying the provided style and relative size. + * @param style style to apply to the new font + * @param relSize size to add or remove from the control size + * @return newly created font + */ + public static Font createFont(int style, int relSize) { + Display display = Activator.getDefault().getWorkbench().getDisplay(); + FontData[] fontData = display.getSystemFont().getFontData(); + for (int i = 0; i < fontData.length; i++) { + fontData[i].setHeight(fontData[i].getHeight() + relSize); + fontData[i].setStyle(style); + } + return new Font(display, fontData); + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FragmentProjectUtils.java new file mode 100644 index 00000000..abfbbfab --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/FragmentProjectUtils.java @@ -0,0 +1,35 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import java.util.List; + +import org.eclipse.babel.core.util.PDEUtils; +import org.eclipse.core.resources.IProject; + +public class FragmentProjectUtils{ + + public static String getPluginId(IProject project){ + return PDEUtils.getPluginId(project); + } + + + public static IProject[] lookupFragment(IProject pluginProject){ + return PDEUtils.lookupFragment(pluginProject); + } + + public static boolean isFragment(IProject pluginProject){ + return PDEUtils.isFragment(pluginProject); + } + + public static List<IProject> getFragments(IProject hostProject){ + return PDEUtils.getFragments(hostProject); + } + + public static String getFragmentId(IProject project, String hostPluginId){ + return PDEUtils.getFragmentId(project, hostPluginId); + } + + public static IProject getFragmentHost(IProject fragment){ + return PDEUtils.getFragmentHost(fragment); + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java new file mode 100644 index 00000000..30437257 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java @@ -0,0 +1,68 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import org.eclipse.jface.resource.ImageRegistry; +import org.eclipse.swt.graphics.Image; +import org.eclipselabs.tapiji.tools.core.Activator; + + + +/** + * Utility methods related to application UI. + * @author Pascal Essiembre ([email protected]) + * @version $Author: nl_carnage $ $Revision: 1.12 $ $Date: 2007/09/11 16:11:10 $ + */ +public final class ImageUtils { + + /** Name of resource bundle image. */ + public static final String IMAGE_RESOURCE_BUNDLE = + "icons/resourcebundle.gif"; //$NON-NLS-1$ + /** Name of properties file image. */ + public static final String IMAGE_PROPERTIES_FILE = + "icons/propertiesfile.gif"; //$NON-NLS-1$ + /** Name of properties file entry image */ + public static final String IMAGE_PROPERTIES_FILE_ENTRY = + "icons/key.gif"; + /** Name of new properties file image. */ + public static final String IMAGE_NEW_PROPERTIES_FILE = + "icons/newpropertiesfile.gif"; //$NON-NLS-1$ + /** Name of hierarchical layout image. */ + public static final String IMAGE_LAYOUT_HIERARCHICAL = + "icons/hierarchicalLayout.gif"; //$NON-NLS-1$ + /** Name of flat layout image. */ + public static final String IMAGE_LAYOUT_FLAT = + "icons/flatLayout.gif"; //$NON-NLS-1$ + public static final String IMAGE_INCOMPLETE_ENTRIES = + "icons/incomplete.gif"; //$NON-NLS-1$ + public static final String IMAGE_EXCLUDED_RESOURCE_ON = + "icons/int.gif"; //$NON-NLS-1$ + public static final String IMAGE_EXCLUDED_RESOURCE_OFF = + "icons/exclude.png"; //$NON-NLS-1$ + public static final String ICON_RESOURCE = + "icons/Resource16_small.png"; + public static final String ICON_RESOURCE_INCOMPLETE = + "icons/Resource16_warning_small.png"; + + /** Image registry. */ + private static final ImageRegistry imageRegistry = new ImageRegistry(); + + /** + * Constructor. + */ + private ImageUtils() { + super(); + } + + /** + * Gets an image. + * @param imageName image name + * @return image + */ + public static Image getImage(String imageName) { + Image image = imageRegistry.get(imageName); + if (image == null) { + image = Activator.getImageDescriptor(imageName).createImage(); + imageRegistry.put(imageName, image); + } + return image; + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LanguageUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LanguageUtils.java new file mode 100644 index 00000000..a4903798 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LanguageUtils.java @@ -0,0 +1,154 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringBufferInputStream; +import java.util.Locale; + +import org.eclipse.babel.editor.api.PropertiesGenerator; +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipselabs.tapiji.tools.core.Logger; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; + + +public class LanguageUtils { + private static final String INITIALISATION_STRING = PropertiesGenerator.GENERATED_BY; + + + private static IFile createFile(IContainer container, String fileName, IProgressMonitor monitor) throws CoreException, IOException { + if (!container.exists()){ + if (container instanceof IFolder){ + ((IFolder) container).create(false, false, monitor); + } + } + + IFile file = container.getFile(new Path(fileName)); + if (!file.exists()){ + InputStream s = new StringBufferInputStream(INITIALISATION_STRING); + file.create(s, true, monitor); + s.close(); + } + + return file; + } + + /** + * Checks if ResourceBundle provides a given locale. If the locale is not + * provided, creates a new properties-file with the ResourceBundle-basename + * and the index of the given locale. + * @param project + * @param rbId + * @param locale + */ + public static void addLanguageToResourceBundle(IProject project, final String rbId, final Locale locale){ + ResourceBundleManager rbManager = ResourceBundleManager.getManager(project); + + if (rbManager.getProvidedLocales(rbId).contains(locale)) return; + + final IResource file = rbManager.getRandomFile(rbId); + final IContainer c = ResourceUtils.getCorrespondingFolders(file.getParent(), project); + + new Job("create new propertfile") { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + String newFilename = ResourceBundleManager.getResourceBundleName(file); + if (locale.getLanguage() != null && !locale.getLanguage().equalsIgnoreCase(ResourceBundleManager.defaultLocaleTag) + && !locale.getLanguage().equals("")) + newFilename += "_"+locale.getLanguage(); + if (locale.getCountry() != null && !locale.getCountry().equals("")) + newFilename += "_"+locale.getCountry(); + if (locale.getVariant() != null && !locale.getCountry().equals("")) + newFilename += "_"+locale.getVariant(); + newFilename += ".properties"; + + createFile(c, newFilename, monitor); + } catch (CoreException e) { + Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e); + } catch (IOException e) { + Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e); + } + monitor.done(); + return Status.OK_STATUS; + } + }.schedule(); + } + + + /** + * Adds new properties-files for a given locale to all ResourceBundles of a project. + * If a ResourceBundle already contains the language, happens nothing. + * @param project + * @param locale + */ + public static void addLanguageToProject(IProject project, Locale locale){ + ResourceBundleManager rbManager = ResourceBundleManager.getManager(project); + + //Audit if all resourecbundles provide this locale. if not - add new file + for (String rbId : rbManager.getResourceBundleIdentifiers()){ + addLanguageToResourceBundle(project, rbId, locale); + } + } + + + private static void deleteFile(IFile file, boolean force, IProgressMonitor monitor) throws CoreException{ + EditorUtils.deleteAuditMarkersForResource(file); + file.delete(force, monitor); + } + + /** + * Removes the properties-file of a given locale from a ResourceBundle, if + * the ResourceBundle provides the locale. + * @param project + * @param rbId + * @param locale + */ + public static void removeFileFromResourceBundle(IProject project, String rbId, Locale locale) { + ResourceBundleManager rbManager = ResourceBundleManager.getManager(project); + + if (!rbManager.getProvidedLocales(rbId).contains(locale)) return; + + final IFile file = rbManager.getResourceBundleFile(rbId, locale); + final String filename = file.getName(); + + new Job("remove properties-file") { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + deleteFile(file, true, monitor); + } catch (CoreException e) { +// MessageDialog.openError(Display.getCurrent().getActiveShell(), "Confirm", "File could not be deleted"); + Logger.logError("File could not be deleted",e); + } + return Status.OK_STATUS; + } + }.schedule(); + } + + /** + * Removes all properties-files of a given locale from all ResourceBundles of a project. + * @param rbManager + * @param locale + * @return + */ + public static void removeLanguageFromProject(IProject project, Locale locale){ + ResourceBundleManager rbManager = ResourceBundleManager.getManager(project); + + for (String rbId : rbManager.getResourceBundleIdentifiers()){ + removeFileFromResourceBundle(project, rbId, locale); + } + + } + + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java new file mode 100644 index 00000000..aef60c50 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java @@ -0,0 +1,32 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import java.util.Locale; +import java.util.Set; + +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; + +public class LocaleUtils { + + public static Locale getLocaleByDisplayName (Set<Locale> locales, String displayName) { + for (Locale l : locales) { + String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(); + if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) { + return l; + } + } + + return null; + } + + public static boolean containsLocaleByDisplayName(Set<Locale> locales, String displayName) { + for (Locale l : locales) { + String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(); + if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) { + return true; + } + } + + return false; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java new file mode 100644 index 00000000..c33682ed --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java @@ -0,0 +1,55 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import org.eclipse.jface.resource.CompositeImageDescriptor; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.Point; + +public class OverlayIcon extends CompositeImageDescriptor { + + public static final int TOP_LEFT = 0; + public static final int TOP_RIGHT = 1; + public static final int BOTTOM_LEFT = 2; + public static final int BOTTOM_RIGHT = 3; + + private Image img; + private Image overlay; + private int location; + private Point imgSize; + + public OverlayIcon(Image baseImage, Image overlayImage, int location) { + super(); + this.img = baseImage; + this.overlay = overlayImage; + this.location = location; + this.imgSize = new Point(baseImage.getImageData().width, baseImage.getImageData().height); + } + + @Override + protected void drawCompositeImage(int width, int height) { + drawImage(img.getImageData(), 0, 0); + ImageData imageData = overlay.getImageData(); + + switch (location) { + case TOP_LEFT: + drawImage(imageData, 0, 0); + break; + case TOP_RIGHT: + drawImage(imageData, imgSize.x - imageData.width, 0); + break; + case BOTTOM_LEFT: + drawImage(imageData, 0, imgSize.y - imageData.height); + break; + case BOTTOM_RIGHT: + drawImage(imageData, imgSize.x - imageData.width, imgSize.y + - imageData.height); + break; + } + } + + @Override + protected Point getSize() { + return new Point(img.getImageData().width, img.getImageData().height); + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/PDEUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/PDEUtils.java new file mode 100644 index 00000000..4f9efbb7 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/PDEUtils.java @@ -0,0 +1,290 @@ +/* + * Copyright (C) 2007 Uwe Voigt + * + * This file is part of Essiembre ResourceBundle Editor. + * + * Essiembre ResourceBundle Editor is free software; you can redistribute it + * and/or modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * Essiembre ResourceBundle Editor is distributed in the hope that it will be + * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Essiembre ResourceBundle Editor; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place, Suite 330, + * Boston, MA 02111-1307 USA + */ +package org.eclipselabs.tapiji.tools.core.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.osgi.framework.Constants; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * A class that helps to find fragment and plugin projects. + * + * @author Uwe Voigt (http://sourceforge.net/users/uwe_ewald/) + */ +public class PDEUtils { + + /** Bundle manifest name */ + public static final String OSGI_BUNDLE_MANIFEST = "META-INF/MANIFEST.MF"; //$NON-NLS-1$ + /** Plugin manifest name */ + public static final String PLUGIN_MANIFEST = "plugin.xml"; //$NON-NLS-1$ + /** Fragment manifest name */ + public static final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$ + + /** + * Returns the plugin-id of the project if it is a plugin project. Else + * null is returned. + * + * @param project the project + * @return the plugin-id or null + */ + public static String getPluginId(IProject project) { + if (project == null) + return null; + IResource manifest = project.findMember(OSGI_BUNDLE_MANIFEST); + String id = getManifestEntryValue(manifest, Constants.BUNDLE_SYMBOLICNAME); + if (id != null) + return id; + manifest = project.findMember(PLUGIN_MANIFEST); + if (manifest == null) + manifest = project.findMember(FRAGMENT_MANIFEST); + if (manifest instanceof IFile) { + InputStream in = null; + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + in = ((IFile) manifest).getContents(); + Document document = builder.parse(in); + Node node = getXMLElement(document, "plugin"); //$NON-NLS-1$ + if (node == null) + node = getXMLElement(document, "fragment"); //$NON-NLS-1$ + if (node != null) + node = node.getAttributes().getNamedItem("id"); //$NON-NLS-1$ + if (node != null) + return node.getNodeValue(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (in != null) + in.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + return null; + } + + /** + * Returns all project containing plugin/fragment of the specified + * project. If the specified project itself is a fragment, then only this is returned. + * + * @param pluginProject the plugin project + * @return the all project containing a fragment or null if none + */ + public static IProject[] lookupFragment(IProject pluginProject) { + List<IProject> fragmentIds = new ArrayList<IProject>(); + + String pluginId = PDEUtils.getPluginId(pluginProject); + if (pluginId == null) + return null; + String fragmentId = getFragmentId(pluginProject, getPluginId(getFragmentHost(pluginProject))); + if (fragmentId != null){ + fragmentIds.add(pluginProject); + return fragmentIds.toArray(new IProject[0]); + } + + IProject[] projects = pluginProject.getWorkspace().getRoot().getProjects(); + for (int i = 0; i < projects.length; i++) { + IProject project = projects[i]; + if (!project.isOpen()) + continue; + if (getFragmentId(project, pluginId) == null) + continue; + fragmentIds.add(project); + } + + if (fragmentIds.size() > 0) return fragmentIds.toArray(new IProject[0]); + else return null; + } + + public static boolean isFragment(IProject pluginProject){ + String pluginId = PDEUtils.getPluginId(pluginProject); + if (pluginId == null) + return false; + String fragmentId = getFragmentId(pluginProject, getPluginId(getFragmentHost(pluginProject))); + if (fragmentId != null) + return true; + else + return false; + } + + public static List<IProject> getFragments(IProject hostProject){ + List<IProject> fragmentIds = new ArrayList<IProject>(); + + String pluginId = PDEUtils.getPluginId(hostProject); + IProject[] projects = hostProject.getWorkspace().getRoot().getProjects(); + + for (int i = 0; i < projects.length; i++) { + IProject project = projects[i]; + if (!project.isOpen()) + continue; + if (getFragmentId(project, pluginId) == null) + continue; + fragmentIds.add(project); + } + + return fragmentIds; + } + + /** + * Returns the fragment-id of the project if it is a fragment project with + * the specified host plugin id as host. Else null is returned. + * + * @param project the project + * @param hostPluginId the host plugin id + * @return the plugin-id or null + */ + public static String getFragmentId(IProject project, String hostPluginId) { + IResource manifest = project.findMember(FRAGMENT_MANIFEST); + Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$ + if (fragmentNode != null) { + Node hostNode = fragmentNode.getAttributes().getNamedItem("plugin-id"); //$NON-NLS-1$ + if (hostNode != null && hostNode.getNodeValue().equals(hostPluginId)) { + Node idNode = fragmentNode.getAttributes().getNamedItem("id"); //$NON-NLS-1$ + if (idNode != null) + return idNode.getNodeValue(); + } + } + manifest = project.findMember(OSGI_BUNDLE_MANIFEST); + String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST); + if (hostId != null && hostId.equals(hostPluginId)) + return getManifestEntryValue(manifest, Constants.BUNDLE_SYMBOLICNAME); + return null; + } + + /** + * Returns the host plugin project of the specified project if it contains a fragment. + * + * @param fragment the fragment project + * @return the host plugin project or null + */ + public static IProject getFragmentHost(IProject fragment) { + IResource manifest = fragment.findMember(FRAGMENT_MANIFEST); + Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$ + if (fragmentNode != null) { + Node hostNode = fragmentNode.getAttributes().getNamedItem("plugin-id"); //$NON-NLS-1$ + if (hostNode != null) + return fragment.getWorkspace().getRoot().getProject(hostNode.getNodeValue()); + } + manifest = fragment.findMember(OSGI_BUNDLE_MANIFEST); + String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST); + if (hostId != null) + return fragment.getWorkspace().getRoot().getProject(hostId); + return null; + } + + /** + * Returns the file content as UTF8 string. + * + * @param file + * @param charset + * @return + */ + public static String getFileContent(IFile file, String charset) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + InputStream in = null; + try { + in = file.getContents(true); + byte[] buf = new byte[8000]; + for (int count; (count = in.read(buf)) != -1;) + outputStream.write(buf, 0, count); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException ignore) { + } + } + } + try { + return outputStream.toString(charset); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return outputStream.toString(); + } + } + + private static String getManifestEntryValue(IResource manifest, String entryKey) { + if (manifest instanceof IFile) { + String content = getFileContent((IFile) manifest, "UTF8"); //$NON-NLS-1$ + int index = content.indexOf(entryKey); + if (index != -1) { + StringTokenizer st = new StringTokenizer(content.substring(index + + entryKey.length()), ";:\r\n"); //$NON-NLS-1$ + return st.nextToken().trim(); + } + } + return null; + } + + private static Document getXMLDocument(IResource resource) { + if (!(resource instanceof IFile)) + return null; + InputStream in = null; + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + in = ((IFile) resource).getContents(); + return builder.parse(in); + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + try { + if (in != null) + in.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + private static Node getXMLElement(Document document, String name) { + if (document == null) + return null; + NodeList list = document.getChildNodes(); + for (int i = 0; i < list.getLength(); i++) { + Node node = list.item(i); + if (node.getNodeType() != Node.ELEMENT_NODE) + continue; + if (name.equals(node.getNodeName())) + return node; + } + return null; + } + +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/RBFileUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/RBFileUtils.java new file mode 100644 index 00000000..1f3ada25 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/RBFileUtils.java @@ -0,0 +1,174 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipselabs.tapiji.tools.core.Activator; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; +import org.eclipselabs.tapiji.tools.core.model.preferences.CheckItem; +import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences; + + +/** + * + * @author mgasser + * + */ +public class RBFileUtils extends Action{ + public static final String PROPERTIES_EXT = "properties"; + + + /** + * Returns true if a file is a ResourceBundle-file + */ + public static boolean isResourceBundleFile(IResource file) { + boolean isValied = false; + + if (file != null && file instanceof IFile && !file.isDerived() && + file.getFileExtension()!=null && file.getFileExtension().equalsIgnoreCase("properties")){ + isValied = true; + + //Check if file is not in the blacklist + IPreferenceStore pref = null; + if (Activator.getDefault() != null) + pref = Activator.getDefault().getPreferenceStore(); + + if (pref != null){ + List<CheckItem> list = TapiJIPreferences.getNonRbPatternAsList(); + for (CheckItem item : list){ + if (item.getChecked() && file.getFullPath().toString().matches(item.getName())){ + isValied = false; + + //if properties-file is not RB-file and has ResouceBundleMarker, deletes all ResouceBundleMarker of the file + if (hasResourceBundleMarker(file)) + try { + file.deleteMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE); + } catch (CoreException e) { + } + } + } + } + } + + return isValied; + } + + /** + * Checks whether a RB-file has a problem-marker + */ + public static boolean hasResourceBundleMarker(IResource r){ + try { + if(r.findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0) + return true; + else return false; + } catch (CoreException e) { + return false; + } + } + + + /** + * @return the locale of a given properties-file + */ + public static Locale getLocale(IFile file){ + String localeID = file.getName(); + localeID = localeID.substring(0, localeID.length() - "properties".length() - 1); + String baseBundleName = ResourceBundleManager.getResourceBundleName(file); + + Locale locale; + if (localeID.length() == baseBundleName.length()) { + locale = null; //Default locale + } else { + localeID = localeID.substring(baseBundleName.length() + 1); + String[] localeTokens = localeID.split("_"); + switch (localeTokens.length) { + case 1: + locale = new Locale(localeTokens[0]); + break; + case 2: + locale = new Locale(localeTokens[0], localeTokens[1]); + break; + case 3: + locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]); + break; + default: + locale = new Locale(""); + break; + } + } + return locale; + } + + /** + * @return number of ResourceBundles in the subtree + */ + public static int countRecursiveResourceBundle(IContainer container) { + return getSubResourceBundle(container).size(); + } + + + private static List<String> getSubResourceBundle(IContainer container){ + ResourceBundleManager rbmanager = ResourceBundleManager.getManager(container.getProject()); + + String conatinerId = container.getFullPath().toString(); + List<String> subResourceBundles = new ArrayList<String>(); + + for (String rbId : rbmanager.getResourceBundleIdentifiers()) { + for(IResource r : rbmanager.getResourceBundles(rbId)){ + if (r.getFullPath().toString().contains(conatinerId) && (!subResourceBundles.contains(rbId))){ + subResourceBundles.add(rbId); + } + } + } + return subResourceBundles; + } + + /** + * @param container + * @return Set with all ResourceBundles in this container + */ + public static Set<String> getResourceBundleIds (IContainer container) { + Set<String> resourcebundles = new HashSet<String>(); + + try { + for(IResource r : container.members()){ + if (r instanceof IFile) { + String resourcebundle = getCorrespondingResourceBundleId((IFile)r); + if (resourcebundle != null) resourcebundles.add(resourcebundle); + } + } + } catch (CoreException e) {/*resourcebundle.size()==0*/} + + return resourcebundles; + } + + /** + * + * @param file + * @return ResourceBundle-name or null if no ResourceBundle contains the file + */ + //TODO integrate in ResourceBundleManager + public static String getCorrespondingResourceBundleId (IFile file) { + ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file.getProject()); + String possibleRBId = null; + + if (isResourceBundleFile((IFile) file)) { + possibleRBId = ResourceBundleManager.getResourceBundleId(file); + + for (String rbId : rbmanager.getResourceBundleIdentifiers()){ + if ( possibleRBId.equals(rbId) ) + return possibleRBId; + } + } + return null; + } +} diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java new file mode 100644 index 00000000..d55d7e34 --- /dev/null +++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java @@ -0,0 +1,98 @@ +package org.eclipselabs.tapiji.tools.core.util; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IPath; +import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; + + +public class ResourceUtils { + + private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*"; + private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*"; + + public static boolean isValidResourceKey (String key) { + boolean isValid = false; + + if (key != null && key.trim().length() > 0) { + isValid = key.matches(REGEXP_RESOURCE_KEY); + } + + return isValid; + } + + public static String deriveNonExistingRBName (String nameProposal, ResourceBundleManager manager) { + // Adapt the proposal to the requirements for Resource-Bundle names + nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME, ""); + + int i = 0; + do { + if (manager.getResourceBundleIdentifiers().contains(nameProposal) || nameProposal.length() == 0) { + nameProposal = nameProposal + (++i); + } else + break; + } while (true); + + return nameProposal; + } + + public static boolean isJavaCompUnit (IResource res) { + boolean result = false; + + if (res.getType() == IResource.FILE && !res.isDerived() && + res.getFileExtension().equalsIgnoreCase("java")) { + result = true; + } + + return result; + } + + public static boolean isJSPResource(IResource res) { + boolean result = false; + + if (res.getType() == IResource.FILE && !res.isDerived() && + (res.getFileExtension().equalsIgnoreCase("jsp") || + res.getFileExtension().equalsIgnoreCase("xhtml"))) { + result = true; + } + + return result; + } + + /** + * + * @param baseFolder + * @param targetProjects Projects with a same structure + * @return List of + */ + public static List<IContainer> getCorrespondingFolders(IContainer baseFolder, List<IProject> targetProjects){ + List<IContainer> correspondingFolder = new ArrayList<IContainer>(); + + for(IProject p : targetProjects){ + IContainer c = getCorrespondingFolders(baseFolder, p); + if (c.exists()) correspondingFolder.add(c); + } + + return correspondingFolder; + } + + /** + * + * @param baseFolder + * @param targetProject + * @return a Container with the corresponding path as the baseFolder. The Container doesn't must exist. + */ + public static IContainer getCorrespondingFolders(IContainer baseFolder, IProject targetProject) { + IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo(baseFolder.getProject().getFullPath()); + + if (!relativ_folder.isEmpty()) + return targetProject.getFolder(relativ_folder); + else + return targetProject; + } + +}
0d8d64ea057546e5e2dcd312fe5a80fcb3214460
intellij-community
cleanup (IDEA-90461)--
c
https://github.com/JetBrains/intellij-community
diff --git a/platform/util/src/com/intellij/util/io/ZipUtil.java b/platform/util/src/com/intellij/util/io/ZipUtil.java index bfa564a6298bb..21ace593552b6 100644 --- a/platform/util/src/com/intellij/util/io/ZipUtil.java +++ b/platform/util/src/com/intellij/util/io/ZipUtil.java @@ -179,34 +179,44 @@ public static void extractEntry(ZipEntry entry, final InputStream inputStream, F public static boolean isZipContainsFolder(File zip) throws IOException { ZipFile zipFile = new ZipFile(zip); - Enumeration en = zipFile.entries(); - - while (en.hasMoreElements()) { - ZipEntry zipEntry = (ZipEntry)en.nextElement(); + try { + Enumeration en = zipFile.entries(); - // we do not necessarily get a separate entry for the subdirectory when the file - // in the ZIP archive is placed in a subdirectory, so we need to check if the slash - // is found anywhere in the path - if (zipEntry.getName().indexOf('/') >= 0) { - return true; + while (en.hasMoreElements()) { + ZipEntry zipEntry = (ZipEntry)en.nextElement(); + + // we do not necessarily get a separate entry for the subdirectory when the file + // in the ZIP archive is placed in a subdirectory, so we need to check if the slash + // is found anywhere in the path + if (zipEntry.getName().indexOf('/') >= 0) { + return true; + } } + zipFile.close(); + return false; + } + finally { + zipFile.close(); } - zipFile.close(); - return false; } public static boolean isZipContainsEntry(File zip, String relativePath) throws IOException { ZipFile zipFile = new ZipFile(zip); - Enumeration en = zipFile.entries(); + try { + Enumeration en = zipFile.entries(); - while (en.hasMoreElements()) { - ZipEntry zipEntry = (ZipEntry)en.nextElement(); - if (relativePath.equals(zipEntry.getName())) { - return true; + while (en.hasMoreElements()) { + ZipEntry zipEntry = (ZipEntry)en.nextElement(); + if (relativePath.equals(zipEntry.getName())) { + return true; + } } + zipFile.close(); + return false; + } + finally { + zipFile.close(); } - zipFile.close(); - return false; } /*
ecea6e2615d9c1990e40613d5332e1f2d674a5b5
orientdb
Issue -1404 WAL durability test improvements.--
p
https://github.com/orientechnologies/orientdb
diff --git a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/LocalPaginatedStorageRestoreFromWAL.java b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/LocalPaginatedStorageRestoreFromWAL.java index 65cf3753dbf..e50d40304f2 100755 --- a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/LocalPaginatedStorageRestoreFromWAL.java +++ b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/LocalPaginatedStorageRestoreFromWAL.java @@ -76,8 +76,9 @@ public void beforeMethod() { if (baseDocumentTx.exists()) { baseDocumentTx.open("admin", "admin"); baseDocumentTx.drop(); - } else - baseDocumentTx.create(); + } + + baseDocumentTx.create(); createSchema(baseDocumentTx); } @@ -166,69 +167,74 @@ public class DataPropagationTask implements Callable<Void> { public Void call() throws Exception { Random random = new Random(); - ODatabaseRecordThreadLocal.INSTANCE.set(baseDocumentTx); - List<ORID> testTwoList = new ArrayList<ORID>(); - List<ORID> firstDocs = new ArrayList<ORID>(); + final ODatabaseDocumentTx db = new ODatabaseDocumentTx(baseDocumentTx.getURL()); + db.open("admin", "admin"); + try { + List<ORID> testTwoList = new ArrayList<ORID>(); + List<ORID> firstDocs = new ArrayList<ORID>(); - OClass classOne = baseDocumentTx.getMetadata().getSchema().getClass("TestOne"); - OClass classTwo = baseDocumentTx.getMetadata().getSchema().getClass("TestTwo"); + OClass classOne = db.getMetadata().getSchema().getClass("TestOne"); + OClass classTwo = db.getMetadata().getSchema().getClass("TestTwo"); - for (int i = 0; i < 1000; i++) { - ODocument docOne = new ODocument(classOne); - docOne.field("intProp", random.nextInt()); + for (int i = 0; i < 1000; i++) { + ODocument docOne = new ODocument(classOne); + docOne.field("intProp", random.nextInt()); - byte[] stringData = new byte[256]; - random.nextBytes(stringData); - String stringProp = new String(stringData); + byte[] stringData = new byte[256]; + random.nextBytes(stringData); + String stringProp = new String(stringData); - docOne.field("stringProp", stringProp); + docOne.field("stringProp", stringProp); - Set<String> stringSet = new HashSet<String>(); - for (int n = 0; n < 5; n++) { - stringSet.add("str" + random.nextInt()); - } - docOne.field("stringSet", stringSet); + Set<String> stringSet = new HashSet<String>(); + for (int n = 0; n < 5; n++) { + stringSet.add("str" + random.nextInt()); + } + docOne.field("stringSet", stringSet); - docOne.save(); + docOne.save(); - firstDocs.add(docOne.getIdentity()); + firstDocs.add(docOne.getIdentity()); - if (random.nextBoolean()) { - ODocument docTwo = new ODocument(classTwo); + if (random.nextBoolean()) { + ODocument docTwo = new ODocument(classTwo); - List<String> stringList = new ArrayList<String>(); + List<String> stringList = new ArrayList<String>(); - for (int n = 0; n < 5; n++) { - stringList.add("strnd" + random.nextInt()); - } + for (int n = 0; n < 5; n++) { + stringList.add("strnd" + random.nextInt()); + } - docTwo.field("stringList", stringList); - docTwo.save(); + docTwo.field("stringList", stringList); + docTwo.save(); - testTwoList.add(docTwo.getIdentity()); - } + testTwoList.add(docTwo.getIdentity()); + } - if (!testTwoList.isEmpty()) { - int startIndex = random.nextInt(testTwoList.size()); - int endIndex = random.nextInt(testTwoList.size() - startIndex) + startIndex; + if (!testTwoList.isEmpty()) { + int startIndex = random.nextInt(testTwoList.size()); + int endIndex = random.nextInt(testTwoList.size() - startIndex) + startIndex; - Map<String, ORID> linkMap = new HashMap<String, ORID>(); + Map<String, ORID> linkMap = new HashMap<String, ORID>(); - for (int n = startIndex; n < endIndex; n++) { - ORID docTwoRid = testTwoList.get(n); - linkMap.put(docTwoRid.toString(), docTwoRid); - } + for (int n = startIndex; n < endIndex; n++) { + ORID docTwoRid = testTwoList.get(n); + linkMap.put(docTwoRid.toString(), docTwoRid); + } - docOne.field("linkMap", linkMap); - docOne.save(); - } + docOne.field("linkMap", linkMap); + docOne.save(); + } - boolean deleteDoc = random.nextDouble() <= 0.2; - if (deleteDoc) { - ORID rid = firstDocs.remove(random.nextInt(firstDocs.size())); - baseDocumentTx.delete(rid); + boolean deleteDoc = random.nextDouble() <= 0.2; + if (deleteDoc) { + ORID rid = firstDocs.remove(random.nextInt(firstDocs.size())); + db.delete(rid); + } } + } finally { + db.close(); } return null;
79e6a0ae50cae9718a66f3d07c70852e8ff1806a
hector-client$hector
remove refs to cassandraCluster. This ended up being a bit hackish, but was minimal effort to duplicate functionality and, for now, avoid using HFactory methods in service package
p
https://github.com/hector-client/hector
diff --git a/src/main/java/me/prettyprint/cassandra/service/CassandraClientFactory.java b/src/main/java/me/prettyprint/cassandra/service/CassandraClientFactory.java index e6914ccc1..83e0900c5 100644 --- a/src/main/java/me/prettyprint/cassandra/service/CassandraClientFactory.java +++ b/src/main/java/me/prettyprint/cassandra/service/CassandraClientFactory.java @@ -69,7 +69,7 @@ public CassandraClient create() throws HectorException { try { c = new CassandraClientImpl(createThriftClient(cassandraHost), new KeyspaceFactory(clientMonitor), cassandraHost, pool, - CassandraClusterFactory.INSTANCE.create(pool, cassandraHost), timestampResolution); + pool.getCluster(), timestampResolution); } catch (Exception e) { throw new HectorException(e); } diff --git a/src/main/java/me/prettyprint/cassandra/service/CassandraClientImpl.java b/src/main/java/me/prettyprint/cassandra/service/CassandraClientImpl.java index 4ff4cf5d0..5b24471e2 100644 --- a/src/main/java/me/prettyprint/cassandra/service/CassandraClientImpl.java +++ b/src/main/java/me/prettyprint/cassandra/service/CassandraClientImpl.java @@ -55,7 +55,7 @@ private final CassandraClientPool cassandraClientPool; /** An instance of the cluster object used to manage meta-operations */ - private final CassandraCluster cassandraCluster; + private final Cluster cluster; /** Has the client network connection been closed? */ private boolean closed = false; @@ -72,7 +72,7 @@ public CassandraClientImpl(Cassandra.Client cassandraThriftClient, KeyspaceFactory keyspaceFactory, CassandraHost cassandraHost, CassandraClientPool clientPools, - CassandraCluster cassandraCluster, + Cluster cassandraCluster, TimestampResolution timestampResolution) throws UnknownHostException { this.mySerial = serial.incrementAndGet(); @@ -81,13 +81,13 @@ public CassandraClientImpl(Cassandra.Client cassandraThriftClient, this.keyspaceFactory = keyspaceFactory; this.cassandraClientPool = clientPools; this.timestampResolution = timestampResolution; - this.cassandraCluster = cassandraCluster; + this.cluster = cassandraCluster; } @Override public String getClusterName() throws HectorException { if (clusterName == null) { - clusterName = cassandraCluster.getClusterName(); + clusterName = cluster.getName(); } return clusterName; } @@ -147,13 +147,13 @@ public List<String> getKeyspaces() throws HectorTransportException { @Override public List<CassandraHost> getKnownHosts(boolean fresh) throws HectorException { - return cassandraCluster.getKnownHosts(fresh); + return new ArrayList<CassandraHost>(cluster.getKnownPoolHosts(fresh)); } @Override public String getServerVersion() throws HectorException { if (serverVersion == null) { - serverVersion = cassandraCluster.describeThriftVersion(); + serverVersion = cluster.describeThriftVersion(); } return serverVersion; } diff --git a/src/main/java/me/prettyprint/cassandra/service/CassandraClientPool.java b/src/main/java/me/prettyprint/cassandra/service/CassandraClientPool.java index 6f55d24ce..a1e192cae 100644 --- a/src/main/java/me/prettyprint/cassandra/service/CassandraClientPool.java +++ b/src/main/java/me/prettyprint/cassandra/service/CassandraClientPool.java @@ -174,4 +174,10 @@ public interface CassandraClientPool { * @return */ CassandraClientMonitorMBean getMbean(); + + /** + * Short-term work around until constructor complexity can be refactored + * @return + */ + Cluster getCluster(); } diff --git a/src/main/java/me/prettyprint/cassandra/service/CassandraClientPoolImpl.java b/src/main/java/me/prettyprint/cassandra/service/CassandraClientPoolImpl.java index 5613acd69..07ccd9a22 100644 --- a/src/main/java/me/prettyprint/cassandra/service/CassandraClientPoolImpl.java +++ b/src/main/java/me/prettyprint/cassandra/service/CassandraClientPoolImpl.java @@ -34,11 +34,13 @@ private final CassandraClientMonitor clientMonitor; private CassandraHostConfigurator cassandraHostConfigurator; + private Cluster cluster; public CassandraClientPoolImpl(CassandraClientMonitor clientMonitor) { log.info("Creating a CassandraClientPool"); pools = new HashMap<CassandraHost, CassandraClientPoolByHost>(); this.clientMonitor = clientMonitor; + this.cluster = new Cluster("Default Cluster", this); } public CassandraClientPoolImpl(CassandraClientMonitor clientMonitor, @@ -49,12 +51,14 @@ public CassandraClientPoolImpl(CassandraClientMonitor clientMonitor, log.debug("Maybe creating pool-by-host instance for {} at {}", cassandraHost, this); getPool(cassandraHost); } + this.cluster = new Cluster("Default Cluster", this); } public CassandraClientPoolImpl(CassandraClientMonitor clientMonitor, CassandraHostConfigurator cassandraHostConfigurator) { this(clientMonitor, cassandraHostConfigurator.buildCassandraHosts()); - this.cassandraHostConfigurator = cassandraHostConfigurator; + this.cassandraHostConfigurator = cassandraHostConfigurator; + this.cluster = new Cluster("Default Cluster", this); } @@ -265,6 +269,14 @@ public void addCassandraHost(CassandraHost cassandraHost) { } } } + + @Override + public Cluster getCluster() { + + return cluster; + } + + } diff --git a/src/main/java/me/prettyprint/cassandra/service/CassandraCluster.java b/src/main/java/me/prettyprint/cassandra/service/CassandraCluster.java deleted file mode 100644 index eda67f568..000000000 --- a/src/main/java/me/prettyprint/cassandra/service/CassandraCluster.java +++ /dev/null @@ -1,68 +0,0 @@ -package me.prettyprint.cassandra.service; - -import java.util.List; -import java.util.Map; -import java.util.Set; - - -import me.prettyprint.cassandra.model.HectorException; -import me.prettyprint.cassandra.model.PoolExhaustedException; - -import org.apache.cassandra.thrift.TokenRange; - -/** - * A class to encapsulate the "Meta-API" portion of the thrift API, the definitions - * historically at bottom of the cassandra.thrift file - * - * @author Nate McCall ([email protected]) - */ -public interface CassandraCluster { - - /** - * Returns a Set of Strings listing the available keyspaces. This includes - * the system keyspace. - */ - Set<String> describeKeyspaces() throws HectorException; - - /** - * Returns the name of the cluster as defined by the ClusterName configuration - * element in the configuration file - */ - String describeClusterName() throws HectorException; - - /** - * Returns the Thrift API version. Note: this is not the version of Cassandra, but - * the underlying Thrift API - */ - String describeThriftVersion() throws HectorException; - - /** - * Describe the structure of the ring for a given Keyspace - * - */ - List<TokenRange> describeRing(String keyspace) throws HectorException; - - /** - * Describe the given keyspace. The key for the outer map is the ColumnFamily name. - * The inner map contains configuration properties mapped to their values. - */ - Map<String, Map<String, String>> describeKeyspace(String keyspace) throws HectorException; - - /** - * Queries the cluster for its name and returns it. - * @return - */ - String getClusterName() throws HectorException; - - /** - * Gets the list of known hosts. - * This method is not failover-safe. If will fail fast if the contacted host is down. - * - * @param fresh whether the get fresh list of hosts or reuse the possibly previous value cached. - * @return - * @throws IllegalStateException - * @throws PoolExhaustedException - */ - List<CassandraHost> getKnownHosts(boolean fresh) throws HectorException; - -} diff --git a/src/main/java/me/prettyprint/cassandra/service/CassandraClusterFactory.java b/src/main/java/me/prettyprint/cassandra/service/CassandraClusterFactory.java deleted file mode 100644 index 064be4573..000000000 --- a/src/main/java/me/prettyprint/cassandra/service/CassandraClusterFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -package me.prettyprint.cassandra.service; - -import me.prettyprint.cassandra.model.HectorException; - - -/** - * Controls access to CassandraCluster, as we need a live CassandraClient - * in order to do anything useful - * - * @author Nate McCall ([email protected]) - * - */ -public enum CassandraClusterFactory { - - INSTANCE; - - public static CassandraClusterFactory getInstance() { - return INSTANCE; - } - - - private CassandraClusterFactory() { - } - - public CassandraCluster create(CassandraClientPool cassandraClientPool, CassandraHost cassandraHost) - throws HectorException { - return new CassandraClusterImpl(cassandraClientPool, cassandraHost); - } - -} diff --git a/src/main/java/me/prettyprint/cassandra/service/CassandraClusterImpl.java b/src/main/java/me/prettyprint/cassandra/service/CassandraClusterImpl.java deleted file mode 100644 index 48405828c..000000000 --- a/src/main/java/me/prettyprint/cassandra/service/CassandraClusterImpl.java +++ /dev/null @@ -1,220 +0,0 @@ -package me.prettyprint.cassandra.service; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import me.prettyprint.cassandra.model.HectorException; -import me.prettyprint.cassandra.service.CassandraClient.FailoverPolicy; - -import org.apache.cassandra.thrift.Cassandra; -import org.apache.cassandra.thrift.TokenRange; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Implementation of the {@link CassandraCluster} interface. - * - * @author Nate McCall ([email protected]) - */ -/* package */class CassandraClusterImpl implements CassandraCluster { - - private static Logger log = LoggerFactory.getLogger(CassandraClusterImpl.class); - - private static final String KEYSPACE_SYSTEM = "system"; - - private final CassandraClientPool cassandraClientPool; - private final FailoverPolicy failoverPolicy; - private List<CassandraHost> knownHosts; - private final CassandraClientMonitor cassandraClientMonitor; - private final CassandraHost preferredCassandraHost; - private final ExceptionsTranslator xtrans; - - /** - * @param cassandraClientPool - * The pool from which to borrow clients for the meta operations. - * @param preferredClientUrl - * a url:port format. If provided, a client by this name will be - * borrowed from the pool. If not, a default client, if exists in the - * pool, will be borrowed. - */ - public CassandraClusterImpl(CassandraClientPool cassandraClientPool, CassandraHost prefferedHost) - throws HectorException { - this.cassandraClientPool = cassandraClientPool; - this.failoverPolicy = FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE; - this.cassandraClientMonitor = JmxMonitor.getInstance().getCassandraMonitor(); - this.preferredCassandraHost = prefferedHost; - xtrans = new ExceptionsTranslatorImpl(); - } - - @Override - public List<CassandraHost> getKnownHosts(boolean fresh) throws HectorException { - if (fresh || knownHosts == null) { - CassandraClient client = borrow(); - try { - knownHosts = new ArrayList<CassandraHost>(buildHostNames(client.getCassandra())); - } finally { - cassandraClientPool.releaseClient(client); - } - } - return knownHosts; - } - - - - private void operateWithFailover(Operation<?> op) throws HectorException { - CassandraClient client = null; - try { - client = borrow(); - FailoverOperator operator = new FailoverOperator(failoverPolicy, getKnownHosts(false), - cassandraClientMonitor, client, cassandraClientPool, null); - client = operator.operate(op); - } finally { - try { - release(client); - } catch (Exception e) { - log.error("Unable to release a client", e); - } - } - } - - private CassandraClient borrow() throws HectorException { - if (preferredCassandraHost == null) { - return cassandraClientPool.borrowClient(); - } else { - return cassandraClientPool.borrowClient(preferredCassandraHost); - - } - } - - private void release(CassandraClient c) throws Exception { - if (c != null) { - cassandraClientPool.releaseClient(c); - } - } - - @Override - public Set<String> describeKeyspaces() throws HectorException { - Operation<Set<String>> op = new Operation<Set<String>>(OperationType.META_READ) { - @Override - public Set<String> execute(Cassandra.Client cassandra) throws HectorException { - try { - return cassandra.describe_keyspaces(); - } catch (Exception e) { - throw xtrans.translate(e); - } - } - }; - operateWithFailover(op); - return op.getResult(); - } - - @Override - public String describeClusterName() throws HectorException { - Operation<String> op = new Operation<String>(OperationType.META_READ) { - @Override - public String execute(Cassandra.Client cassandra) throws HectorException { - try { - return cassandra.describe_cluster_name(); - } catch (Exception e) { - throw xtrans.translate(e); - } - } - }; - operateWithFailover(op); - return op.getResult(); - } - - @Override - public String describeThriftVersion() throws HectorException { - Operation<String> op = new Operation<String>(OperationType.META_READ) { - @Override - public String execute(Cassandra.Client cassandra) throws HectorException { - try { - return cassandra.describe_version(); - } catch (Exception e) { - throw xtrans.translate(e); - } - } - }; - operateWithFailover(op); - return op.getResult(); - } - - @Override - public List<TokenRange> describeRing(final String keyspace) throws HectorException { - Operation<List<TokenRange>> op = new Operation<List<TokenRange>>(OperationType.META_READ) { - @Override - public List<TokenRange> execute(Cassandra.Client cassandra) throws HectorException { - try { - return cassandra.describe_ring(keyspace); - } catch (Exception e) { - throw xtrans.translate(e); - } - } - }; - operateWithFailover(op); - return op.getResult(); - } - - private Set<CassandraHost> buildHostNames(Cassandra.Client cassandra) throws HectorException { - try { - Set<CassandraHost> hostnames = new HashSet<CassandraHost>(); - for (String keyspace : cassandra.describe_keyspaces()) { - if (!keyspace.equals(KEYSPACE_SYSTEM)) { - List<TokenRange> tokenRanges = cassandra.describe_ring(keyspace); - for (TokenRange tokenRange : tokenRanges) { - for (String host : tokenRange.getEndpoints()) { - hostnames.add(new CassandraHost(host + ":" + preferredCassandraHost.getPort())); - } - } - break; - } - } - return hostnames; - } catch (Exception e) { - throw xtrans.translate(e); - } - } - - @Override - public Map<String, Map<String, String>> describeKeyspace(final String keyspace) - throws HectorException { - Operation<Map<String, Map<String, String>>> op = new Operation<Map<String, Map<String, String>>>( - OperationType.META_READ) { - @Override - public Map<String, Map<String, String>> execute(Cassandra.Client cassandra) - throws HectorException { - try { - return cassandra.describe_keyspace(keyspace); - } catch (org.apache.cassandra.thrift.NotFoundException nfe) { - setException(xtrans.translate(nfe)); - return null; - } catch (Exception e) { - throw xtrans.translate(e); - } - } - }; - operateWithFailover(op); - return op.getResult(); - } - - @Override - public String getClusterName() throws HectorException { - Operation<String> op = new Operation<String>(OperationType.META_READ) { - @Override - public String execute(Cassandra.Client cassandra) throws HectorException { - try { - return cassandra.describe_cluster_name(); - } catch (Exception e) { - throw xtrans.translate(e); - } - - } - }; - operateWithFailover(op); - return op.getResult(); - } -} diff --git a/src/main/java/me/prettyprint/cassandra/service/Cluster.java b/src/main/java/me/prettyprint/cassandra/service/Cluster.java index 9b340750d..1ef76774f 100644 --- a/src/main/java/me/prettyprint/cassandra/service/Cluster.java +++ b/src/main/java/me/prettyprint/cassandra/service/Cluster.java @@ -59,6 +59,15 @@ public Cluster(String clusterName, CassandraHostConfigurator cassandraHostConfig xtrans = new ExceptionsTranslatorImpl(); } + public Cluster(String clusterName, CassandraClientPool pool) { + this.pool = pool; + name = clusterName; + configurator = null; + failoverPolicy = FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE; + cassandraClientMonitor = JmxMonitor.getInstance().getCassandraMonitor(); + xtrans = new ExceptionsTranslatorImpl(); + } + public Set<CassandraHost> getKnownPoolHosts(boolean refresh) { if (refresh || knownPoolHosts == null) { knownPoolHosts = pool.getKnownHosts(); @@ -91,7 +100,7 @@ public Set<String> getClusterHosts(boolean refresh) { * @param skipApplyConfig */ public void addHost(CassandraHost cassandraHost, boolean skipApplyConfig) { - if (!skipApplyConfig) { + if (!skipApplyConfig && configurator != null) { configurator.applyConfig(cassandraHost); } pool.addCassandraHost(cassandraHost); diff --git a/src/test/java/me/prettyprint/cassandra/service/CassandraClientTest.java b/src/test/java/me/prettyprint/cassandra/service/CassandraClientTest.java index ff1541dce..4a09d36af 100644 --- a/src/test/java/me/prettyprint/cassandra/service/CassandraClientTest.java +++ b/src/test/java/me/prettyprint/cassandra/service/CassandraClientTest.java @@ -84,7 +84,7 @@ public void testGetKeyspaces() throws HectorException { @Test public void testGetClusterName() throws HectorException { String name = client.getClusterName(); - assertEquals("Test Cluster", name); + assertEquals("Default Cluster", name); } @Test
895ccdf8615c0b9bbbef60dbfc88614a6f27926b
tapiji
updated licenses
p
https://github.com/tapiji/tapiji
diff --git a/at.ac.tuwien.inso.eclipse.rbe/epl-v10.html b/at.ac.tuwien.inso.eclipse.rbe/epl-v10.html new file mode 100644 index 00000000..ed4b1966 --- /dev/null +++ b/at.ac.tuwien.inso.eclipse.rbe/epl-v10.html @@ -0,0 +1,328 @@ +<html xmlns:o="urn:schemas-microsoft-com:office:office" +xmlns:w="urn:schemas-microsoft-com:office:word" +xmlns="http://www.w3.org/TR/REC-html40"> + +<head> +<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> +<meta name=ProgId content=Word.Document> +<meta name=Generator content="Microsoft Word 9"> +<meta name=Originator content="Microsoft Word 9"> +<link rel=File-List +href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> +<title>Eclipse Public License - Version 1.0</title> +<!--[if gte mso 9]><xml> + <o:DocumentProperties> + <o:Revision>2</o:Revision> + <o:TotalTime>3</o:TotalTime> + <o:Created>2004-03-05T23:03:00Z</o:Created> + <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> + <o:Pages>4</o:Pages> + <o:Words>1626</o:Words> + <o:Characters>9270</o:Characters> + <o:Lines>77</o:Lines> + <o:Paragraphs>18</o:Paragraphs> + <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> + <o:Version>9.4402</o:Version> + </o:DocumentProperties> +</xml><![endif]--><!--[if gte mso 9]><xml> + <w:WordDocument> + <w:TrackRevisions/> + </w:WordDocument> +</xml><![endif]--> +<style> +<!-- + /* Font Definitions */ +@font-face + {font-family:Tahoma; + panose-1:2 11 6 4 3 5 4 4 2 4; + mso-font-charset:0; + mso-generic-font-family:swiss; + mso-font-pitch:variable; + mso-font-signature:553679495 -2147483648 8 0 66047 0;} + /* Style Definitions */ +p.MsoNormal, li.MsoNormal, div.MsoNormal + {mso-style-parent:""; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p + {margin-right:0in; + mso-margin-top-alt:auto; + mso-margin-bottom-alt:auto; + margin-left:0in; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p.BalloonText, li.BalloonText, div.BalloonText + {mso-style-name:"Balloon Text"; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:8.0pt; + font-family:Tahoma; + mso-fareast-font-family:"Times New Roman";} +@page Section1 + {size:8.5in 11.0in; + margin:1.0in 1.25in 1.0in 1.25in; + mso-header-margin:.5in; + mso-footer-margin:.5in; + mso-paper-source:0;} +div.Section1 + {page:Section1;} +--> +</style> +</head> + +<body lang=EN-US style='tab-interval:.5in'> + +<div class=Section1> + +<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> +</p> + +<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER +THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, +REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE +OF THIS AGREEMENT.</span> </p> + +<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> + +<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +in the case of the initial Contributor, the initial code and documentation +distributed under this Agreement, and<br clear=left> +b) in the case of each subsequent Contributor:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +changes to the Program, and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +additions to the Program;</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where +such changes and/or additions to the Program originate from and are distributed +by that particular Contributor. A Contribution 'originates' from a Contributor +if it was added to the Program by such Contributor itself or anyone acting on +such Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in conjunction +with the Program under their own license agreement, and (ii) are not derivative +works of the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or +entity that distributes the Program.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Licensed Patents &quot; mean patent +claims licensable by a Contributor which are necessarily infringed by the use +or sale of its Contribution alone or when combined with the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions +distributed in accordance with this Agreement.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who +receives the Program under this Agreement, including all Contributors.</span> </p> + +<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +Subject to the terms of this Agreement, each Contributor hereby grants Recipient +a non-exclusive, worldwide, royalty-free copyright license to<span +style='color:red'> </span>reproduce, prepare derivative works of, publicly +display, publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and object code +form.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free +patent license under Licensed Patents to make, use, sell, offer to sell, import +and otherwise transfer the Contribution of such Contributor, if any, in source +code and object code form. This patent license shall apply to the combination +of the Contribution and the Program if, at the time the Contribution is added +by the Contributor, such addition of the Contribution causes such combination +to be covered by the Licensed Patents. The patent license shall not apply to +any other combinations which include the Contribution. No hardware per se is +licensed hereunder. </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c) +Recipient understands that although each Contributor grants the licenses to its +Contributions set forth herein, no assurances are provided by any Contributor +that the Program does not infringe the patent or other intellectual property +rights of any other entity. Each Contributor disclaims any liability to Recipient +for claims brought by any other entity based on infringement of intellectual +property rights or otherwise. As a condition to exercising the rights and +licenses granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For example, +if a third party patent license is required to allow Recipient to distribute +the Program, it is Recipient's responsibility to acquire that license before +distributing the Program.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d) +Each Contributor represents that to its knowledge it has sufficient copyright +rights in its Contribution, if any, to grant the copyright license set forth in +this Agreement. </span></p> + +<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> + +<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the +Program in object code form under its own license agreement, provided that:</span> +</p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it complies with the terms and conditions of this Agreement; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +its license agreement:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +effectively excludes on behalf of all Contributors all liability for damages, +including direct, indirect, special, incidental and consequential damages, such +as lost profits; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) +states that any provisions which differ from this Agreement are offered by that +Contributor alone and not by any other party; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv) +states that source code for the Program is available from such Contributor, and +informs licensees how to obtain it in a reasonable manner on or through a +medium customarily used for software exchange.<span style='color:blue'> </span></span></p> + +<p><span style='font-size:10.0pt'>When the Program is made available in source +code form:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it must be made available under this Agreement; and </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a +copy of this Agreement must be included with each copy of the Program. </span></p> + +<p><span style='font-size:10.0pt'>Contributors may not remove or alter any +copyright notices contained within the Program. </span></p> + +<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the +originator of its Contribution, if any, in a manner that reasonably allows +subsequent Recipients to identify the originator of the Contribution. </span></p> + +<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> + +<p><span style='font-size:10.0pt'>Commercial distributors of software may +accept certain responsibilities with respect to end users, business partners +and the like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes the +Program in a commercial product offering, such Contributor (&quot;Commercial +Contributor&quot;) hereby agrees to defend and indemnify every other +Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and +costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to +the extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may participate +in any such claim at its own expense.</span> </p> + +<p><span style='font-size:10.0pt'>For example, a Contributor might include the +Program in a commercial product offering, Product X. That Contributor is then a +Commercial Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance claims and +warranties are such Commercial Contributor's responsibility alone. Under this +section, the Commercial Contributor would have to defend claims against the +other Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages.</span> </p> + +<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, +WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and distributing the +Program and assumes all risks associated with its exercise of rights under this +Agreement , including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs or +equipment, and unavailability or interruption of operations. </span></p> + +<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF +THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES.</span> </p> + +<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> + +<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid +or unenforceable under applicable law, it shall not affect the validity or +enforceability of the remainder of the terms of this Agreement, and without +further action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable.</span> </p> + +<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Program itself (excluding combinations of the Program with +other software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the date +such litigation is filed. </span></p> + +<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement +shall terminate if it fails to comply with any of the material terms or +conditions of this Agreement and does not cure such failure in a reasonable +period of time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive. </span></p> + +<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute +copies of this Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The Agreement +Steward reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the initial +Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved.</span> </p> + +<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the +State of New York and the intellectual property laws of the United States of +America. No party to this Agreement will bring a legal action under this +Agreement more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation.</span> </p> + +<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> + +</div> + +</body> + +</html> \ No newline at end of file
a768016779e3bdbddf310d2d861e74830a62d16c
elasticsearch
Allow to configure a common logger prefix using- `es.logger.prefix` system prop
a
https://github.com/elastic/elasticsearch
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/common/logging/Loggers.java b/modules/elasticsearch/src/main/java/org/elasticsearch/common/logging/Loggers.java index 74a5a3d518fe9..a19cac5adf1ea 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/common/logging/Loggers.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/common/logging/Loggers.java @@ -40,6 +40,8 @@ */ public class Loggers { + private final static String commonPrefix = System.getProperty("es.logger.prefix", ""); + public static final String SPACE = " "; private static boolean consoleLoggingEnabled = true; @@ -152,6 +154,6 @@ private static String getLoggerName(String name) { if (name.startsWith("org.elasticsearch.")) { return name.substring("org.elasticsearch.".length()); } - return name; + return commonPrefix + name; } }
21f80973533b8c64032d864d8299bcb05f54445e
hbase
HBASE-2040 Fixes to group commit--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@889775 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 1396c5306bca..04cb8e73780e 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -123,6 +123,7 @@ Release 0.21.0 - Unreleased empty oldlogfile.log (Lars George via Stack) HBASE-2022 NPE in housekeeping kills RS HBASE-2033 Shell scan 'limit' is off by one + HBASE-2040 Fixes to group commit IMPROVEMENTS HBASE-1760 Cleanup TODOs in HTable diff --git a/src/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java b/src/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java index 7ba395d51aa4..a17baaeb3e94 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java @@ -237,7 +237,7 @@ public HLog(final FileSystem fs, final Path dir, final HBaseConfiguration conf, ", flushlogentries=" + this.flushlogentries + ", optionallogflushinternal=" + this.optionalFlushInterval + "ms"); rollWriter(); - logSyncerThread = new LogSyncer(this.flushlogentries); + logSyncerThread = new LogSyncer(this.optionalFlushInterval); Threads.setDaemonThreadRunning(logSyncerThread, Thread.currentThread().getName() + ".logSyncer"); } @@ -726,9 +726,9 @@ class LogSyncer extends Thread { // Condition used to signal that the sync is done private final Condition syncDone = lock.newCondition(); - private final int optionalFlushInterval; + private final long optionalFlushInterval; - LogSyncer(int optionalFlushInterval) { + LogSyncer(long optionalFlushInterval) { this.optionalFlushInterval = optionalFlushInterval; } @@ -739,7 +739,12 @@ public void run() { // Wait until something has to be synced or do it if we waited enough // time (useful if something appends but does not sync). - queueEmpty.await(this.optionalFlushInterval, TimeUnit.MILLISECONDS); + if (!queueEmpty.await(this.optionalFlushInterval, + TimeUnit.MILLISECONDS)) { + forceSync = true; + } + + // We got the signal, let's syncFS. We currently own the lock so new // writes are waiting to acquire it in addToSyncQueue while the ones
359a2756e623e605aaf29a1f3c7181666fae775c
orientdb
Improved automatic backup management of errors--
p
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseWrapperAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseWrapperAbstract.java index b2f87de61ad..1793a65f43c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseWrapperAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseWrapperAbstract.java @@ -306,7 +306,7 @@ public void unregisterListener(final ODatabaseListener iListener) { underlying.unregisterListener(iListener); } - public <V> V callInLock(Callable<V> iCallable, boolean iExclusiveLock) { + public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) { return getStorage().callInLock(iCallable, iExclusiveLock); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalLHPEPS.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalLHPEPS.java index e310b14a2db..bcdc773873e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalLHPEPS.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalLHPEPS.java @@ -348,7 +348,7 @@ private void initState() { public void truncate() throws IOException { storage.checkForClusterPermissions(getName()); - + acquireExclusiveLock(); try { long localSize = size; @@ -451,6 +451,11 @@ public boolean addPhysicalPosition(OPhysicalPosition iPPosition) throws IOExcept } } + @Override + public String toString() { + return name; + } + public OPhysicalPosition getPhysicalPosition(OPhysicalPosition iPPosition) throws IOException { acquireSharedLock(); try { diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java index a9f44d8614f..3998de6139a 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java @@ -1451,10 +1451,13 @@ protected int registerDataSegment(final OStorageDataConfiguration iConfig) throw private int createClusterFromConfig(final OStorageClusterConfiguration iConfig) throws IOException { OCluster cluster = clusterMap.get(iConfig.getName()); - if (cluster != null) { - if (cluster instanceof OClusterLocal) + if (cluster instanceof OClusterLocal && iConfig instanceof OStoragePhysicalClusterLHPEPSConfiguration) + clusterMap.remove(iConfig.getName()); + else if (cluster != null) { + if (cluster instanceof OClusterLocal) { // ALREADY CONFIGURED, JUST OVERWRITE CONFIG ((OClusterLocal) cluster).configure(this, iConfig); + } return -1; }
f83662f51e2bbcb77a760d23695dda66fdfb6a11
Delta Spike
DELTASPIKE-378 unify handling of defaultValue
c
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 6b3ada263..b7802a38b 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 @@ -108,15 +108,9 @@ public static synchronized void freeConfigSources() */ public static String getPropertyValue(String key, String defaultValue) { - String configuredValue = getPropertyValue(key); - if (configuredValue == null) - { - LOG.log(Level.FINE, "no configured value found for key {0}, using default value {1}.", - new Object[]{key, defaultValue}); + String value = getPropertyValue(key); - configuredValue = defaultValue; - } - return configuredValue; + return fallbackToDefaultIfEmpty(key, value, defaultValue); } /** @@ -189,12 +183,7 @@ public static String getProjectStageAwarePropertyValue(String key, String defaul { String value = getProjectStageAwarePropertyValue(key); - if (value == null || value.length() == 0) - { - value = defaultValue; - } - - return value; + return fallbackToDefaultIfEmpty(key, value, defaultValue); } /** @@ -263,12 +252,7 @@ public static String getPropertyAwarePropertyValue(String key, String property, { String value = getPropertyAwarePropertyValue(key, property); - if (value == null || value.length() == 0) - { - value = defaultValue; - } - - return value; + return fallbackToDefaultIfEmpty(key, value, defaultValue); } /** @@ -402,4 +386,18 @@ private static ProjectStage getProjectStage() return projectStage; } + private static String fallbackToDefaultIfEmpty(String key, String value, String defaultValue) + { + if (value == null || value.length() == 0) + { + LOG.log(Level.FINE, "no configured value found for key {0}, using default value {1}.", + new Object[]{key, defaultValue}); + + return defaultValue; + } + + return value; + } + + }
ac61b13a7c8284dea58ca4d2a046a44d317ced00
spring-framework
AnnotatedElementUtils wraps unexpected exceptions- with descriptive IllegalStateException--Issue: SPR-10441-
c
https://github.com/spring-projects/spring-framework
diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java index 8494c0f51d25..78fc584adb46 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java @@ -42,7 +42,6 @@ public class AnnotatedElementUtils { public static Set<String> getMetaAnnotationTypes(AnnotatedElement element, String annotationType) { final Set<String> types = new LinkedHashSet<String>(); process(element, annotationType, true, new Processor<Object>() { - @Override public Object process(Annotation annotation, int metaDepth) { if (metaDepth > 0) { @@ -50,7 +49,6 @@ public Object process(Annotation annotation, int metaDepth) { } return null; } - @Override public void postProcess(Annotation annotation, Object result) { } @@ -60,7 +58,6 @@ public void postProcess(Annotation annotation, Object result) { public static boolean hasMetaAnnotationTypes(AnnotatedElement element, String annotationType) { return Boolean.TRUE.equals(process(element, annotationType, true, new Processor<Boolean>() { - @Override public Boolean process(Annotation annotation, int metaDepth) { if (metaDepth > 0) { @@ -68,7 +65,6 @@ public Boolean process(Annotation annotation, int metaDepth) { } return null; } - @Override public void postProcess(Annotation annotation, Boolean result) { } @@ -77,12 +73,10 @@ public void postProcess(Annotation annotation, Boolean result) { public static boolean isAnnotated(AnnotatedElement element, String annotationType) { return Boolean.TRUE.equals(process(element, annotationType, true, new Processor<Boolean>() { - @Override public Boolean process(Annotation annotation, int metaDepth) { return Boolean.TRUE; } - @Override public void postProcess(Annotation annotation, Boolean result) { } @@ -97,12 +91,10 @@ public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement elem final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) { return process(element, annotationType, true, new Processor<AnnotationAttributes>() { - @Override public AnnotationAttributes process(Annotation annotation, int metaDepth) { return AnnotationUtils.getAnnotationAttributes(annotation, classValuesAsString, nestedAnnotationsAsMap); } - @Override public void postProcess(Annotation annotation, AnnotationAttributes result) { for (String key : result.keySet()) { @@ -117,8 +109,7 @@ public void postProcess(Annotation annotation, AnnotationAttributes result) { }); } - public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element, - final String annotationType) { + public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element, String annotationType) { return getAllAnnotationAttributes(element, annotationType, false, false); } @@ -127,7 +118,6 @@ public static MultiValueMap<String, Object> getAllAnnotationAttributes(Annotated final MultiValueMap<String, Object> attributes = new LinkedMultiValueMap<String, Object>(); process(element, annotationType, false, new Processor<Void>() { - @Override public Void process(Annotation annotation, int metaDepth) { if (annotation.annotationType().getName().equals(annotationType)) { @@ -138,7 +128,6 @@ public Void process(Annotation annotation, int metaDepth) { } return null; } - @Override public void postProcess(Annotation annotation, Void result) { for (String key : attributes.keySet()) { @@ -157,12 +146,10 @@ public void postProcess(Annotation annotation, Void result) { /** * Process all annotations of the specified {@code annotationType} and * recursively all meta-annotations on the specified {@code element}. - * * <p>If the {@code traverseClassHierarchy} flag is {@code true} and the sought * annotation is neither <em>directly present</em> on the given element nor * present on the given element as a meta-annotation, then the algorithm will * recursively search through the class hierarchy of the given element. - * * @param element the annotated element * @param annotationType the annotation type to find * @param traverseClassHierarchy whether or not to traverse up the class @@ -172,19 +159,23 @@ public void postProcess(Annotation annotation, Void result) { */ private static <T> T process(AnnotatedElement element, String annotationType, boolean traverseClassHierarchy, Processor<T> processor) { - return doProcess(element, annotationType, traverseClassHierarchy, processor, new HashSet<AnnotatedElement>(), 0); + + try { + return doProcess(element, annotationType, traverseClassHierarchy, processor, new HashSet<AnnotatedElement>(), 0); + } + catch (Throwable ex) { + throw new IllegalStateException("Failed to introspect annotations: " + element, ex); + } } /** * Perform the search algorithm for the {@link #process} method, avoiding * endless recursion by tracking which annotated elements have already been * <em>visited</em>. - * * <p>The {@code metaDepth} parameter represents the depth of the annotation * relative to the initial element. For example, an annotation that is * <em>present</em> on the element will have a depth of 0; a meta-annotation * will have a depth of 1; and a meta-meta-annotation will have a depth of 2. - * * @param element the annotated element * @param annotationType the annotation type to find * @param traverseClassHierarchy whether or not to traverse up the class @@ -198,10 +189,8 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType, Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth) { if (visited.add(element)) { - - Annotation[] annotations = traverseClassHierarchy ? element.getDeclaredAnnotations() - : element.getAnnotations(); - + Annotation[] annotations = + (traverseClassHierarchy ? element.getDeclaredAnnotations() : element.getAnnotations()); for (Annotation annotation : annotations) { if (annotation.annotationType().getName().equals(annotationType) || metaDepth > 0) { T result = processor.process(annotation, metaDepth); @@ -216,7 +205,6 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType, } } } - for (Annotation annotation : annotations) { if (!isInJavaLangAnnotationPackage(annotation)) { T result = doProcess(annotation.annotationType(), annotationType, traverseClassHierarchy, @@ -227,7 +215,6 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType, } } } - if (traverseClassHierarchy && element instanceof Class) { Class<?> superclass = ((Class<?>) element).getSuperclass(); if (superclass != null && !superclass.equals(Object.class)) { @@ -239,7 +226,6 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType, } } } - return null; } @@ -252,13 +238,11 @@ private static interface Processor<T> { /** * Called to process the annotation. - * * <p>The {@code metaDepth} parameter represents the depth of the * annotation relative to the initial element. For example, an annotation * that is <em>present</em> on the element will have a depth of 0; a * meta-annotation will have a depth of 1; and a meta-meta-annotation * will have a depth of 2. - * * @param annotation the annotation to process * @param metaDepth the depth of the annotation relative to the initial element * @return the result of the processing or {@code null} to continue
e0f983040c7680fce1b2c3b662ebad63a01e8d31
drools
[BZ-980385] fix comparison of 2 timer nodes--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java index 44a10b5a584..9cbb49c0720 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java @@ -2170,4 +2170,39 @@ public void testAddSameResourceTwice() { assertTrue(kbuilder.hasResults(ResultSeverity.INFO, ResultSeverity.WARNING, ResultSeverity.ERROR)); } + @Test + public void testTwoTimers() { + // BZ-980385 + String str = + "import java.util.Date\n" + + "import java.util.List\n" + + "\n" + + "global List dates\n" + + "\n" + + "rule \"intervalRule\"\n" + + " timer(int: 200ms 100ms)\n" + + "when\n" + + " String(this == \"intervalRule\")\n" + + "then\n" + + " Date date = new Date();\n" + + " dates.add(date);\n" + + "end\n" + + "\n" + + "\n" + + "// this rule stops timer\n" + + "rule \"stopIntervalRule\"\n" + + " timer(int: 320ms)\n" + + "when\n" + + " $s : String(this == \"intervalRule\")\n" + + "then\n" + + " retract($s);\n" + + "end\n"; + + KieServices ks = KieServices.Factory.get(); + + KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str ); + assertEquals(0, ks.newKieBuilder( kfs ).buildAll().getResults().getMessages().size()); + + KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession(); + } } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java b/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java index 7259b924e9c..cab2d915de6 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java @@ -149,11 +149,12 @@ public String toString() { public int hashCode() { int hash = this.leftInput.hashCode() ^ this.timer.hashCode(); - for (int i = 0; i < calendarNames.length; i++) { - hash = hash ^ calendarNames[i].hashCode(); + if (calendarNames != null) { + for (int i = 0; i < calendarNames.length; i++) { + hash = hash ^ calendarNames[i].hashCode(); + } } return hash; - } public boolean equals(final Object object) { @@ -167,14 +168,16 @@ public boolean equals(final Object object) { final TimerNode other = (TimerNode) object; - if (other.getCalendarNames().length != calendarNames.length) { - return false; - } - - for (int i = 0; i < calendarNames.length; i++) { - if (!other.getCalendarNames()[i].equals(calendarNames[i])) { + if (calendarNames != null) { + if (other.getCalendarNames() == null || other.getCalendarNames().length != calendarNames.length) { return false; } + + for (int i = 0; i < calendarNames.length; i++) { + if (!other.getCalendarNames()[i].equals(calendarNames[i])) { + return false; + } + } } if ( declarations != null ) {
50ac59fa8530bbd35c21cd61cfd64d2bd7d3eb57
hbase
HBASE-11558 Caching set on Scan object gets lost- when using TableMapReduceUtil in 0.95+ (Ishan Chhabra)--
c
https://github.com/apache/hbase
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java index f7531eec052e..eea3b72fe79e 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java @@ -904,6 +904,9 @@ public static ClientProtos.Scan toScan( if (scan.getConsistency() == Consistency.TIMELINE) { scanBuilder.setConsistency(toConsistency(scan.getConsistency())); } + if (scan.getCaching() > 0) { + scanBuilder.setCaching(scan.getCaching()); + } return scanBuilder.build(); } @@ -986,6 +989,9 @@ public static Scan toScan( if (proto.hasConsistency()) { scan.setConsistency(toConsistency(proto.getConsistency())); } + if (proto.hasCaching()) { + scan.setCaching(proto.getCaching()); + } return scan; } diff --git a/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java b/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java index 6956b310b154..c197eb706c95 100644 --- a/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java +++ b/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java @@ -13658,6 +13658,16 @@ org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameBytesPairOrBuilder ge * <code>optional .Consistency consistency = 16 [default = STRONG];</code> */ org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency getConsistency(); + + // optional uint32 caching = 17; + /** + * <code>optional uint32 caching = 17;</code> + */ + boolean hasCaching(); + /** + * <code>optional uint32 caching = 17;</code> + */ + int getCaching(); } /** * Protobuf type {@code Scan} @@ -13829,6 +13839,11 @@ private Scan( } break; } + case 136: { + bitField0_ |= 0x00004000; + caching_ = input.readUInt32(); + break; + } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { @@ -14191,6 +14206,22 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency getCo return consistency_; } + // optional uint32 caching = 17; + public static final int CACHING_FIELD_NUMBER = 17; + private int caching_; + /** + * <code>optional uint32 caching = 17;</code> + */ + public boolean hasCaching() { + return ((bitField0_ & 0x00004000) == 0x00004000); + } + /** + * <code>optional uint32 caching = 17;</code> + */ + public int getCaching() { + return caching_; + } + private void initFields() { column_ = java.util.Collections.emptyList(); attribute_ = java.util.Collections.emptyList(); @@ -14208,6 +14239,7 @@ private void initFields() { small_ = false; reversed_ = false; consistency_ = org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency.STRONG; + caching_ = 0; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { @@ -14287,6 +14319,9 @@ public void writeTo(com.google.protobuf.CodedOutputStream output) if (((bitField0_ & 0x00002000) == 0x00002000)) { output.writeEnum(16, consistency_.getNumber()); } + if (((bitField0_ & 0x00004000) == 0x00004000)) { + output.writeUInt32(17, caching_); + } getUnknownFields().writeTo(output); } @@ -14360,6 +14395,10 @@ public int getSerializedSize() { size += com.google.protobuf.CodedOutputStream .computeEnumSize(16, consistency_.getNumber()); } + if (((bitField0_ & 0x00004000) == 0x00004000)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(17, caching_); + } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; @@ -14457,6 +14496,11 @@ public boolean equals(final java.lang.Object obj) { result = result && (getConsistency() == other.getConsistency()); } + result = result && (hasCaching() == other.hasCaching()); + if (hasCaching()) { + result = result && (getCaching() + == other.getCaching()); + } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; @@ -14534,6 +14578,10 @@ public int hashCode() { hash = (37 * hash) + CONSISTENCY_FIELD_NUMBER; hash = (53 * hash) + hashEnum(getConsistency()); } + if (hasCaching()) { + hash = (37 * hash) + CACHING_FIELD_NUMBER; + hash = (53 * hash) + getCaching(); + } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; @@ -14706,6 +14754,8 @@ public Builder clear() { bitField0_ = (bitField0_ & ~0x00004000); consistency_ = org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency.STRONG; bitField0_ = (bitField0_ & ~0x00008000); + caching_ = 0; + bitField0_ = (bitField0_ & ~0x00010000); return this; } @@ -14816,6 +14866,10 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Scan buildPartial to_bitField0_ |= 0x00002000; } result.consistency_ = consistency_; + if (((from_bitField0_ & 0x00010000) == 0x00010000)) { + to_bitField0_ |= 0x00004000; + } + result.caching_ = caching_; result.bitField0_ = to_bitField0_; onBuilt(); return result; @@ -14926,6 +14980,9 @@ public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.ClientProtos if (other.hasConsistency()) { setConsistency(other.getConsistency()); } + if (other.hasCaching()) { + setCaching(other.getCaching()); + } this.mergeUnknownFields(other.getUnknownFields()); return this; } @@ -16106,6 +16163,39 @@ public Builder clearConsistency() { return this; } + // optional uint32 caching = 17; + private int caching_ ; + /** + * <code>optional uint32 caching = 17;</code> + */ + public boolean hasCaching() { + return ((bitField0_ & 0x00010000) == 0x00010000); + } + /** + * <code>optional uint32 caching = 17;</code> + */ + public int getCaching() { + return caching_; + } + /** + * <code>optional uint32 caching = 17;</code> + */ + public Builder setCaching(int value) { + bitField0_ |= 0x00010000; + caching_ = value; + onChanged(); + return this; + } + /** + * <code>optional uint32 caching = 17;</code> + */ + public Builder clearCaching() { + bitField0_ = (bitField0_ & ~0x00010000); + caching_ = 0; + onChanged(); + return this; + } + // @@protoc_insertion_point(builder_scope:Scan) } @@ -30643,7 +30733,7 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiResponse mul "(\0132\016.MutationProto\022\035\n\tcondition\030\003 \001(\0132\n." + "Condition\022\023\n\013nonce_group\030\004 \001(\004\"<\n\016Mutate" + "Response\022\027\n\006result\030\001 \001(\0132\007.Result\022\021\n\tpro" + - "cessed\030\002 \001(\010\"\250\003\n\004Scan\022\027\n\006column\030\001 \003(\0132\007." + + "cessed\030\002 \001(\010\"\271\003\n\004Scan\022\027\n\006column\030\001 \003(\0132\007." + "Column\022!\n\tattribute\030\002 \003(\0132\016.NameBytesPai" + "r\022\021\n\tstart_row\030\003 \001(\014\022\020\n\010stop_row\030\004 \001(\014\022\027", "\n\006filter\030\005 \001(\0132\007.Filter\022\036\n\ntime_range\030\006 " + @@ -30653,55 +30743,55 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiResponse mul "re_limit\030\013 \001(\r\022\024\n\014store_offset\030\014 \001(\r\022&\n\036" + "load_column_families_on_demand\030\r \001(\010\022\r\n\005" + "small\030\016 \001(\010\022\027\n\010reversed\030\017 \001(\010:\005false\022)\n\013" + - "consistency\030\020 \001(\0162\014.Consistency:\006STRONG\"" + - "\236\001\n\013ScanRequest\022 \n\006region\030\001 \001(\0132\020.Region" + - "Specifier\022\023\n\004scan\030\002 \001(\0132\005.Scan\022\022\n\nscanne", - "r_id\030\003 \001(\004\022\026\n\016number_of_rows\030\004 \001(\r\022\025\n\rcl" + - "ose_scanner\030\005 \001(\010\022\025\n\rnext_call_seq\030\006 \001(\004" + - "\"\210\001\n\014ScanResponse\022\030\n\020cells_per_result\030\001 " + - "\003(\r\022\022\n\nscanner_id\030\002 \001(\004\022\024\n\014more_results\030" + - "\003 \001(\010\022\013\n\003ttl\030\004 \001(\r\022\030\n\007results\030\005 \003(\0132\007.Re" + - "sult\022\r\n\005stale\030\006 \001(\010\"\263\001\n\024BulkLoadHFileReq" + - "uest\022 \n\006region\030\001 \002(\0132\020.RegionSpecifier\0225" + - "\n\013family_path\030\002 \003(\0132 .BulkLoadHFileReque" + - "st.FamilyPath\022\026\n\016assign_seq_num\030\003 \001(\010\032*\n" + - "\nFamilyPath\022\016\n\006family\030\001 \002(\014\022\014\n\004path\030\002 \002(", - "\t\"\'\n\025BulkLoadHFileResponse\022\016\n\006loaded\030\001 \002" + - "(\010\"a\n\026CoprocessorServiceCall\022\013\n\003row\030\001 \002(" + - "\014\022\024\n\014service_name\030\002 \002(\t\022\023\n\013method_name\030\003" + - " \002(\t\022\017\n\007request\030\004 \002(\014\"9\n\030CoprocessorServ" + - "iceResult\022\035\n\005value\030\001 \001(\0132\016.NameBytesPair" + - "\"d\n\031CoprocessorServiceRequest\022 \n\006region\030" + - "\001 \002(\0132\020.RegionSpecifier\022%\n\004call\030\002 \002(\0132\027." + - "CoprocessorServiceCall\"]\n\032CoprocessorSer" + - "viceResponse\022 \n\006region\030\001 \002(\0132\020.RegionSpe" + - "cifier\022\035\n\005value\030\002 \002(\0132\016.NameBytesPair\"{\n", - "\006Action\022\r\n\005index\030\001 \001(\r\022 \n\010mutation\030\002 \001(\013" + - "2\016.MutationProto\022\021\n\003get\030\003 \001(\0132\004.Get\022-\n\014s" + - "ervice_call\030\004 \001(\0132\027.CoprocessorServiceCa" + - "ll\"Y\n\014RegionAction\022 \n\006region\030\001 \002(\0132\020.Reg" + - "ionSpecifier\022\016\n\006atomic\030\002 \001(\010\022\027\n\006action\030\003" + - " \003(\0132\007.Action\"\221\001\n\021ResultOrException\022\r\n\005i" + - "ndex\030\001 \001(\r\022\027\n\006result\030\002 \001(\0132\007.Result\022!\n\te" + - "xception\030\003 \001(\0132\016.NameBytesPair\0221\n\016servic" + - "e_result\030\004 \001(\0132\031.CoprocessorServiceResul" + - "t\"f\n\022RegionActionResult\022-\n\021resultOrExcep", - "tion\030\001 \003(\0132\022.ResultOrException\022!\n\texcept" + - "ion\030\002 \001(\0132\016.NameBytesPair\"G\n\014MultiReques" + - "t\022#\n\014regionAction\030\001 \003(\0132\r.RegionAction\022\022" + - "\n\nnonceGroup\030\002 \001(\004\"@\n\rMultiResponse\022/\n\022r" + - "egionActionResult\030\001 \003(\0132\023.RegionActionRe" + - "sult*\'\n\013Consistency\022\n\n\006STRONG\020\000\022\014\n\010TIMEL" + - "INE\020\0012\261\002\n\rClientService\022 \n\003Get\022\013.GetRequ" + - "est\032\014.GetResponse\022)\n\006Mutate\022\016.MutateRequ" + - "est\032\017.MutateResponse\022#\n\004Scan\022\014.ScanReque" + - "st\032\r.ScanResponse\022>\n\rBulkLoadHFile\022\025.Bul", - "kLoadHFileRequest\032\026.BulkLoadHFileRespons" + - "e\022F\n\013ExecService\022\032.CoprocessorServiceReq" + - "uest\032\033.CoprocessorServiceResponse\022&\n\005Mul" + - "ti\022\r.MultiRequest\032\016.MultiResponseBB\n*org" + - ".apache.hadoop.hbase.protobuf.generatedB" + - "\014ClientProtosH\001\210\001\001\240\001\001" + "consistency\030\020 \001(\0162\014.Consistency:\006STRONG\022" + + "\017\n\007caching\030\021 \001(\r\"\236\001\n\013ScanRequest\022 \n\006regi" + + "on\030\001 \001(\0132\020.RegionSpecifier\022\023\n\004scan\030\002 \001(\013", + "2\005.Scan\022\022\n\nscanner_id\030\003 \001(\004\022\026\n\016number_of" + + "_rows\030\004 \001(\r\022\025\n\rclose_scanner\030\005 \001(\010\022\025\n\rne" + + "xt_call_seq\030\006 \001(\004\"\210\001\n\014ScanResponse\022\030\n\020ce" + + "lls_per_result\030\001 \003(\r\022\022\n\nscanner_id\030\002 \001(\004" + + "\022\024\n\014more_results\030\003 \001(\010\022\013\n\003ttl\030\004 \001(\r\022\030\n\007r" + + "esults\030\005 \003(\0132\007.Result\022\r\n\005stale\030\006 \001(\010\"\263\001\n" + + "\024BulkLoadHFileRequest\022 \n\006region\030\001 \002(\0132\020." + + "RegionSpecifier\0225\n\013family_path\030\002 \003(\0132 .B" + + "ulkLoadHFileRequest.FamilyPath\022\026\n\016assign" + + "_seq_num\030\003 \001(\010\032*\n\nFamilyPath\022\016\n\006family\030\001", + " \002(\014\022\014\n\004path\030\002 \002(\t\"\'\n\025BulkLoadHFileRespo" + + "nse\022\016\n\006loaded\030\001 \002(\010\"a\n\026CoprocessorServic" + + "eCall\022\013\n\003row\030\001 \002(\014\022\024\n\014service_name\030\002 \002(\t" + + "\022\023\n\013method_name\030\003 \002(\t\022\017\n\007request\030\004 \002(\014\"9" + + "\n\030CoprocessorServiceResult\022\035\n\005value\030\001 \001(" + + "\0132\016.NameBytesPair\"d\n\031CoprocessorServiceR" + + "equest\022 \n\006region\030\001 \002(\0132\020.RegionSpecifier" + + "\022%\n\004call\030\002 \002(\0132\027.CoprocessorServiceCall\"" + + "]\n\032CoprocessorServiceResponse\022 \n\006region\030" + + "\001 \002(\0132\020.RegionSpecifier\022\035\n\005value\030\002 \002(\0132\016", + ".NameBytesPair\"{\n\006Action\022\r\n\005index\030\001 \001(\r\022" + + " \n\010mutation\030\002 \001(\0132\016.MutationProto\022\021\n\003get" + + "\030\003 \001(\0132\004.Get\022-\n\014service_call\030\004 \001(\0132\027.Cop" + + "rocessorServiceCall\"Y\n\014RegionAction\022 \n\006r" + + "egion\030\001 \002(\0132\020.RegionSpecifier\022\016\n\006atomic\030" + + "\002 \001(\010\022\027\n\006action\030\003 \003(\0132\007.Action\"\221\001\n\021Resul" + + "tOrException\022\r\n\005index\030\001 \001(\r\022\027\n\006result\030\002 " + + "\001(\0132\007.Result\022!\n\texception\030\003 \001(\0132\016.NameBy" + + "tesPair\0221\n\016service_result\030\004 \001(\0132\031.Coproc" + + "essorServiceResult\"f\n\022RegionActionResult", + "\022-\n\021resultOrException\030\001 \003(\0132\022.ResultOrEx" + + "ception\022!\n\texception\030\002 \001(\0132\016.NameBytesPa" + + "ir\"G\n\014MultiRequest\022#\n\014regionAction\030\001 \003(\013" + + "2\r.RegionAction\022\022\n\nnonceGroup\030\002 \001(\004\"@\n\rM" + + "ultiResponse\022/\n\022regionActionResult\030\001 \003(\013" + + "2\023.RegionActionResult*\'\n\013Consistency\022\n\n\006" + + "STRONG\020\000\022\014\n\010TIMELINE\020\0012\261\002\n\rClientService" + + "\022 \n\003Get\022\013.GetRequest\032\014.GetResponse\022)\n\006Mu" + + "tate\022\016.MutateRequest\032\017.MutateResponse\022#\n" + + "\004Scan\022\014.ScanRequest\032\r.ScanResponse\022>\n\rBu", + "lkLoadHFile\022\025.BulkLoadHFileRequest\032\026.Bul" + + "kLoadHFileResponse\022F\n\013ExecService\022\032.Copr" + + "ocessorServiceRequest\032\033.CoprocessorServi" + + "ceResponse\022&\n\005Multi\022\r.MultiRequest\032\016.Mul" + + "tiResponseBB\n*org.apache.hadoop.hbase.pr" + + "otobuf.generatedB\014ClientProtosH\001\210\001\001\240\001\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { @@ -30791,7 +30881,7 @@ public com.google.protobuf.ExtensionRegistry assignDescriptors( internal_static_Scan_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Scan_descriptor, - new java.lang.String[] { "Column", "Attribute", "StartRow", "StopRow", "Filter", "TimeRange", "MaxVersions", "CacheBlocks", "BatchSize", "MaxResultSize", "StoreLimit", "StoreOffset", "LoadColumnFamiliesOnDemand", "Small", "Reversed", "Consistency", }); + new java.lang.String[] { "Column", "Attribute", "StartRow", "StopRow", "Filter", "TimeRange", "MaxVersions", "CacheBlocks", "BatchSize", "MaxResultSize", "StoreLimit", "StoreOffset", "LoadColumnFamiliesOnDemand", "Small", "Reversed", "Consistency", "Caching", }); internal_static_ScanRequest_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_ScanRequest_fieldAccessorTable = new diff --git a/hbase-protocol/src/main/protobuf/Client.proto b/hbase-protocol/src/main/protobuf/Client.proto index 8c71ef1018dc..9eedd1b0c903 100644 --- a/hbase-protocol/src/main/protobuf/Client.proto +++ b/hbase-protocol/src/main/protobuf/Client.proto @@ -247,6 +247,7 @@ message Scan { optional bool small = 14; optional bool reversed = 15 [default = false]; optional Consistency consistency = 16 [default = STRONG]; + optional uint32 caching = 17; } /** diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java index f4b71f788fd1..d51f007f8ed0 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java @@ -291,15 +291,21 @@ public void testScan() throws IOException { scanBuilder.addColumn(columnBuilder.build()); ClientProtos.Scan proto = scanBuilder.build(); - // default fields + + // Verify default values assertEquals(1, proto.getMaxVersions()); assertEquals(true, proto.getCacheBlocks()); + // Verify fields survive ClientProtos.Scan -> Scan -> ClientProtos.Scan + // conversion scanBuilder = ClientProtos.Scan.newBuilder(proto); - scanBuilder.setMaxVersions(1); - scanBuilder.setCacheBlocks(true); - - Scan scan = ProtobufUtil.toScan(proto); - assertEquals(scanBuilder.build(), ProtobufUtil.toScan(scan)); + scanBuilder.setMaxVersions(2); + scanBuilder.setCacheBlocks(false); + scanBuilder.setCaching(1024); + ClientProtos.Scan expectedProto = scanBuilder.build(); + + ClientProtos.Scan actualProto = ProtobufUtil.toScan( + ProtobufUtil.toScan(expectedProto)); + assertEquals(expectedProto, actualProto); } }
0c9cd2f936f77ccf22dcf98df1c9679cdafa791f
drools
JBRULES-2353: Update HumanTask to the new grid inf- and CommandExecutor
a
https://github.com/kiegroup/drools
diff --git a/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java b/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java index 2877f0f0349..92182ae97a8 100644 --- a/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java +++ b/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java @@ -85,11 +85,12 @@ public boolean connect() { } } // Connecting with services - if (this.services!=null) { + if (this.services != null) { for (GenericConnector connector : services){ boolean serviceConnected = connector.connect(); - if ( serviceConnected ) + if ( serviceConnected ){ System.out.println("Service Connected"); + } } } @@ -98,9 +99,11 @@ public boolean connect() { public void disconnect() { this.client.disconnect(); - if (this.services!=null) - for (GenericConnector connector : this.services) + if (this.services != null){ + for (GenericConnector connector : this.services){ connector.disconnect(); + } + } } public KnowledgeBuilderProvider getKnowledgeBuilderFactory() { diff --git a/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java b/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java index dca0e7fa17f..9219f952c0c 100644 --- a/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java +++ b/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java @@ -41,6 +41,7 @@ import org.drools.task.service.Command; import org.drools.task.service.ContentData; import org.drools.task.service.HumanTaskServiceImpl; +import org.drools.task.service.responsehandlers.AbstractBaseResponseHandler; import org.drools.vsm.GenericConnector; import org.drools.vsm.Message; import org.drools.vsm.mina.MinaConnector; @@ -208,7 +209,7 @@ public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { } } - public class TaskWorkItemAddTaskMessageResponseHandler implements AddTaskMessageResponseHandler { + public class TaskWorkItemAddTaskMessageResponseHandler extends AbstractBaseResponseHandler implements AddTaskMessageResponseHandler { private Map<Long, WorkItemManager> managers; private Map<Long, Long> idMapping; @@ -249,13 +250,11 @@ public void receive(Message message) { client.registerForEvent( key, true, eventResponseHandler ); } - public void setError(RuntimeException error) { - throw new UnsupportedOperationException("Not supported yet."); - } + } - private class TaskCompletedMessageHandler implements EventMessageResponseHandler { + private class TaskCompletedMessageHandler extends AbstractBaseResponseHandler implements EventMessageResponseHandler { private long workItemId; private long taskId; private final Map<Long, WorkItemManager> managers; @@ -266,13 +265,9 @@ public TaskCompletedMessageHandler(long workItemId, long taskId, Map<Long, WorkI this.managers = managers; } - public void execute(Payload payload) { - throw new UnsupportedOperationException("Not supported yet."); - } + - public void setError(RuntimeException error) { - throw new UnsupportedOperationException("Not supported yet."); - } + public void receive(Message message) { Command cmd = (Command) message.getPayload(); @@ -299,9 +294,13 @@ public void receive(Message message) { } } } + + public void execute(Payload payload) { + throw new UnsupportedOperationException("Not supported yet."); + } } - private class GetCompletedTaskMessageResponseHandler implements GetTaskMessageResponseHandler { + private class GetCompletedTaskMessageResponseHandler extends AbstractBaseResponseHandler implements GetTaskMessageResponseHandler { private WorkItemManager manager; @@ -309,9 +308,7 @@ public GetCompletedTaskMessageResponseHandler(WorkItemManager manager) { this.manager = manager; } - public void setError(RuntimeException error) { - throw new UnsupportedOperationException("Not supported yet."); - } + public void receive(Message message) { Command cmd = (Command) message.getPayload(); @@ -333,9 +330,11 @@ public void receive(Message message) { public void execute(Task task) { throw new UnsupportedOperationException("Not supported yet."); } + + } - private class GetResultContentMessageResponseHandler implements GetContentMessageResponseHandler { + private class GetResultContentMessageResponseHandler extends AbstractBaseResponseHandler implements GetContentMessageResponseHandler { private Task task; private final WorkItemManager manager; @@ -347,9 +346,7 @@ public GetResultContentMessageResponseHandler(WorkItemManager manager, Task task this.results = results; } - public void setError(RuntimeException error) { - throw new UnsupportedOperationException("Not supported yet."); - } + public void receive(Message message) { Command cmd = (Command)message.getPayload(); diff --git a/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java b/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java index 8ad421caff1..fcbd508b84f 100644 --- a/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java +++ b/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java @@ -132,6 +132,7 @@ public void testTask() throws Exception { BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); @@ -169,6 +170,7 @@ public void testTaskMultipleActors() throws Exception { BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); @@ -214,6 +216,7 @@ public void testTaskGroupActors() throws Exception { List<String> groupIds = new ArrayList<String>(); groupIds.add("Crusaders"); humanTaskClient.getTasksAssignedAsPotentialOwner(null, groupIds, "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary taskSummary = tasks.get(0); @@ -271,6 +274,7 @@ public void testTaskSingleAndGroupActors() throws Exception { List<String> groupIds = new ArrayList<String>(); groupIds.add("Crusaders"); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", groupIds, "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(2, tasks.size()); } @@ -289,6 +293,7 @@ public void testTaskFail() throws Exception { BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); @@ -327,6 +332,7 @@ public void testTaskSkip() throws Exception { BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); @@ -363,6 +369,7 @@ public void testTaskAbortSkippable() throws Exception { BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(0, tasks.size()); } @@ -382,6 +389,7 @@ public void testTaskAbortNotSkippable() throws Exception { BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); @@ -410,6 +418,7 @@ public void testTaskData() throws Exception { BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary taskSummary = tasks.get(0); @@ -480,6 +489,7 @@ public void testOnAllSubTasksEndParentEndStrategy() throws Exception { //Test if the task is succesfully created BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); @@ -625,6 +635,7 @@ public void testOnParentAbortAllSubTasksEndStrategy() throws Exception { //Test if the task is succesfully created BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); List<TaskSummary> tasks = responseHandler.getResults(); assertEquals(1, tasks.size()); TaskSummary task = tasks.get(0); diff --git a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java index 25c4ec4e956..ed5eaa2106b 100644 --- a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java +++ b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java @@ -12,26 +12,42 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; +import junit.framework.TestCase; import org.apache.commons.collections.map.HashedMap; import org.apache.mina.transport.socket.SocketAcceptor; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.apache.mina.transport.socket.nio.NioSocketConnector; +import org.drools.KnowledgeBase; +import org.drools.KnowledgeBaseProvider; import org.drools.SystemEventListenerFactory; +import org.drools.builder.KnowledgeBuilder; +import org.drools.builder.KnowledgeBuilderProvider; +import org.drools.builder.ResourceType; +import org.drools.io.impl.ClassPathResource; +import org.drools.runtime.StatefulKnowledgeSession; +import org.drools.runtime.process.ProcessInstance; import org.drools.task.Group; import org.drools.task.User; +import org.drools.task.query.TaskSummary; +import org.drools.task.service.ContentData; +import org.drools.task.service.HumanTaskServiceImpl; import org.drools.task.service.TaskService; import org.drools.task.service.TaskServiceSession; import org.drools.vsm.mina.MinaAcceptor; import org.drools.vsm.mina.MinaConnector; import org.drools.vsm.mina.MinaIoHandler; import org.drools.vsm.remote.ServiceManagerRemoteClient; +import org.drools.vsm.remote.StatefulKnowledgeSessionRemoteClient; import org.drools.vsm.task.TaskServerMessageHandlerImpl; +import org.drools.vsm.task.responseHandlers.BlockingTaskOperationMessageResponseHandler; +import org.drools.vsm.task.responseHandlers.BlockingTaskSummaryMessageResponseHandler; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.ExpressionCompiler; -public class ServiceManagerHumanTaskMinaRemoteTest extends ServiceManagerTestBase { +public class ServiceManagerHumanTaskMinaRemoteTest extends TestCase { + //extends ServiceManagerTestBase { AcceptorService server; AcceptorService humanTaskServer; @@ -40,7 +56,10 @@ public class ServiceManagerHumanTaskMinaRemoteTest extends ServiceManagerTestBas protected TaskServiceSession taskSession; protected Map<String, User> users; protected Map<String, Group> groups; - + private HumanTaskService htClient; + private static final int DEFAULT_WAIT_TIME = 5000; + protected ServiceManager client; + protected void setUp() throws Exception { // Configure persistence to be used inside the WSHT Service // Use persistence.xml configuration @@ -134,6 +153,7 @@ protected void tearDown() throws Exception { ((ServiceManagerRemoteClient) client).disconnect(); this.server.stop(); this.humanTaskServer.stop(); + } public Object eval(Reader reader, Map<String, Object> vars) { @@ -164,4 +184,69 @@ public String toString(Reader reader) throws IOException { sb.append((char) charValue); return sb.toString(); } + public void testHumanTasks() throws Exception { + + KnowledgeBuilderProvider kbuilderFactory = this.client.getKnowledgeBuilderFactory(); + KnowledgeBuilder kbuilder = kbuilderFactory.newKnowledgeBuilder(); + kbuilder.add( new ClassPathResource("rules/humanTasks.rf"), + ResourceType.DRF ); + + if ( kbuilder.hasErrors() ) { + System.out.println( "Errors: " + kbuilder.getErrors() ); + } + + KnowledgeBaseProvider kbaseFactory = this.client.getKnowledgeBaseFactory(); + KnowledgeBase kbase = kbaseFactory.newKnowledgeBase(); + + kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); + + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + + ((StatefulKnowledgeSessionRemoteClient)ksession).registerWorkItemHandler("Human Task", "org.drools.vsm.task.CommandBasedVSMWSHumanTaskHandler"); + ProcessInstance processInstance = ksession.startProcess("org.drools.test.humanTasks"); + HumanTaskServiceProvider humanTaskServiceFactory = this.client.getHumanTaskService(); + htClient = humanTaskServiceFactory.newHumanTaskServiceClient(); + + Thread.sleep(1000); + + ksession.fireAllRules(); + + System.out.println("First Task Execution"); + assertEquals(true , executeNextTask("lucaz")); + Thread.sleep(8000); + System.out.println("Second Task Execution"); + assertEquals(true , executeNextTask("lucaz")); + System.out.println("Inexistent Task Execution"); + Thread.sleep(8000); + assertEquals(false, executeNextTask("lucaz")); + + } + + private boolean executeNextTask(String user) { + + BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); + ((HumanTaskServiceImpl)htClient).getTasksAssignedAsPotentialOwner(user, "en-UK", responseHandler); + responseHandler.waitTillDone(DEFAULT_WAIT_TIME); + + if (responseHandler.getResults().size()==0) + return false; + + TaskSummary task = responseHandler.getResults().get(0); + ContentData data = new ContentData(); + data.setContent("next step".getBytes()); + + BlockingTaskOperationMessageResponseHandler startResponseHandler = new BlockingTaskOperationMessageResponseHandler(); + ((HumanTaskServiceImpl)htClient).start(task.getId(), user, startResponseHandler ); + startResponseHandler.waitTillDone(DEFAULT_WAIT_TIME); + + System.out.println("Started Task " + task.getId()); + + BlockingTaskOperationMessageResponseHandler completeResponseHandler = new BlockingTaskOperationMessageResponseHandler(); + ((HumanTaskServiceImpl)htClient).complete(task.getId(), user, null , completeResponseHandler); + completeResponseHandler.waitTillDone(DEFAULT_WAIT_TIME); + System.out.println("Completed Task " + task.getId()); + + return true; + } + } diff --git a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java index 3cde4428027..adc8e8ed7d1 100644 --- a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java +++ b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java @@ -9,24 +9,16 @@ import org.drools.builder.ResourceType; import org.drools.command.runtime.rule.FireAllRulesCommand; import org.drools.io.ResourceFactory; -import org.drools.io.impl.ClassPathResource; import org.drools.runtime.ExecutionResults; import org.drools.runtime.StatefulKnowledgeSession; -import org.drools.runtime.process.ProcessInstance; -import org.drools.task.query.TaskSummary; -import org.drools.task.service.ContentData; -import org.drools.task.service.HumanTaskServiceImpl; -import org.drools.vsm.remote.StatefulKnowledgeSessionRemoteClient; -import org.drools.vsm.task.responseHandlers.BlockingTaskOperationMessageResponseHandler; -import org.drools.vsm.task.responseHandlers.BlockingTaskSummaryMessageResponseHandler; public class ServiceManagerTestBase extends TestCase { - private static final int DEFAULT_WAIT_TIME = 5000; + protected ServiceManager client; - private HumanTaskService htClient; + public void testFireAllRules() throws Exception { String str = ""; @@ -187,69 +179,5 @@ public void testVsmPipeline() throws Exception { // assertEquals( 2, (int ) ( Integer) results.getValue( "fired" ) ); } - public void testHumanTasks() throws Exception { - - KnowledgeBuilderProvider kbuilderFactory = this.client.getKnowledgeBuilderFactory(); - KnowledgeBuilder kbuilder = kbuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ClassPathResource("rules/humanTasks.rf"), - ResourceType.DRF ); - - if ( kbuilder.hasErrors() ) { - System.out.println( "Errors: " + kbuilder.getErrors() ); - } - - KnowledgeBaseProvider kbaseFactory = this.client.getKnowledgeBaseFactory(); - KnowledgeBase kbase = kbaseFactory.newKnowledgeBase(); - - kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); - - StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); - - ((StatefulKnowledgeSessionRemoteClient)ksession).registerWorkItemHandler("Human Task", "org.drools.vsm.task.CommandBasedVSMWSHumanTaskHandler"); - ProcessInstance processInstance = ksession.startProcess("org.drools.test.humanTasks"); - HumanTaskServiceProvider humanTaskServiceFactory = this.client.getHumanTaskService(); - htClient = humanTaskServiceFactory.newHumanTaskServiceClient(); - - Thread.sleep(1000); - - ksession.fireAllRules(); - - System.out.println("First Task Execution"); - assertEquals(true , executeNextTask("lucaz")); - Thread.sleep(8000); - System.out.println("Second Task Execution"); - assertEquals(true , executeNextTask("lucaz")); - System.out.println("Inexistent Task Execution"); - Thread.sleep(8000); - assertEquals(false, executeNextTask("lucaz")); - - } - - private boolean executeNextTask(String user) { - - BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler(); - ((HumanTaskServiceImpl)htClient).getTasksAssignedAsPotentialOwner(user, "en-UK", responseHandler); - responseHandler.waitTillDone(DEFAULT_WAIT_TIME); - - if (responseHandler.getResults().size()==0) - return false; - - TaskSummary task = responseHandler.getResults().get(0); - ContentData data = new ContentData(); - data.setContent("next step".getBytes()); - - BlockingTaskOperationMessageResponseHandler startResponseHandler = new BlockingTaskOperationMessageResponseHandler(); - ((HumanTaskServiceImpl)htClient).start(task.getId(), user, startResponseHandler ); - startResponseHandler.waitTillDone(DEFAULT_WAIT_TIME); - - System.out.println("Started Task " + task.getId()); - - BlockingTaskOperationMessageResponseHandler completeResponseHandler = new BlockingTaskOperationMessageResponseHandler(); - ((HumanTaskServiceImpl)htClient).complete(task.getId(), user, null , completeResponseHandler); - completeResponseHandler.waitTillDone(DEFAULT_WAIT_TIME); - System.out.println("Completed Task " + task.getId()); - - return true; - } - + }
cf75df69f253669574263f69b1ec7b1554ea5701
hadoop
YARN-1497. Fix comment and remove accidental- println--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1567491 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java index 80e548d26e632..4332f5beeafdc 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java @@ -382,11 +382,7 @@ private void killApplication(String applicationId) throws YarnException, } /** - * Kills the application with the application id as appId - * - * @param applicationId - * @throws YarnException - * @throws IOException + * Moves the application with the given ID to the given queue. */ private void moveApplicationAcrossQueues(String applicationId, String queue) throws YarnException, IOException { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java index 12bc6be731640..97721864968db 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java @@ -675,7 +675,6 @@ public void testAppsHelpCommand() throws Exception { int result = spyCli.run(new String[] { "-help" }); Assert.assertTrue(result == 0); verify(spyCli).printUsage(any(Options.class)); - System.err.println(sysOutStream.toString()); //todo sandyt remove this hejfkdsl Assert.assertEquals(createApplicationCLIHelpMessage(), sysOutStream.toString());
9ee96d6949dd01841bf3a1af91850483a37bbf4c
adangel$pmd
Improved Designer look and functionality thanks to Brian Remedios. git-svn-id: https://pmd.svn.sourceforge.net/svnroot/pmd/trunk@4451 51baf565-9d33-0410-a72c-fc3788e3496d
p
https://github.com/adangel/pmd
diff --git a/pmd/etc/changelog.txt b/pmd/etc/changelog.txt index 8b3b175dce0..f3724ee1b4c 100644 --- a/pmd/etc/changelog.txt +++ b/pmd/etc/changelog.txt @@ -1,4 +1,4 @@ - ????, 2006 - 3.8: + ????, 2006 - 3.8: BEFORE RELEASE: - remove deprecated methods from PMD.java, RuleSetFactory @@ -13,6 +13,7 @@ Fixed a bug in the C++ grammar - the tokenizer now properly recognizes macro def Applied patch 1481024 (fulfilling RFE 1490181)- NOPMD messages can now be reported with a user specified msg, e.g., //NOPMD - this is expected Added JSP support to the copy/paste detector. Refactored UseIndexOfChar to extract common functionality into AbstractPoorMethodCall. +Improved Designer look and functionality thanks to Brian Remedios. June 1, 2006 - 3.7: New rules: diff --git a/pmd/src/net/sourceforge/pmd/util/StringUtil.java b/pmd/src/net/sourceforge/pmd/util/StringUtil.java index 4a0f8995ef8..a7a9fce07bc 100644 --- a/pmd/src/net/sourceforge/pmd/util/StringUtil.java +++ b/pmd/src/net/sourceforge/pmd/util/StringUtil.java @@ -88,32 +88,39 @@ else if (c == '>') } } -/* public static void appendXmlEscaped2(StringBuffer buf, String src) { - int l = src.length(); - char c; - for (int i = 0; i < l; i++) { - c = src.charAt(i); - if (c <= 32) { - buf.append(c); - } else if (c > '~') {// 126 - if (c <= 255) - buf.append(ENTITIES[c - 126]); - else + /** + * Parses the input source using the delimiter specified. This method is much + * faster than using the StringTokenizer or String.split(char) approach and + * serves as a replacement for String.split() for JDK1.3 that doesn't have it. + * + * @param source String + * @param delimiter char + * @return String[] + */ + public static String[] substringsOf(String source, char delimiter) { - buf.append("&u").append(Integer.toHexString(c)).append(';'); - } else if (c == 38) - buf.append("&amp;"); - else if (c == 34) - buf.append("&quot;"); - else if (c == 39) - buf.append("&apos;"); - else if (c == 60) - buf.append("&lt;"); - else if (c == 62) - buf.append("&gt;"); - else - buf.append(c); - } - } -*/ + int delimiterCount = 0; + int length = source.length(); + char[] chars = source.toCharArray(); + + for (int i=0; i<length; i++) { + if (chars[i] == delimiter) delimiterCount++; + } + + if (delimiterCount == 0) return new String[] { source }; + + String results[] = new String[delimiterCount+1]; + + int i = 0; + int offset = 0; + + while (offset <= length) { + int pos = source.indexOf(delimiter, offset); + if (pos < 0) pos = length; + results[i++] = pos == offset ? "" : source.substring(offset, pos); + offset = pos + 1; + } + + return results; + } } diff --git a/pmd/src/net/sourceforge/pmd/util/SymbolTableViewer.java b/pmd/src/net/sourceforge/pmd/util/SymbolTableViewer.java index 9d39722b63e..cc39af7cdf9 100644 --- a/pmd/src/net/sourceforge/pmd/util/SymbolTableViewer.java +++ b/pmd/src/net/sourceforge/pmd/util/SymbolTableViewer.java @@ -25,11 +25,9 @@ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { } private String spaces() { - String s = ""; - for (int i = 0; i < depth; i++) { - s += " "; - } - return s; + StringBuffer sb = new StringBuffer(depth); + for (int i=0; i<depth; i++) sb.append(' '); + return sb.toString(); } /* diff --git a/pmd/src/net/sourceforge/pmd/util/designer/CodeEditorTextPane.java b/pmd/src/net/sourceforge/pmd/util/designer/CodeEditorTextPane.java index 257725ca8f5..1156acc6ff8 100644 --- a/pmd/src/net/sourceforge/pmd/util/designer/CodeEditorTextPane.java +++ b/pmd/src/net/sourceforge/pmd/util/designer/CodeEditorTextPane.java @@ -16,6 +16,7 @@ public class CodeEditorTextPane extends JTextPane implements HasLines, ActionListener { private static final String SETTINGS_FILE_NAME = System.getProperty("user.home") + System.getProperty("file.separator") + ".pmd_designer"; + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); public CodeEditorTextPane() { setPreferredSize(new Dimension(400, 200)); @@ -57,8 +58,7 @@ private String loadCode() { StringBuffer text = new StringBuffer(); String hold; while ((hold = br.readLine()) != null) { - text.append(hold); - text.append(System.getProperty("line.separator")); + text.append(hold).append(LINE_SEPARATOR); } return text.toString(); } catch (IOException e) { @@ -66,12 +66,10 @@ private String loadCode() { return ""; } finally { try { - if (br != null) - br.close(); + if (br != null) br.close(); } catch (IOException e) { e.printStackTrace(); } } } } - diff --git a/pmd/src/net/sourceforge/pmd/util/designer/DFAPanel.java b/pmd/src/net/sourceforge/pmd/util/designer/DFAPanel.java index 68695bd4c47..9b0c252f46a 100644 --- a/pmd/src/net/sourceforge/pmd/util/designer/DFAPanel.java +++ b/pmd/src/net/sourceforge/pmd/util/designer/DFAPanel.java @@ -1,27 +1,38 @@ package net.sourceforge.pmd.util.designer; -import net.sourceforge.pmd.ast.ASTMethodDeclaration; -import net.sourceforge.pmd.ast.SimpleNode; -import net.sourceforge.pmd.dfa.IDataFlowNode; -import net.sourceforge.pmd.dfa.variableaccess.VariableAccess; -import net.sourceforge.pmd.util.HasLines; - -import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; -import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; +import java.awt.FontMetrics; import java.awt.Graphics; import java.util.Iterator; import java.util.List; +import javax.swing.BorderFactory; +import javax.swing.DefaultListModel; +import javax.swing.JComponent; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import net.sourceforge.pmd.ast.ASTMethodDeclaration; +import net.sourceforge.pmd.ast.SimpleNode; +import net.sourceforge.pmd.dfa.IDataFlowNode; +import net.sourceforge.pmd.dfa.variableaccess.VariableAccess; +import net.sourceforge.pmd.util.HasLines; + public class DFAPanel extends JComponent implements ListSelectionListener { - public static class DFACanvas extends Canvas { + public static final String[] emptyStringSet = new String[0]; - private static final int NODE_RADIUS = 10; + public static class DFACanvas extends JPanel { + + private static final int NODE_RADIUS = 12; private static final int NODE_DIAMETER = 2 * NODE_RADIUS; private SimpleNode node; @@ -30,51 +41,113 @@ public static class DFACanvas extends Canvas { private int y = 50; private HasLines lines; - public void paint(Graphics g) { - super.paint(g); - if (node == null) { - return; + private void addAccessLabel(StringBuffer sb, VariableAccess va) { + + if (va.isDefinition()) { + sb.append("d("); + } else if (va.isReference()) { + sb.append("r("); + } else if (va.isUndefinition()) { + sb.append("u("); + //continue; // eo - the u() entries add a lot of clutter to the report + } else { + sb.append("?("); + } + + sb.append(va.getVariableName()).append(')'); + } + + private String childIndicesOf(IDataFlowNode node, String separator) { + + List kids = node.getChildren(); + if (kids.isEmpty()) return ""; + + StringBuffer sb = new StringBuffer(); + sb.append(((IDataFlowNode)kids.get(0)).getIndex()); + + for (int j = 1; j < node.getChildren().size(); j++) { + sb.append(separator); + sb.append(((IDataFlowNode)kids.get(j)).getIndex()); + } + return sb.toString(); + } + + private String[] deriveAccessLabels(List flow) { + + if (flow == null && flow.isEmpty()) return emptyStringSet; + + String[] labels = new String[flow.size()]; + + for (int i=0; i<labels.length; i++) { + List access = ((IDataFlowNode) flow.get(i)).getVariableAccess(); + + if (access == null || access.isEmpty()) { + continue; // leave a null at this slot + } + + StringBuffer exp = new StringBuffer(); + addAccessLabel(exp, (VariableAccess) access.get(0)); + + for (int k = 1; k < access.size(); k++) { + exp.append(", "); + addAccessLabel(exp, (VariableAccess) access.get(k)); + } + + labels[i] = exp.toString(); } + return labels; + } + + private int maxWidthOf(String[] strings, FontMetrics fm) { + + int max = 0; + String str; + + for (int i=0; i<strings.length; i++) { + str = strings[i]; + if (str == null) continue; + max = Math.max(max, SwingUtilities.computeStringWidth(fm, str)); + } + return max; + } + + + public void paintComponent(Graphics g) { + super.paintComponent(g); + + if (node == null) return; + List flow = node.getDataFlowNode().getFlow(); + FontMetrics fm = g.getFontMetrics(); + int halfFontHeight = fm.getAscent() / 2; + + String[] accessLabels = deriveAccessLabels(flow); + int maxAccessLabelWidth = maxWidthOf(accessLabels, fm); + for (int i = 0; i < flow.size(); i++) { IDataFlowNode inode = (IDataFlowNode) flow.get(i); y = computeDrawPos(inode.getIndex()); g.drawArc(x, y, NODE_DIAMETER, NODE_DIAMETER, 0, 360); - g.drawString(lines.getLine(inode.getLine()), x + 200, y + 15); - + g.drawString(lines.getLine(inode.getLine()), x + 100 + maxAccessLabelWidth, y + 15); + // draw index number centered inside of node String idx = String.valueOf(inode.getIndex()); - int hack = 4 * (idx.length() / 2); // eo - hack to get one and two digit numbers centered - g.drawString(idx, x + NODE_RADIUS - 2 - hack, y + NODE_RADIUS + 4); - - List access = inode.getVariableAccess(); - if (access != null) { - StringBuffer exp = new StringBuffer(); - for (int k = 0; k < access.size(); k++) { - VariableAccess va = (VariableAccess) access.get(k); - if (va.isDefinition()) { - exp.append("d("); - } else if (va.isReference()) { - exp.append("r("); - } else if (va.isUndefinition()) { - exp.append("u("); - //continue; // eo - the u() entries add a lot of clutter to the report - } else { - exp.append("?("); - } - exp.append(va.getVariableName() + "), "); - } - g.drawString(exp.toString(), x + 70, y + 15); + int halfWidth = SwingUtilities.computeStringWidth(fm, idx) / 2; + g.drawString(idx, x + NODE_RADIUS - halfWidth, y + NODE_RADIUS + halfFontHeight); + + String accessLabel = accessLabels[i]; + if (accessLabel != null) { + g.drawString(accessLabel, x + 70, y + 15); } for (int j = 0; j < inode.getChildren().size(); j++) { IDataFlowNode n = (IDataFlowNode) inode.getChildren().get(j); - this.drawMyLine(inode.getIndex(), n.getIndex(), g); - String output = (j == 0 ? "" : ",") + String.valueOf(n.getIndex()); - g.drawString(output, x - 3 * NODE_DIAMETER + (j * 20), y + NODE_RADIUS - 2); + drawMyLine(inode.getIndex(), n.getIndex(), g); } + String childIndices = childIndicesOf(inode, ", "); + g.drawString(childIndices, x - 3 * NODE_DIAMETER, y + NODE_RADIUS - 2); } } @@ -91,17 +164,42 @@ private int computeDrawPos(int index) { return z + index * z; } + private void drawArrow(Graphics g, int x, int y, int direction) { + + final int height = NODE_RADIUS * 2/3; + final int width = NODE_RADIUS * 2/3; + + switch (direction) { + case SwingConstants.NORTH : + g.drawLine(x, y, x - width/2, y + height); + g.drawLine(x, y, x + width/2, y + height); + break; + case SwingConstants.SOUTH : + g.drawLine(x, y, x - width/2, y - height); + g.drawLine(x, y, x + width/2, y - height); + break; + case SwingConstants.EAST : + g.drawLine(x, y, x - height, y - width/2); + g.drawLine(x, y, x - height, y + width/2); + break; + case SwingConstants.WEST : + g.drawLine(x, y, x + height, y - width/2); + g.drawLine(x, y, x + height, y + width/2); + } + } + private void drawMyLine(int index1, int index2, Graphics g) { int y1 = this.computeDrawPos(index1); int y2 = this.computeDrawPos(index2); - int arrow = 3; + int arrow = 6; if (index1 < index2) { if (index2 - index1 == 1) { x += NODE_RADIUS; g.drawLine(x, y1 + NODE_DIAMETER, x, y2); - g.fillRect(x - arrow, y2 - arrow, arrow * 2, arrow * 2); + // g.fillRect(x - arrow, y2 - arrow, arrow * 2, arrow * 2); + drawArrow(g, x, y2, SwingConstants.SOUTH); x -= NODE_RADIUS; } else if (index2 - index1 > 1) { y1 = y1 + NODE_RADIUS; @@ -110,7 +208,8 @@ private void drawMyLine(int index1, int index2, Graphics g) { g.drawLine(x, y1, x - n, y1); g.drawLine(x - n, y1, x - n, y2); g.drawLine(x - n, y2, x, y2); - g.fillRect(x - arrow, y2 - arrow, arrow * 2, arrow * 2); + // g.fillRect(x - arrow, y2 - arrow, arrow * 2, arrow * 2); + drawArrow(g, x,y2, SwingConstants.EAST); } } else { @@ -122,12 +221,14 @@ private void drawMyLine(int index1, int index2, Graphics g) { g.drawLine(x, y1, x + n, y1); g.drawLine(x + n, y1, x + n, y2); g.drawLine(x + n, y2, x, y2); - g.fillRect(x - arrow, y2 - arrow, arrow * 2, arrow * 2); + // g.fillRect(x - arrow, y2 - arrow, arrow * 2, arrow * 2); + drawArrow(g, x, y2, SwingConstants.WEST); x = x - NODE_DIAMETER; } else if (index1 - index2 == 1) { y2 = y2 + NODE_DIAMETER; g.drawLine(x + NODE_RADIUS, y2, x + NODE_RADIUS, y1); - g.fillRect(x + NODE_RADIUS - arrow, y2 - arrow, arrow * 2, arrow * 2); + // g.fillRect(x + NODE_RADIUS - arrow, y2 - arrow, arrow * 2, arrow * 2); + drawArrow(g, x + NODE_RADIUS, y2, SwingConstants.NORTH); } } } @@ -149,33 +250,32 @@ public String toString() { } } - private DFACanvas dfaCanvas; - private JList nodeList; - private DefaultListModel nodes = new DefaultListModel(); - private JPanel wrapperPanel; + private DFACanvas dfaCanvas; + private JList nodeList; + private DefaultListModel nodes = new DefaultListModel(); public DFAPanel() { super(); setLayout(new BorderLayout()); JPanel leftPanel = new JPanel(); + nodeList = new JList(nodes); nodeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); nodeList.setFixedCellWidth(150); nodeList.setBorder(BorderFactory.createLineBorder(Color.black)); nodeList.addListSelectionListener(this); + leftPanel.add(nodeList); add(leftPanel, BorderLayout.WEST); dfaCanvas = new DFACanvas(); - JScrollPane scrollPane = new JScrollPane(); - scrollPane.setPreferredSize(new Dimension(800, 450)); // eo - it would be better to calculate the size based on the containing object's size - dfaCanvas.setSize(2000, 4000); // eo - these seem to give a big enough canvas - scrollPane.add(dfaCanvas); - wrapperPanel = new JPanel(); - wrapperPanel.add(scrollPane); - wrapperPanel.setBorder(BorderFactory.createLineBorder(Color.black)); - add(wrapperPanel, BorderLayout.EAST); + dfaCanvas.setBackground(Color.WHITE); + dfaCanvas.setPreferredSize(new Dimension(900, 1400)); + + JScrollPane scrollPane = new JScrollPane(dfaCanvas); + + add(scrollPane, BorderLayout.CENTER); } public void valueChanged(ListSelectionEvent event) { @@ -204,4 +304,3 @@ public void resetTo(List newNodes, HasLines lines) { repaint(); } } - diff --git a/pmd/src/net/sourceforge/pmd/util/designer/Designer.java b/pmd/src/net/sourceforge/pmd/util/designer/Designer.java index 7a7f4d5e99c..d2c2c70162d 100644 --- a/pmd/src/net/sourceforge/pmd/util/designer/Designer.java +++ b/pmd/src/net/sourceforge/pmd/util/designer/Designer.java @@ -3,33 +3,14 @@ */ package net.sourceforge.pmd.util.designer; -import net.sourceforge.pmd.PMD; -import net.sourceforge.pmd.RuleContext; -import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.SourceType; -import net.sourceforge.pmd.TargetJDK1_3; -import net.sourceforge.pmd.TargetJDK1_4; -import net.sourceforge.pmd.TargetJDK1_5; -import net.sourceforge.pmd.TargetJDKVersion; -import net.sourceforge.pmd.ast.JavaParser; -import net.sourceforge.pmd.ast.ParseException; -import net.sourceforge.pmd.ast.SimpleNode; -import net.sourceforge.pmd.jaxen.DocumentNavigator; -import net.sourceforge.pmd.jaxen.MatchesFunction; -import net.sourceforge.pmd.jsp.ast.JspCharStream; -import net.sourceforge.pmd.jsp.ast.JspParser; - -import org.apache.xml.serialize.OutputFormat; -import org.apache.xml.serialize.XMLSerializer; -import org.jaxen.BaseXPath; -import org.jaxen.JaxenException; -import org.jaxen.XPath; - -import javax.swing.*; import java.awt.BorderLayout; import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; @@ -43,86 +24,359 @@ import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Enumeration; import java.util.Iterator; import java.util.List; +import java.util.Vector; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.DefaultListModel; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.ScrollPaneConstants; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; + +import net.sourceforge.pmd.PMD; +import net.sourceforge.pmd.RuleContext; +import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.SourceType; +import net.sourceforge.pmd.TargetJDK1_3; +import net.sourceforge.pmd.TargetJDK1_4; +import net.sourceforge.pmd.TargetJDK1_5; +import net.sourceforge.pmd.ast.Node; +import net.sourceforge.pmd.ast.ParseException; +import net.sourceforge.pmd.ast.SimpleNode; +import net.sourceforge.pmd.jaxen.DocumentNavigator; +import net.sourceforge.pmd.jaxen.MatchesFunction; +import net.sourceforge.pmd.jsp.ast.JspCharStream; +import net.sourceforge.pmd.jsp.ast.JspParser; + +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; +import org.jaxen.BaseXPath; +import org.jaxen.JaxenException; +import org.jaxen.XPath; public class Designer implements ClipboardOwner { - private JavaParser createParser() { - return getJDKVersion().createParser(new StringReader(codeEditorPane.getText())); - } + private static final char labelImageSeparator = ':'; + private static final Color imageTextColour = Color.BLUE; + private static final String lineSeparator = System.getProperty("line.separator", "\n"); + + private interface Parser { public SimpleNode parse(StringReader sr); }; + + private static final Parser jdkParser1_3 = new Parser() { + public SimpleNode parse(StringReader sr) { return (new TargetJDK1_3()).createParser(sr).CompilationUnit(); }; + }; + + private static final Parser jdkParser1_4 = new Parser() { + public SimpleNode parse(StringReader sr) { return (new TargetJDK1_4()).createParser(sr).CompilationUnit(); }; + }; + + private static final Parser jdkParser1_5 = new Parser() { + public SimpleNode parse(StringReader sr) { return (new TargetJDK1_5()).createParser(sr).CompilationUnit(); }; + }; + + private static final Parser jspParser = new Parser() { + public SimpleNode parse(StringReader sr) { return (new JspParser(new JspCharStream(sr))).CompilationUnit(); }; + }; + + private static final Object[][] sourceTypeSets = new Object[][] { + { "JDK 1.3", SourceType.JAVA_13, jdkParser1_3 }, + { "JDK 1.4", SourceType.JAVA_14, jdkParser1_4 }, + { "JDK 1.5", SourceType.JAVA_15, jdkParser1_5 }, + { "JSP", SourceType.JSP, jspParser } + }; + + private static final int defaultSourceTypeSelectionIndex = 1; // JDK 1.4 + - private JspParser createJspParser() { - return new JspParser(new JspCharStream(new StringReader(codeEditorPane.getText()))); + private SimpleNode getCompilationUnit() { + + Parser parser = (Parser)sourceTypeSets[selectedSourceTypeIndex()][2]; + return parser.parse(new StringReader(codeEditorPane.getText())); } - - private SimpleNode getCompilationUnit() { - if (getSourceType().equals(SourceType.JSP)) { - return createJspParser().CompilationUnit(); - } - return createParser().CompilationUnit(); + private SourceType getSourceType() { + + return (SourceType)sourceTypeSets[selectedSourceTypeIndex()][1]; } - - private TargetJDKVersion getJDKVersion() { - if (jdk14MenuItem.isSelected()) { - return new TargetJDK1_4(); - } else if (jdk13MenuItem.isSelected()) { - return new TargetJDK1_3(); - } - return new TargetJDK1_5(); + + private int selectedSourceTypeIndex() { + for (int i=0; i<sourceTypeMenuItems.length; i++) { + if (sourceTypeMenuItems[i].isSelected()) return i; + } + throw new RuntimeException("Initial default source type not specified"); } - private SourceType getSourceType() { - if (jspMenuItem.isSelected()) { - return SourceType.JSP; - } else if (jdk14MenuItem.isSelected()) { - return SourceType.JAVA_14; - } else if (jdk13MenuItem.isSelected()) { - return SourceType.JAVA_13; + private class ExceptionNode implements TreeNode { + + private Object item; + private ExceptionNode[] kids; + + public ExceptionNode(Object theItem) { + item = theItem; + + if (item instanceof ParseException) createKids(); + } + + // each line in the error message becomes a separate tree node + private void createKids() { + + String message = ((ParseException)item).getMessage(); + String[] lines = message.split(lineSeparator); + + kids = new ExceptionNode[lines.length]; + for (int i=0; i<lines.length; i++) { + kids[i] = new ExceptionNode(lines[i]); + }; + } + + public int getChildCount() { return kids == null ? 0 : kids.length; } + public boolean getAllowsChildren() {return false; } + public boolean isLeaf() { return kids == null; } + public TreeNode getParent() { return null; } + public TreeNode getChildAt(int childIndex) { return kids[childIndex]; } + public String label() { return item.toString(); } + + public Enumeration children() { + Enumeration e = new Enumeration() { + int i = 0; + public boolean hasMoreElements() { + return kids != null && i < kids.length; + } + + public Object nextElement() { return kids[i++]; } + }; + return e; + } + + public int getIndex(TreeNode node) { + for (int i=0; i<kids.length; i++) { + if (kids[i] == node) return i; + } + return -1; + } + } + + // Tree node that wraps the AST node for the tree widget and + // any possible children they may have. + private class ASTTreeNode implements TreeNode { + + private Node node; + private ASTTreeNode parent; + private ASTTreeNode[] kids; + + public ASTTreeNode(Node theNode) { + node = theNode; + + Node prnt = node.jjtGetParent(); + if (prnt != null) parent = new ASTTreeNode(prnt); + } + + public int getChildCount() { return node.jjtGetNumChildren(); } + public boolean getAllowsChildren() { return false; } + public boolean isLeaf() { return node.jjtGetNumChildren() == 0; } + public TreeNode getParent() { return parent; } + + public Enumeration children() { + + if (getChildCount() > 0) getChildAt(0); // force it to build kids + + Enumeration e = new Enumeration() { + int i = 0; + public boolean hasMoreElements() { + return kids != null && i < kids.length; + } + public Object nextElement() { return kids[i++]; } + }; + return e; + } + + public TreeNode getChildAt(int childIndex) { + + if (kids == null) { + kids = new ASTTreeNode[node.jjtGetNumChildren()]; + for (int i=0; i<kids.length; i++) { + kids[i] = new ASTTreeNode(node.jjtGetChild(i)); + } + } + return kids[childIndex]; + } + + public int getIndex(TreeNode node) { + + for (int i=0; i<kids.length; i++) { + if (kids[i] == node) return i; + } + return -1; + } + + public String label() { + if (node instanceof SimpleNode) { + SimpleNode sn = (SimpleNode)node; + if (sn.getImage() == null) return node.toString(); + return node.toString() + labelImageSeparator + sn.getImage(); + } + return node.toString(); + } + } + + // Create our own renderer to ensure we don't show the default icon + // and render any node image data in a different colour to hightlight + // it. + + private class ASTCellRenderer extends DefaultTreeCellRenderer { + + private ASTTreeNode node; + + public Icon getIcon() { return null; }; + + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,boolean expanded,boolean leaf, int row, boolean hasFocus) { + + if (value instanceof ASTTreeNode) { + node = (ASTTreeNode)value; + } + return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); + } + + // overwrite the image data (if present) in a different colour + public void paint(Graphics g) { + + super.paint(g); + + if (node == null) return; + + String text = node.label(); + int separatorPos = text.indexOf(labelImageSeparator); + if (separatorPos < 0) return; + + String label = text.substring(0, separatorPos+1); + String image = text.substring(separatorPos+1); + + FontMetrics fm = g.getFontMetrics(); + int width = SwingUtilities.computeStringWidth(fm, label); + + g.setColor(imageTextColour); + g.drawString(image, width, fm.getMaxAscent()); + } + } + + // Special tree variant that knows how to retrieve node labels and + // provides the ability to expand all nodes at once. + + private class ASTTreeWidget extends JTree { + + public ASTTreeWidget(Vector items) { + super(items); + } + + public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { + if (value == null) return ""; + if (value instanceof ASTTreeNode) { + return ((ASTTreeNode)value).label(); + } + if (value instanceof ExceptionNode) { + return ((ExceptionNode)value).label(); + } + return value.toString(); + } + + public void expandAll(boolean expand) { + TreeNode root = (TreeNode)getModel().getRoot(); + expandAll(new TreePath(root), expand); } - return SourceType.JAVA_15; + + private void expandAll(TreePath parent, boolean expand) { + // Traverse children + TreeNode node = (TreeNode)parent.getLastPathComponent(); + if (node.getChildCount() >= 0) { + for (Enumeration e=node.children(); e.hasMoreElements(); ) { + TreeNode n = (TreeNode)e.nextElement(); + TreePath path = parent.pathByAddingChild(n); + expandAll(path, expand); + } + } + + if (expand) { + expandPath(parent); + } else { + collapsePath(parent); + } + } + } + + private void loadTreeData(TreeNode rootNode) { + astWidget.setModel(new DefaultTreeModel(rootNode)); + astWidget.expandAll(true); } private class ShowListener implements ActionListener { public void actionPerformed(ActionEvent ae) { MyPrintStream ps = new MyPrintStream(); System.setOut(ps); + TreeNode tn; try { SimpleNode lastCompilationUnit = getCompilationUnit(); - lastCompilationUnit.dump(""); - astArea.setText(ps.getString()); - } catch (ParseException pe) { - astArea.setText(pe.fillInStackTrace().getMessage()); - } + tn = new ASTTreeNode(lastCompilationUnit); + } catch (ParseException pe) { + tn = new ExceptionNode(pe); + } + + loadTreeData(tn); } } private class DFAListener implements ActionListener { public void actionPerformed(ActionEvent ae) { - try { - DFAGraphRule dfaGraphRule = new DFAGraphRule(); - RuleSet rs = new RuleSet(); - SourceType sourceType = getSourceType(); - if(!sourceType.equals(SourceType.JSP)){ - rs.addRule(dfaGraphRule); - } - RuleContext ctx = new RuleContext(); - ctx.setSourceCodeFilename("[no filename]"); - StringReader reader = new StringReader(codeEditorPane.getText()); - PMD pmd = new PMD(); - pmd.setJavaVersion(getSourceType()); + + DFAGraphRule dfaGraphRule = new DFAGraphRule(); + RuleSet rs = new RuleSet(); + SourceType sourceType = getSourceType(); + if (!sourceType.equals(SourceType.JSP)){ + rs.addRule(dfaGraphRule); + } + RuleContext ctx = new RuleContext(); + ctx.setSourceCodeFilename("[no filename]"); + StringReader reader = new StringReader(codeEditorPane.getText()); + PMD pmd = new PMD(); + pmd.setJavaVersion(sourceType); + + try { pmd.processFile(reader, rs, ctx); - List methods = dfaGraphRule.getMethods(); - if (methods != null && !methods.isEmpty()) { - dfaPanel.resetTo(methods, codeEditorPane); - dfaPanel.repaint(); - } - } catch (Exception e) { - e.printStackTrace(); - } +// } catch (PMDException pmde) { +// loadTreeData(new ExceptionNode(pmde)); + } catch (Exception e) { + e.printStackTrace(); + } + + List methods = dfaGraphRule.getMethods(); + if (methods != null && !methods.isEmpty()) { + dfaPanel.resetTo(methods, codeEditorPane); + dfaPanel.repaint(); + } } - } private class XPathListener implements ActionListener { @@ -147,7 +401,7 @@ public void actionPerformed(ActionEvent ae) { SimpleNode node = (SimpleNode) obj; String name = node.getClass().getName().substring(node.getClass().getName().lastIndexOf('.') + 1); String line = " at line " + String.valueOf(node.getBeginLine()); - sb.append(name).append(line).append(System.getProperty("line.separator")); + sb.append(name).append(line).append(lineSeparator); xpathResults.addElement(sb.toString().trim()); } } @@ -165,17 +419,14 @@ public void actionPerformed(ActionEvent ae) { } private final CodeEditorTextPane codeEditorPane = new CodeEditorTextPane(); - private final JTextArea astArea = new JTextArea(); - private DefaultListModel xpathResults = new DefaultListModel(); - private final JList xpathResultList = new JList(xpathResults); - private final JTextArea xpathQueryArea = new JTextArea(15, 30); - private final JFrame frame = new JFrame("PMD Rule Designer"); - private final DFAPanel dfaPanel = new DFAPanel(); - private JRadioButtonMenuItem jdk13MenuItem; - private JRadioButtonMenuItem jdk14MenuItem; - private JRadioButtonMenuItem jdk15MenuItem; - private JRadioButtonMenuItem jspMenuItem; - + private final ASTTreeWidget astWidget = new ASTTreeWidget(new Vector()); + private DefaultListModel xpathResults = new DefaultListModel(); + private final JList xpathResultList = new JList(xpathResults); + private final JTextArea xpathQueryArea = new JTextArea(15, 30); + private final JFrame frame = new JFrame("PMD Rule Designer"); + private final DFAPanel dfaPanel = new DFAPanel(); + private final JRadioButtonMenuItem[] sourceTypeMenuItems = new JRadioButtonMenuItem[sourceTypeSets.length]; + public Designer() { MatchesFunction.registerSelfInSimpleContext(); @@ -216,8 +467,10 @@ public Designer() { frame.getContentPane().add(containerSplitPane); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; - int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + int screenHeight = screenSize.height; + int screenWidth = screenSize.width; + frame.setSize(screenHeight - (screenHeight / 4), screenHeight - (screenHeight / 4)); frame.setLocation((screenWidth / 2) - frame.getWidth() / 2, (screenHeight / 2) - frame.getHeight() / 2); frame.setVisible(true); @@ -231,22 +484,14 @@ private JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("JDK"); ButtonGroup group = new ButtonGroup(); - jdk13MenuItem = new JRadioButtonMenuItem("JDK 1.3"); - jdk13MenuItem.setSelected(false); - group.add(jdk13MenuItem); - menu.add(jdk13MenuItem); - jdk14MenuItem = new JRadioButtonMenuItem("JDK 1.4"); - jdk14MenuItem.setSelected(true); - group.add(jdk14MenuItem); - menu.add(jdk14MenuItem); - jdk15MenuItem = new JRadioButtonMenuItem("JDK 1.5"); - jdk15MenuItem.setSelected(false); - group.add(jdk15MenuItem); - menu.add(jdk15MenuItem); - jspMenuItem = new JRadioButtonMenuItem("JSP"); - jspMenuItem.setSelected(false); - group.add(jspMenuItem); - menu.add(jspMenuItem); + + for (int i=0; i<sourceTypeSets.length; i++) { + JRadioButtonMenuItem button = new JRadioButtonMenuItem(sourceTypeSets[i][0].toString()); + sourceTypeMenuItems[i] = button; + group.add(button); + menu.add(button); + } + sourceTypeMenuItems[defaultSourceTypeSelectionIndex].setSelected(true); menuBar.add(menu); JMenu actionsMenu = new JMenu("Actions"); @@ -269,7 +514,6 @@ public void actionPerformed(ActionEvent e) { return menuBar; } - private void createRuleXML() { JPanel rulenamePanel = new JPanel(); rulenamePanel.setLayout(new FlowLayout()); @@ -349,12 +593,10 @@ public void actionPerformed(ActionEvent e) { } private JComponent createASTPanel() { - astArea.setRows(10); - astArea.setColumns(20); - JScrollPane astScrollPane = new JScrollPane(astArea); - return astScrollPane; + astWidget.setCellRenderer(new ASTCellRenderer()); + return new JScrollPane(astWidget); } - + private JComponent createXPathResultPanel() { xpathResults.addElement("No results yet"); xpathResultList.setBorder(BorderFactory.createLineBorder(Color.black)); @@ -414,7 +656,7 @@ private final void copyXmlToClipboard() { * Returns an unformatted xml string (without the declaration) * * @param node - * @return + * @return String * @throws java.io.IOException */ private String getXmlString(SimpleNode node) throws IOException { diff --git a/pmd/xdocs/credits.xml b/pmd/xdocs/credits.xml index 0f794f78565..fb8c051bdb3 100644 --- a/pmd/xdocs/credits.xml +++ b/pmd/xdocs/credits.xml @@ -48,7 +48,7 @@ </subsection> <subsection name="Contributors"> <ul> - <li>Brian Remedios - code cleanup of net.sourceforge.pmd.ant.Formatter.java, code improvements to Eclipse plugin, Created AbstractPoorMethodCall & Refactored UseIndexOfChar</li> + <li>Brian Remedios - code cleanup of rule designer, code cleanup of net.sourceforge.pmd.ant.Formatter.java, code improvements to Eclipse plugin, Created AbstractPoorMethodCall & Refactored UseIndexOfChar</li> <li>Adam Zell - Reported bug in UselessOverridingMethod</li> <li>Daniel Serodio - Reported bug in ExceptionSignatureDeclaration</li> <li>John Redford - Reported bug in AvoidProtectedFieldInFinalClass</li>
697192068a4c9f42e5e3b1b7bb6f2c389c389506
Vala
glib-2.0: add byte order swap macros Fixes bug 613473.
a
https://github.com/GNOME/vala/
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi index 7b1b47f16f..3421a5d7b5 100644 --- a/vapi/glib-2.0.vapi +++ b/vapi/glib-2.0.vapi @@ -418,6 +418,13 @@ public struct uint16 { public static uint16 from_big_endian (uint16 val); [CCode (cname = "GUINT16_FROM_LE")] public static uint16 from_little_endian (uint16 val); + + [CCode (cname = "GUINT16_SWAP_BE_PDP")] + public uint16 swap_big_endian_pdp (); + [CCode (cname = "GUINT16_SWAP_LE_BE")] + public uint16 swap_little_endian_big_endian (); + [CCode (cname = "GUINT16_SWAP_LE_PDP")] + public uint16 swap_little_endian_pdp (); } [SimpleType] @@ -488,6 +495,13 @@ public struct uint32 { public static uint32 from_big_endian (uint32 val); [CCode (cname = "GUINT32_FROM_LE")] public static uint32 from_little_endian (uint32 val); + + [CCode (cname = "GUINT32_SWAP_BE_PDP")] + public uint32 swap_big_endian_pdp (); + [CCode (cname = "GUINT32_SWAP_LE_BE")] + public uint32 swap_little_endian_big_endian (); + [CCode (cname = "GUINT32_SWAP_LE_PDP")] + public uint32 swap_little_endian_pdp (); } [SimpleType] @@ -525,6 +539,9 @@ public struct int64 { public static int64 from_big_endian (int64 val); [CCode (cname = "GINT64_FROM_LE")] public static int64 from_little_endian (int64 val); + + [CCode (cname = "GUINT64_SWAP_LE_BE")] + public uint64 swap_little_endian_big_endian (); } [SimpleType] @@ -1243,6 +1260,8 @@ namespace GLib { PDP_ENDIAN } + public const ByteOrder BYTE_ORDER; + /* Atomic Operations */ namespace AtomicInt {
93fbeee2b06807a7190b82edb46db3f43f9b84bb
Vala
glib-2.0: add g_date_set_time_t binding
a
https://github.com/GNOME/vala/
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi index 18872b0ac4..7b1b47f16f 100644 --- a/vapi/glib-2.0.vapi +++ b/vapi/glib-2.0.vapi @@ -1963,6 +1963,7 @@ namespace GLib { public void set_year (DateYear year); public void set_dmy (DateDay day, int month, DateYear y); public void set_julian (uint julian_day); + public void set_time_t (time_t timet); public void set_time_val (TimeVal timeval); public void set_parse (string str); public void add_days (uint n_days);