Example usage for org.eclipse.jdt.core IJavaProject findPackageFragmentRoot

List of usage examples for org.eclipse.jdt.core IJavaProject findPackageFragmentRoot

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject findPackageFragmentRoot.

Prototype

IPackageFragmentRoot findPackageFragmentRoot(IPath path) throws JavaModelException;

Source Link

Document

Returns the existing package fragment root on this project's classpath whose path matches the given (absolute) path, or null if one does not exist.

Usage

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that removing a tag from a type updates the workspace baseline
 * //  ww  w .  jav  a2s.c  o  m
 * This test removes a @noinstantiate tag to an inner class in TestClass3
 */
public void testWPUpdateSourceTypeRemoveTag() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestClass3"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestClass3.java")); //$NON-NLS-1$
    assertNotNull("TestClass3 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "InnerTestClass3", null, "@noextend", true); //$NON-NLS-1$ //$NON-NLS-2$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.typeDescriptor("a.b.c.TestClass3$InnerTestClass3")); //$NON-NLS-1$
    assertNotNull("the annotations for 'InnerTestClass3' cannot be null", annot); //$NON-NLS-1$
    assertTrue("there must be a no restrictions for 'InnerTestClass3'", //$NON-NLS-1$
            (annot.getRestrictions() & RestrictionModifiers.NO_INSTANTIATE) == 0);
}

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that removing a tag from a field updates the workspace baseline
 * // w w w.  ja v a2  s  .co m
 * This test adds a @noextend tag to the field 'field' in TestField9
 */
public void testWPUpdateSourceFieldRemoveTag() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestField9"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestField9.java")); //$NON-NLS-1$
    assertNotNull("TestField9 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "field1", null, "@noreference", true); //$NON-NLS-1$ //$NON-NLS-2$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.fieldDescriptor("a.b.c.TestField9", "field")); //$NON-NLS-1$ //$NON-NLS-2$
    assertNotNull("the annotations for 'field' cannot be null", annot); //$NON-NLS-1$
    assertTrue("there must be a no restrictions for 'field'", annot.getRestrictions() == 0); //$NON-NLS-1$
}

From source file:org.eclipse.pde.internal.core.util.PDEJavaHelper.java

License:Open Source License

private static IPackageFragment getExternalPackageFragment(String packageName, String pluginID) {
    if (pluginID == null)
        return null;
    IPluginModelBase base = null;/*from w  ww .  j  a v a2  s  .c  om*/
    try {
        IPluginModelBase plugin = PluginRegistry.findModel(pluginID);
        if (plugin == null)
            return null;
        ImportPackageSpecification[] packages = plugin.getBundleDescription().getImportPackages();
        for (int i = 0; i < packages.length; i++)
            if (packages[i].getName().equals(packageName)) {
                ExportPackageDescription desc = (ExportPackageDescription) packages[i].getSupplier();
                if (desc != null)
                    base = PluginRegistry.findModel(desc.getExporter().getSymbolicName());
                break;
            }
        if (base == null)
            return null;
        IResource res = base.getUnderlyingResource();
        if (res != null) {
            IJavaProject jp = JavaCore.create(res.getProject());
            if (jp != null)
                try {
                    IPackageFragmentRoot[] roots = jp.getAllPackageFragmentRoots();
                    for (int i = 0; i < roots.length; i++) {
                        IPackageFragment frag = roots[i].getPackageFragment(packageName);
                        if (frag.exists())
                            return frag;
                    }
                } catch (JavaModelException e) {
                }
        }
        IProject proj = PDECore.getWorkspace().getRoot()
                .getProject(SearchablePluginsManager.PROXY_PROJECT_NAME);
        if (proj == null)
            return searchWorkspaceForPackage(packageName, base);
        IJavaProject jp = JavaCore.create(proj);
        IPath path = new Path(base.getInstallLocation());
        // if model is in jar form
        if (!path.toFile().isDirectory()) {
            IPackageFragmentRoot root = jp.findPackageFragmentRoot(path);
            if (root != null) {
                IPackageFragment frag = root.getPackageFragment(packageName);
                if (frag.exists())
                    return frag;
            }
            // else model is in folder form, try to find model's libraries on filesystem
        } else {
            IPluginLibrary[] libs = base.getPluginBase().getLibraries();
            for (int i = 0; i < libs.length; i++) {
                if (IPluginLibrary.RESOURCE.equals(libs[i].getType()))
                    continue;
                String libName = ClasspathUtilCore.expandLibraryName(libs[i].getName());
                IPackageFragmentRoot root = jp.findPackageFragmentRoot(path.append(libName));
                if (root != null) {
                    IPackageFragment frag = root.getPackageFragment(packageName);
                    if (frag.exists())
                        return frag;
                }
            }
        }
    } catch (JavaModelException e) {
    }
    return searchWorkspaceForPackage(packageName, base);
}

From source file:org.eclipse.pde.internal.core.util.PDEJavaHelper.java

License:Open Source License

private static IPackageFragment searchWorkspaceForPackage(String packageName, IPluginModelBase base) {
    IPluginLibrary[] libs = base.getPluginBase().getLibraries();
    ArrayList<IPath> libPaths = new ArrayList<IPath>();
    IPath path = new Path(base.getInstallLocation());
    if (libs.length == 0) {
        libPaths.add(path);/*from   w  w w  .ja v a2 s .co  m*/
    }
    for (int i = 0; i < libs.length; i++) {
        if (IPluginLibrary.RESOURCE.equals(libs[i].getType()))
            continue;
        String libName = ClasspathUtilCore.expandLibraryName(libs[i].getName());
        libPaths.add(path.append(libName));
    }
    IProject[] projects = PDECore.getWorkspace().getRoot().getProjects();
    for (int i = 0; i < projects.length; i++) {
        try {
            if (!projects[i].hasNature(JavaCore.NATURE_ID) || !projects[i].isOpen())
                continue;
            IJavaProject jp = JavaCore.create(projects[i]);
            ListIterator<IPath> li = libPaths.listIterator();
            while (li.hasNext()) {
                IPackageFragmentRoot root = jp.findPackageFragmentRoot(li.next());
                if (root != null) {
                    IPackageFragment frag = root.getPackageFragment(packageName);
                    if (frag.exists())
                        return frag;
                }
            }
        } catch (CoreException e) {
        }
    }
    return null;
}

From source file:org.eclipse.wb.tests.designer.core.nls.EditableSupportTest.java

License:Open Source License

public void test_addSource() throws Exception {
    waitForAutoBuild();/*from w  w  w . j a  v a  2s  .  c  om*/
    ContainerInfo frame = parseContainer("public class Test extends JFrame {", "  public Test() {",
            "    setTitle('My JFrame');", "    //", "    JButton button = new JButton('abc');",
            "    getContentPane().add(button);", "  }", "}");
    ContainerInfo contentPane = (ContainerInfo) frame.getChildrenComponents().get(0);
    ComponentInfo button = contentPane.getChildrenComponents().get(0);
    NlsSupport support = NlsSupport.get(frame);
    //
    // STAGE #1
    //
    {
        EditableSupport editableSupport = (EditableSupport) support.getEditable();
        // add listener
        final StringBuffer buffer = new StringBuffer();
        IEditableSupportListener editableSupportListener = createEditableSupportListener(buffer);
        editableSupport.addListener(editableSupportListener);
        // addSource()
        IEditableSource editableSource;
        {
            editableSource = NlsTestUtils.createEmptyEditable("messages");
            SourceDescription sourceDescription = NlsSupport.getSourceDescriptions(frame)[0];
            // prepare parameters
            SourceParameters parameters = new SourceParameters();
            IJavaProject javaProject = m_lastEditor.getJavaProject();
            {
                parameters.m_accessorSourceFolder = javaProject
                        .findPackageFragmentRoot(new Path("/TestProject/src"));
                parameters.m_accessorPackage = javaProject
                        .findPackageFragment(new Path("/TestProject/src/test"));
                parameters.m_accessorPackageName = parameters.m_accessorPackage.getElementName();
                parameters.m_accessorClassName = "Messages";
                parameters.m_accessorFullClassName = "test.Messages";
                parameters.m_accessorExists = false;
            }
            {
                parameters.m_propertySourceFolder = parameters.m_accessorSourceFolder;
                parameters.m_propertyPackage = parameters.m_accessorPackage;
                parameters.m_propertyFileName = "messages.properties";
                parameters.m_propertyBundleName = "test.messages";
                parameters.m_propertyFileExists = false;
            }
            parameters.m_withDefaultValue = true;
            // do add
            editableSupport.addSource(editableSource, sourceDescription, parameters);
            assertContains(buffer, "sourceAdded");
        }
        // no key before externalizing
        {
            assertTrue(editableSource.getKeys().isEmpty());
            assertTrue(editableSource.getFormKeys().isEmpty());
        }
        // externalize
        {
            List<StringPropertyInfo> properties = Lists.newArrayList();
            properties.addAll(editableSupport.getProperties(frame));
            properties.addAll(editableSupport.getProperties(button));
            for (StringPropertyInfo propertyInfo : properties) {
                editableSupport.externalizeProperty(propertyInfo, editableSource, true);
                assertContains(buffer, "externalizedPropertiesChanged");
            }
        }
        // check keys
        {
            assertStringSet(editableSource.getKeys(), new String[] { "Test.this.title", "Test.button.text" });
            assertStringSet(editableSource.getFormKeys(),
                    new String[] { "Test.this.title", "Test.button.text" });
            checkComponentsMap(editableSource, new String[] { "Test.this.title", "Test.button.text" },
                    new JavaInfo[][] { new JavaInfo[] { frame }, new JavaInfo[] { button } });
        }
        // check values
        {
            assertEquals("My JFrame", editableSource.getValue(LocaleInfo.DEFAULT, "Test.this.title"));
            assertEquals("abc", editableSource.getValue(LocaleInfo.DEFAULT, "Test.button.text"));
        }
        // check for value in not existing locale
        {
            String value = editableSource.getValue(new LocaleInfo(Locale.GERMAN), "Test.this.title");
            assertNull(value);
        }
        // rename key
        {
            IEditableSourceListener listener = createEditableSourceListener(buffer);
            editableSource.addListener(listener);
            // don't change key, ignored, no log expected
            editableSource.renameKey("Test.button.text", "Test.button.text");
            assertTrue(buffer.length() == 0);
            // change wrong key, ignored, no log expected
            editableSource.renameKey("no-such-key", "some-other-key");
            assertTrue(buffer.length() == 0);
            // rename key with listener
            editableSource.renameKey("Test.button.text", "Test.button.text3");
            assertContains(buffer, "keyRenamed: Test.button.text -> Test.button.text3");
            // remove listener, no log in buffer expected
            editableSource.removeListener(listener);
            editableSource.renameKey("Test.button.text3", "Test.button.text2");
            assertTrue(buffer.length() == 0);
            // check keys
            {
                assertStringSet(editableSource.getKeys(),
                        new String[] { "Test.this.title", "Test.button.text2" });
                assertStringSet(editableSource.getFormKeys(),
                        new String[] { "Test.this.title", "Test.button.text2" });
                checkComponentsMap(editableSource, new String[] { "Test.this.title", "Test.button.text2" },
                        new JavaInfo[][] { new JavaInfo[] { frame }, new JavaInfo[] { button } });
            }
            // check values
            {
                assertEquals("My JFrame", editableSource.getValue(LocaleInfo.DEFAULT, "Test.this.title"));
                assertEquals("abc", editableSource.getValue(LocaleInfo.DEFAULT, "Test.button.text2"));
            }
        }
        // apply commands
        support.applyEditable(editableSupport);
        editableSupport.removeListener(editableSupportListener);
        // checks
        {
            {
                String newProperties = getFileContentSrc("test/messages.properties");
                assertTrue(newProperties.contains("#Eclipse messages class"));
                assertTrue(newProperties.contains("Test.this.title=My JFrame"));
                assertTrue(newProperties.contains("Test.button.text2=abc"));
            }
            assertEditor("public class Test extends JFrame {", "  public Test() {",
                    "    setTitle(Messages.getString(\"Test.this.title\", \"My JFrame\")); //$NON-NLS-1$ //$NON-NLS-2$",
                    "    //",
                    "    JButton button = new JButton(Messages.getString(\"Test.button.text2\", \"abc\")); //$NON-NLS-1$ //$NON-NLS-2$",
                    "    getContentPane().add(button);", "  }", "}");
        }
    }
    //
    // STAGE #2
    //
    {
        final StringBuffer buffer = new StringBuffer();
        // prepare editable support
        EditableSupport editableSupport = (EditableSupport) support.getEditable();
        editableSupport.addListener(createEditableSupportListener(buffer));
        // prepare editable source
        IEditableSource editableSource = getSingleExistingEditableSource(editableSupport, buffer);
        // internalize
        {
            assertStringSet(editableSource.getKeys(), new String[] { "Test.this.title", "Test.button.text2" });
            //
            editableSource.internalizeKey("Test.button.text2");
            assertContains(buffer, "externalizedPropertiesChanged", false);
            assertContains(buffer, "keyRemoved: Test.button.text2");
            //
            assertStringSet(editableSource.getKeys(), new String[] { "Test.this.title" });
            checkComponentsMap(editableSource, new String[] { "Test.this.title" },
                    new JavaInfo[][] { new JavaInfo[] { frame } });
        }
        // apply commands
        support.applyEditable(editableSupport);
        // checks
        {
            {
                String newProperties = getFileContentSrc("test/messages.properties");
                assertTrue(newProperties.contains("Test.this.title=My JFrame"));
                assertFalse(newProperties.contains("Test.button.text2=abc"));
            }
            assertEditor("public class Test extends JFrame {", "  public Test() {",
                    "    setTitle(Messages.getString(\"Test.this.title\", \"My JFrame\")); //$NON-NLS-1$ //$NON-NLS-2$",
                    "    //", "    JButton button = new JButton(\"abc\");", "    getContentPane().add(button);",
                    "  }", "}");
        }
    }
    frame.refresh();
    //
    // STAGE #3
    //
    {
        final StringBuffer buffer = new StringBuffer();
        // prepare editable support
        EditableSupport editableSupport = (EditableSupport) support.getEditable();
        editableSupport.addListener(createEditableSupportListener(buffer));
        // prepare editable source
        IEditableSource editableSource = getSingleExistingEditableSource(editableSupport, buffer);
        // externalize
        {
            assertStringSet(editableSource.getKeys(), new String[] { "Test.this.title" });
            //
            StringPropertyInfo property = editableSupport.getProperties(button).get(0);
            editableSource.externalize(property, true);
            assertContains(buffer, "externalizedPropertiesChanged", false);
            assertContains(buffer, "keyAdded: Test.button.text");
            //
            assertStringSet(editableSource.getKeys(), new String[] { "Test.this.title", "Test.button.text" });
            checkComponentsMap(editableSource, new String[] { "Test.this.title", "Test.button.text" },
                    new JavaInfo[][] { new JavaInfo[] { frame }, new JavaInfo[] { button } });
        }
        // set "empty" value for unknown key, ignored
        {
            String key = "no-such-key";
            editableSource.setValue(LocaleInfo.DEFAULT, key, "");
            assertNull(editableSource.getValue(LocaleInfo.DEFAULT, key));
        }
        // set same value, ignored
        {
            String key = "Test.this.title";
            String oldValue = editableSource.getValue(LocaleInfo.DEFAULT, key);
            editableSource.setValue(LocaleInfo.DEFAULT, key, new String("My JFrame"));
            assertSame(oldValue, editableSource.getValue(LocaleInfo.DEFAULT, key));
        }
        // locales
        {
            {
                LocaleInfo[] locales = editableSource.getLocales();
                assertEquals(1, locales.length);
                assertEquals("(default)", locales[0].getTitle());
            }
            // add locales
            editableSource.addLocale(new LocaleInfo(new Locale("it")), LocaleInfo.DEFAULT);
            editableSource.addLocale(new LocaleInfo(new Locale("fr")), null);
            {
                LocaleInfo[] locales = editableSource.getLocales();
                assertEquals(3, locales.length);
                assertEquals("(default)", locales[0].getTitle());
                assertEquals("fr", locales[1].getTitle());
                assertEquals("it", locales[2].getTitle());
            }
        }
        // apply commands
        support.applyEditable(editableSupport);
        // checks
        {
            // *.properties: default
            {
                String newProperties = getFileContentSrc("test/messages.properties");
                assertTrue(newProperties.contains("Test.this.title=My JFrame"));
                assertTrue(newProperties.contains("Test.button.text=abc"));
            }
            // *.properties: it
            {
                String newProperties = getFileContentSrc("test/messages_it.properties");
                assertTrue(newProperties.contains("Test.this.title=My JFrame"));
                assertTrue(newProperties.contains("Test.button.text=abc"));
            }
            // *.properties: fr
            {
                String newProperties = getFileContentSrc("test/messages_fr.properties");
                assertFalse(newProperties.contains("Test.this.title=My JFrame"));
                assertFalse(newProperties.contains("Test.button.text=abc"));
            }
            assertEditor("public class Test extends JFrame {", "  public Test() {",
                    "    setTitle(Messages.getString(\"Test.this.title\", \"My JFrame\")); //$NON-NLS-1$ //$NON-NLS-2$",
                    "    //",
                    "    JButton button = new JButton(Messages.getString(\"Test.button.text\", \"abc\")); //$NON-NLS-1$ //$NON-NLS-2$",
                    "    getContentPane().add(button);", "  }", "}");
        }
    }
    frame.refresh();
    //
    // STAGE #4
    //
    {
        final StringBuffer buffer = new StringBuffer();
        // prepare editable support
        EditableSupport editableSupport = (EditableSupport) support.getEditable();
        editableSupport.addListener(createEditableSupportListener(buffer));
        // prepare editable source
        IEditableSource editableSource = getSingleExistingEditableSource(editableSupport, buffer);
        // rename key (in 'fr' we don't have value)
        {
            editableSource.renameKey("Test.button.text", "Test.button.text3");
            assertContains(buffer, "keyRenamed: Test.button.text -> Test.button.text3");
        }
        // remove locale
        {
            {
                LocaleInfo[] locales = editableSource.getLocales();
                assertEquals(3, locales.length);
                assertEquals("fr", locales[1].toString());
                assertEquals("it", locales[2].toString());
            }
            editableSource.removeLocale(editableSource.getLocales()[1]);
            {
                LocaleInfo[] locales = editableSource.getLocales();
                assertEquals(2, locales.length);
                assertEquals("(default)", locales[0].getTitle());
                assertEquals("it", locales[1].getTitle());
            }
        }
        // apply commands
        support.applyEditable(editableSupport);
        // checks
        {
            assertTrue(getFileSrc("test", "messages.properties").exists());
            assertTrue(getFileSrc("test", "messages_it.properties").exists());
            // *.properties: fr - should be removed
            assertFalse(getFileSrc("test", "messages_fr.properties").exists());
        }
    }
    frame.refresh();
    // clean up
    frame.refresh_dispose();
}

From source file:org.eclipse.wb.tests.designer.core.nls.SourceDirectTest.java

License:Open Source License

public void test_create() throws Exception {
    ContainerInfo frame = parseContainer("public class Test extends JFrame {", "  public Test() {",
            "    setTitle('My JFrame');", "  }", "}");
    NlsSupport support = NlsSupport.get(frame);
    IEditableSupport editableSupport = support.getEditable();
    // prepare editable source
    IEditableSource editableSource = NlsTestUtils.createEmptyEditable("test.messages");
    // prepare parameters
    SourceParameters parameters = new SourceParameters();
    IJavaProject javaProject = m_lastEditor.getJavaProject();
    {// w  w w  . j a v a 2  s  .c o m
        parameters.m_propertySourceFolder = javaProject.findPackageFragmentRoot(new Path("/TestProject/src"));
        parameters.m_propertyPackage = javaProject.findPackageFragment(new Path("/TestProject/src/test"));
        parameters.m_propertyFileName = "messages.properties";
        parameters.m_propertyBundleName = "test.messages";
        parameters.m_propertyFileExists = false;
    }
    // add source
    editableSupport.addSource(editableSource,
            new SourceDescription(DirectSource.class, DirectSourceNewComposite.class), parameters);
    // do externalize
    StringPropertyInfo propertyInfo = editableSupport.getProperties(frame).get(0);
    editableSupport.externalizeProperty(propertyInfo, editableSource, true);
    // apply commands
    support.applyEditable(editableSupport);
    // checks
    assertEditor("import java.util.ResourceBundle;", "public class Test extends JFrame {", "  public Test() {",
            "    setTitle(ResourceBundle.getBundle('test.messages').getString('Test.this.title')); //$NON-NLS-1$ //$NON-NLS-2$",
            "  }", "}");
    {
        String newProperties = getFileContentSrc("test/messages.properties");
        assertTrue(newProperties.contains("#Direct ResourceBundle"));
        assertTrue(newProperties.contains("Test.this.title=My JFrame"));
    }
}

From source file:org.eclipse.wb.tests.designer.core.nls.SourceEclipseModernTest.java

License:Open Source License

public void test_create() throws Exception {
    ContainerInfo frame = parseContainer("public class Test extends JFrame {", "  public Test() {",
            "    setTitle('My JFrame');", "  }", "}");
    NlsSupport support = NlsSupport.get(frame);
    IEditableSupport editableSupport = support.getEditable();
    // prepare editable source
    IEditableSource editableSource = NlsTestUtils.createEmptyEditable("test.messages");
    editableSource.setKeyGeneratorStrategy(ModernEclipseSource.MODERN_KEY_GENERATOR);
    // prepare parameters
    SourceParameters parameters = new SourceParameters();
    IJavaProject javaProject = m_lastEditor.getJavaProject();
    {/*from  www .jav  a 2  s.  c  o m*/
        parameters.m_accessorSourceFolder = javaProject.findPackageFragmentRoot(new Path("/TestProject/src"));
        parameters.m_accessorPackage = javaProject.findPackageFragment(new Path("/TestProject/src/test"));
        parameters.m_accessorPackageName = parameters.m_accessorPackage.getElementName();
        parameters.m_accessorClassName = "Messages";
        parameters.m_accessorFullClassName = "test.Messages";
        parameters.m_accessorExists = false;
    }
    {
        parameters.m_propertySourceFolder = parameters.m_accessorSourceFolder;
        parameters.m_propertyPackage = parameters.m_accessorPackage;
        parameters.m_propertyFileName = "messages.properties";
        parameters.m_propertyBundleName = "test.messages";
        parameters.m_propertyFileExists = false;
    }
    // add source
    editableSupport.addSource(editableSource,
            new SourceDescription(ModernEclipseSource.class, ModernEclipseSourceNewComposite.class),
            parameters);
    // do externalize
    StringPropertyInfo propertyInfo = editableSupport.getProperties(frame).get(0);
    editableSupport.externalizeProperty(propertyInfo, editableSource, true);
    // apply commands
    support.applyEditable(editableSupport);
    // checks
    assertEditor("public class Test extends JFrame {", "  public Test() {",
            "    setTitle(Messages.Test_this_title);", "  }", "}");
    {
        String messages = StringUtils.replace(getFileContentSrc("test/Messages.java"), "\r\n", "\n");
        assertEquals(getSourceDQ("package test;", "", "import org.eclipse.osgi.util.NLS;", "",
                "public class Messages extends NLS {",
                "  private static final String BUNDLE_NAME = 'test.messages'; //$NON-NLS-1$",
                "  public static String Test_this_title;",
                "  ////////////////////////////////////////////////////////////////////////////", "  //",
                "  // Constructor", "  //",
                "  ////////////////////////////////////////////////////////////////////////////",
                "  private Messages() {", "    // do not instantiate", "  }",
                "  ////////////////////////////////////////////////////////////////////////////", "  //",
                "  // Class initialization", "  //",
                "  ////////////////////////////////////////////////////////////////////////////", "  static {",
                "    // load message values from bundle file",
                "    NLS.initializeMessages(BUNDLE_NAME, Messages.class);", "  }", "}"), messages);
    }
    {
        String newProperties = getFileContentSrc("test/messages.properties");
        assertTrue(newProperties.contains("#Eclipse modern messages class"));
        assertTrue(newProperties.contains("Test_this_title=My JFrame"));
    }
}

From source file:org.eclipse.wb.tests.designer.core.nls.SourceEclipseOldTest.java

License:Open Source License

/**
 * Use constructor without accessor, only to create {@link IEditableSource} using existing
 * *.properties./*from w  ww. j a v a  2  s .  c o  m*/
 */
public void test_constructorWithoutAccessor() throws Exception {
    setFileContentSrc("test/messages.properties", getSourceDQ("frame.title=My JFrame"));
    waitForAutoBuild();
    //
    ContainerInfo frame = parseContainer("// filler filler filler", "public class Test extends JFrame {",
            "  public Test() {", "  }", "}");
    NlsSupport support = NlsSupport.get(frame);
    // prepare editable source
    IEditableSource editableSource;
    {
        EclipseSource source = new EclipseSource(frame, null, "test.messages");
        editableSource = source.getEditable();
        assertEquals("My JFrame", editableSource.getValue(LocaleInfo.DEFAULT, "frame.title"));
    }
    // prepare parameters
    SourceParameters parameters = new SourceParameters();
    IJavaProject javaProject = m_lastEditor.getJavaProject();
    {
        parameters.m_accessorSourceFolder = javaProject.findPackageFragmentRoot(new Path("/TestProject/src"));
        parameters.m_accessorPackage = javaProject.findPackageFragment(new Path("/TestProject/src/test"));
        parameters.m_accessorPackageName = parameters.m_accessorPackage.getElementName();
        parameters.m_accessorClassName = "Messages";
        parameters.m_accessorFullClassName = "test.Messages";
        parameters.m_accessorExists = false;
    }
    {
        parameters.m_propertySourceFolder = parameters.m_accessorSourceFolder;
        parameters.m_propertyPackage = parameters.m_accessorPackage;
        parameters.m_propertyFileName = "messages.properties";
        parameters.m_propertyBundleName = "test.messages";
        parameters.m_propertyFileExists = false;
    }
    // add source
    IEditableSupport editableSupport = support.getEditable();
    editableSupport.addSource(editableSource, NlsSupport.getSourceDescriptions(frame)[0], parameters);
    // apply commands
    support.applyEditable(editableSupport);
    // checks
    assertTrue(getFileSrc("/test/Messages.java").exists());
    {
        String newProperties = getFileContentSrc("test/messages.properties");
        // no comment expected because existing file should be used
        assertFalse(newProperties.contains("#Eclipse messages class"));
        // also no change
        assertTrue(newProperties.contains("frame.title=My JFrame"));
    }
}

From source file:org.eclipse.wb.tests.designer.core.nls.SourceEclipseOldTest.java

License:Open Source License

public void test_addSource() throws Exception {
    ContainerInfo frame = parseContainer("public class Test extends JFrame {", "  public Test() {",
            "    setTitle('My JFrame');", "  }", "}");
    NlsSupport support = NlsSupport.get(frame);
    ///*from  w w  w . ja  v a2  s .  c  o  m*/
    EditableSupport editableSupport = (EditableSupport) support.getEditable();
    // addSource()
    IEditableSource editableSource;
    {
        editableSource = NlsTestUtils.createEmptyEditable("messages");
        SourceDescription sourceDescription = NlsSupport.getSourceDescriptions(frame)[0];
        assertSame(EclipseSource.class, sourceDescription.getSourceClass());
        // prepare parameters
        SourceParameters parameters = new SourceParameters();
        IJavaProject javaProject = m_lastEditor.getJavaProject();
        {
            parameters.m_accessorSourceFolder = javaProject
                    .findPackageFragmentRoot(new Path("/TestProject/src"));
            parameters.m_accessorPackage = javaProject.findPackageFragment(new Path("/TestProject/src/test"));
            parameters.m_accessorPackageName = parameters.m_accessorPackage.getElementName();
            parameters.m_accessorClassName = "Messages";
            parameters.m_accessorFullClassName = "test.Messages";
            parameters.m_accessorExists = false;
        }
        {
            parameters.m_propertySourceFolder = parameters.m_accessorSourceFolder;
            parameters.m_propertyPackage = parameters.m_accessorPackage;
            parameters.m_propertyFileName = "messages.properties";
            parameters.m_propertyBundleName = "test.messages";
            parameters.m_propertyFileExists = false;
        }
        parameters.m_withDefaultValue = false;
        // do add
        editableSupport.addSource(editableSource, sourceDescription, parameters);
    }
    // apply commands
    support.applyEditable(editableSupport);
    assertEquals(
            getSourceDQ("package test;", "", "import java.beans.Beans;",
                    "import java.util.MissingResourceException;", "import java.util.ResourceBundle;", "",
                    "public class Messages {",
                    "  ////////////////////////////////////////////////////////////////////////////", "  //",
                    "  // Constructor", "  //",
                    "  ////////////////////////////////////////////////////////////////////////////",
                    "  private Messages() {", "    // do not instantiate", "  }",
                    "  ////////////////////////////////////////////////////////////////////////////", "  //",
                    "  // Bundle access", "  //",
                    "  ////////////////////////////////////////////////////////////////////////////",
                    "  private static final String BUNDLE_NAME = 'test.messages'; //$NON-NLS-1$",
                    "  private static final ResourceBundle RESOURCE_BUNDLE = loadBundle();",
                    "  private static ResourceBundle loadBundle() {",
                    "    return ResourceBundle.getBundle(BUNDLE_NAME);", "  }",
                    "  ////////////////////////////////////////////////////////////////////////////", "  //",
                    "  // Strings access", "  //",
                    "  ////////////////////////////////////////////////////////////////////////////",
                    "  public static String getString(String key) {", "    try {",
                    "      ResourceBundle bundle = Beans.isDesignTime() ? loadBundle() : RESOURCE_BUNDLE;",
                    "      return bundle.getString(key);", "    } catch (MissingResourceException e) {",
                    "      return '!' + key + '!';", "    }", "  }", "}"),
            StringUtils.replace(getFileContentSrc("test/Messages.java"), "\r\n", "\n"));
    assertTrue(getFileSrc("test/messages.properties").exists());
}

From source file:org.eclipse.wb.tests.designer.core.nls.SourceFieldTest.java

License:Open Source License

public void test_create() throws Exception {
    ContainerInfo frame = parseContainer("public class Test extends JFrame {", "  public Test() {",
            "    setTitle('My JFrame');", "  }", "}");
    NlsSupport support = NlsSupport.get(frame);
    IEditableSupport editableSupport = support.getEditable();
    // prepare editable source
    IEditableSource editableSource = NlsTestUtils.createEmptyEditable("test.messages");
    // prepare parameters
    SourceParameters parameters = new SourceParameters();
    IJavaProject javaProject = m_lastEditor.getJavaProject();
    {/*from w  ww.j a  va2s.  c  o m*/
        parameters.m_propertySourceFolder = javaProject.findPackageFragmentRoot(new Path("/TestProject/src"));
        parameters.m_propertyPackage = javaProject.findPackageFragment(new Path("/TestProject/src/test"));
        parameters.m_propertyFileName = "messages.properties";
        parameters.m_propertyBundleName = "test.messages";
        parameters.m_propertyFileExists = false;
        //
        parameters.m_fieldName = "m_bundle";
    }
    // add source
    editableSupport.addSource(editableSource,
            new SourceDescription(FieldSource.class, FieldSourceNewComposite.class), parameters);
    // do externalize
    StringPropertyInfo propertyInfo = editableSupport.getProperties(frame).get(0);
    editableSupport.externalizeProperty(propertyInfo, editableSource, true);
    // apply commands
    support.applyEditable(editableSupport);
    // checks
    assertEditor("import java.util.ResourceBundle;", "public class Test extends JFrame {",
            "  private static final ResourceBundle m_bundle = ResourceBundle.getBundle('test.messages'); //$NON-NLS-1$",
            "  public Test() {", "    setTitle(m_bundle.getString('Test.this.title')); //$NON-NLS-1$", "  }",
            "}");
    {
        String newProperties = getFileContentSrc("test/messages.properties");
        assertTrue(newProperties.contains("#Field ResourceBundle: m_bundle"));
        assertTrue(newProperties.contains("Test.this.title=My JFrame"));
    }
}