Why I am able to re-create java.lang package and classes? - package

I am just playing with package structure. And to my surprise I can bypass the default classes by creating my package and class name with that name.
For ex:
I created a package called java.lang and Class is Boolean. When I import java.lang.Boolean it's not the JDK's version of Boolean. It's mine. It's just showing the methods of Objects which every object java have.
Why so ? Why I am allowed to create the package java.lang? And the program runs fine.
Another baffle is if I create a Class with name Object and try to runs the program then an exception
java.lang.SecurityException: Prohibited package name: java.lang
at java.lang.ClassLoader.preDefineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
Why is this behaviour ? is this a bug or normal behaviour ?

The restriction on java.lang classes is a runtime restriction, not a compile time one.
The JVM actually specifically provides a mechanism for overriding classes in java.lang. You can do it using the -Xbootclasspath command line flag:
-Xbootclasspath:bootclasspath
Specifies a semicolon-separated list of directories, JAR files, and ZIP archives to search for boot class files. These are used in place of the boot class files included in the Java platform JDK.
Applications that use this option for the purpose of overriding a class in rt.jar should not be deployed because doing so would contravene the Java Runtime Environment binary code license.
-Xbootclasspath/a:path
Specifies a semicolon-separated path of directories, JAR files, and ZIP archives to append to the default bootstrap class path.
-Xbootclasspath/p:path
Specifies a semicolon-separated path of directories, JAR files, and ZIP archives to add in front of the default bootstrap class path.
Do not deploy applications that use this option to override a class in rt.jar because this violates the Java Runtime Environment binary code license.
However, as I've already emphasized with bold marks, doing so is a violation of the Oracle Binary Code License Agreement for Java SE and JavaFX Technologies:
D. JAVA TECHNOLOGY RESTRICTIONS. You may not create, modify, or change the behavior of, or authorize your licensees to create, modify, or change the behavior of, classes, interfaces, or subpackages that are in any way identified as "java", "javax", "javafx", "sun", “oracle” or similar convention as specified by Oracle in any naming convention designation. You shall not redistribute the Software listed on Schedule 1.
Apart from the above, you may add whatever class you want to whatever packages you want; it's specifically discussed in the the JLS §13.3:
13.3. Evolution of Packages
A new top level class or interface type may be added to a package without breaking compatibility with pre-existing binaries, provided the new type does not reuse a name previously given to an unrelated type.
If a new type reuses a name previously given to an unrelated type, then a conflict may result, since binaries for both types could not be loaded by the same class loader.
Changes in top level class and interface types that are not public and that are not a superclass or superinterface, respectively, of a public type, affect only types within the package in which they are declared. Such types may be deleted or otherwise changed, even if incompatibilities are otherwise described here, provided that the affected binaries of that package are updated together.

Answer to SecurityException related question:
SecurityManger throws this RuntimeException while your classloader calling defineClass method and encountered specified class(your "custom class") name has "java.*" in it.
This is because you defined your class in "java.*" package and as per ClassLoader's documentation this is not allowed.
defineClass( )
..
The specified name cannot begin with "java.", since all classes in the "java.* packages can only be defined by the bootstrap class loader. If name is not null, it must be equal to the binary name of the class specified by the byte array "b", otherwise a NoClassDefFoundError will be thrown.
Throws:
..
SecurityException - If an attempt is made to add this class to a package that contains classes that were signed by a different set of certificates than this class, or if name begins with "java.".
For your testing, try creating java.test package and define one Custom class (names doesn't matter; like Object..). In this case as well you will get same SecurityException.
package java.test;
public class Test {
public static void main(String[] args) {
System.out.println("This is Test");
}
}

This is not Bug.
Behaviour beacause of:
When the Java Virtual Machine (JVM) tries to load our class, it recognizes its package name as invalid and thus, a SecurityException is thrown.
The SecurityException indicates that a security violation has occurred an thus, the application cannot be executed.
public class SecurityException
extends RuntimeException
Thrown by the security manager to indicate a security violation.
please use different package name it not for only language package of java.it covers all package not gives permissions to override in build classes and packages of java.
By Changing this we can create or override same package and class:
a/j2ee.core.utilities/src/org/netbeans/modules/j2ee/core/api/support/java/JavaIdentifiers.java
b/j2ee.core.utilities/src/org/netbeans/modules/j2ee/core/api/support/java/JavaIdentifiers.java
**if (packageName.startsWith(".") || packageName.endsWith(".")) {// NOI18N
return false;
}
if(packageName.equals("java") || packageName.startsWith("java.")) {//NOI18N
return false;
}**
String[] tokens = packageName.split("\\."); //NOI18N
if (tokens.length == 0) {
return Utilities.isJavaIdentifier(packageName);
a/j2ee.core.utilities/test/unit/src/org/netbeans/modules/j2ee/core/api/support/java/JavaIdentifiersTest.java b/j2ee.core.utilities/test/unit/src/org/netbeans/modules/j2ee/core/api/support/java/JavaIdentifiersTest.java
assertFalse(JavaIdentifiers.isValidPackageName(" "));
assertFalse(JavaIdentifiers.isValidPackageName("public"));
assertFalse(JavaIdentifiers.isValidPackageName("int"));
assertFalse(JavaIdentifiers.isValidPackageName("java"));
assertFalse(JavaIdentifiers.isValidPackageName("java.something"));
}

Your problem with java.lang.Boolean as your Boolean Class, and not the Object one is simple to explain.
The Object class is the root of every other classes you can find, use, or even create. Which means that if you could have the ability to override it, not a single class, method, or whatever you want to use would work, since every of them depends on that root class.
For the Boolean Class, it is not a boolean type, but a class for a boolean type. And since nothing depends on it, it is then possible to override it.
A better way to understand this problem, is to look at this link: [http://docs.oracle.com/javase/7/docs/api/overview-tree.html] You will notice that every kind of package, containing every kind of java classes, depends on the Object Class.
So the security exception you encountered is like a "life savior" for your program.
If I'm wrong about your question, other persons may find a more appropriate answer to it. :)

Related

.Net 6 WinForms - Unable to get configuration section value

I have a .Net 6 WinForms application and am trying to access some sections in the App.config (myapp.dll.config after build).
I have a class defined with the properties MyProp { public String runDate {get;set;} and app looking for a section called in the file.
I have used ConfigurationBuild().SetBasePath(AppContext.BasePath().AddXMLFile("myapp.dll.config").Build() returning an IConfiguration object called config.
The issue is that when I call either config.GetSection("MyProp").Bind(props) or config.GetSection("MyProp").Get(); It returns the entity but with the value null.
Note: if I change the settings section to bob then both values work. However, my config section is in the old web.config format and uses key/value pairs.
I recognize that when using an XML Provider, the key and value become attributes of the XElement, so its [the xelement] will have a value set to nothing. I was wondering if AddXmlFile was the correct provider to use for this?

UITestControlNotAvailableException is received when TC is included in Ordered Test

I use SpecFlow with Coded UI to create some automated functional tests for a WPF application. Test case execution is performed using MsTest and Visual Studio Premium 2012.
I have a lot of test cases. If I execute them one by one everything is OK. If I put them all in an ordered test I receive the following error:
Microsoft.VisualStudio.TestTools.UITest.Extension.UITestControlNotAvailableException: The following element is no longer available: Name [], ControlType [Custom], AutomationId [reags:LoadView_1], RuntimeId [7,1620,64780193] ---> System.Windows.Automation.ElementNotAvailableException: The following element is no longer available: Name [], ControlType [Window], AutomationId [UnitializedCB3702D1-14B6-4001-8BC7-CD4C22C18BE1], RuntimeId [42,1770052]
at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaUtility.MapAndThrowException(SystemException e, IUITechnologyElement element)
at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaElement.get_AutomationId()
at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaElement.HasValidAutomationId()
at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaElement.get_FriendlyName()
at Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMapUtil.FillPropertyFromUIElement(UIObject obj, IUITechnologyElement element)
at Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMapUtil.FillPropertyOfTopLevelElementFromUIElement(UIObject obj, IUITechnologyElement element)
at Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMapUtil.FillTopLevelElementFromUIElement(IUITechnologyElement element, TopLevelElement obj, Boolean stripBrowserWindowTitleSuffix)
at Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMapUtil.GetCompleteQueryId(UITechnologyElement pluginNode)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetQueryIdForCaching()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.<>c__DisplayClass6.<CacheQueryId>b__5()
at Microsoft.VisualStudio.TestTools.UITesting.CodedUITestMethodInvoker.InvokeMethod[T](Func`1 function, UITestControl control, Boolean firePlaybackErrorEvent, Boolean logAsAction)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.CacheQueryId(String queryId)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl..ctor(IUITechnologyElement element, UITestControl searchContainer, String queryIdForRefetch)
at Microsoft.VisualStudio.TestTools.UITesting.TechnologyElementPropertyProvider.GetPropertyValue(UITestControl uiControl, String propertyName)
at Microsoft.VisualStudio.TestTools.UITesting.UITestPropertyProvider.TryGetPropertyFromTechnologyElement(UITestControl uiControl, String propertyName, Object& value)
at Microsoft.VisualStudio.TestTools.UITesting.PropertyProviderBase.GetPropertyValue(UITestControl uiControl, String propertyName)
at Microsoft.VisualStudio.TestTools.UITesting.UITestPropertyProvider.GetPropertyValueWrapper(UITestControl uiControl, String propertyName)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetPropertyValuePrivate(String propertyName)
The first couple of errors were fixed using this hint, but I have some auto-generated steps and in order to re-search the controls I have to move the code and... a lot of unnecessary and annoying work.
Could you suggest some another solution to fix this? Is there some trick with the ordered tests? Or some nice clean-up methods for problems like this?
Thanks!
Here's what I did with a recent project.
First I created some CodedUI test methods as if SpecFlow didn't exist so I could keep those layers separate. Then I created step definition classes in C# that delegate to the coded UI test methods I created.
In a before scenario hook I created my UIMap instances (the classes generated by the CodedUI test generator) so each scenario had a fresh instance of my UIMap classes. You need this because object references in these classes are cached. Each new screen in your app is a whole new object tree that CodedUI must traverse.
Many times my step definitions just dive right into the CodedUI API to create custom searches, and I used the auto generated methods in my UIMap classes as a point of reference.
A little elaboration on how I set up my test project.
About My Test Project
I created a new "Test" project in Visual Studio 2010, which references the following libraries:
Microsoft (probably comes with default Test project template)
Microsoft.VisualStudio.QualityTools.CodedUITestFramework
Microsoft.VisualStudio.QualityTools.UnitTestFramework
Microsoft.VisualStudio.TestTools.UITest.Common
Microsoft.VisualStudio.TestTools.UITest.Extension
Microsoft.VisualStudio.TestTools.UITesting
UIAutomationTypes
NuGet Packages
AutoMapper
AutoMapper.Net4
SpecFlow.Assist.Dynamic
TechTalk.SpecFlow
Test Project Structure
This was my first stab at CodedUI Tests. I came from a Ruby on Rails background, and did a fair amount of reading online about implementing CodedUI Tests and SpecFlow tests. It's not a perfect setup, but it seems to be pretty maintainable for us.
Tests (Test project)
Features/
Bar.feature
Foo.feature
Regression/
Screen1/
TestsA.feature
TestsB.feature
StepDefinitions/
CommonHooks.cs
DataAssertionSteps.cs
DataSteps.cs
FormSteps.cs
GeneralSteps.cs
PresentationAssertionSteps.cs
Screen1Steps.cs
Screen2Steps.cs
UI/
FormMaps/
Screen1FormMap.cs
Screen2FormMap.cs
UIMapLoader/
User.cs
UIMap.uitest (created by CodedUI test framework)
Models (C# Class Library Project)
Entities/
Blog.cs
Comment.cs
Post.cs
Repositories/
BlogRepository.cs
CommentRepository.cs
PostRepository.cs
ViewModels/
Screen1ViewModel.cs
Screen2ViewModel.cs
Tests/Features
This folder contains all the SpecFlow feature files implementing the basic business rules, or acceptance tests. Simple screens got their own feature file, whereas screens with more complex business logic were broken into multiple feature files. I tried to keep these features friendly to read for both Business and Developers.
Tests/Regression
Because our Web Application was not architected in a manor allowing unit testing, all of our testing must be done through the UI. The Tests/Regressions folder contains all the SpecFlow feature files for our full regression of the application. This includes the really granular tests, like typing too many characters into form fields, etc. These features weren't really meant as business documenation. They are only meant to prevent us from being woken up at 3 a.m. because of production problems. Why do these problems always happen at 3 a.m.? ...
Tests/StepDefinitions
The Test/StepDefinitions folder contains all the SpecFlow Step Definition files. I broke these files down first into common steps, and then steps pertaining to a particular screen in my application.
CommonHooks.cs -- Created by SpecFlow
[Binding]
public class CommonHooks
{
[BeforeTestRun]
public static void BeforeTestRun()
{
...
}
[BeforeScenario]
public void BeforeScenario()
{
User.General.OpenLauncher();
}
[AfterScenario]
public void AfterScenario()
{
User.General.CloseBrowser();
User.General = null;
}
}
The BeforeScenario and AfterScenario methods are where I create and/or destroy instances of the CodedUI UIMap classes (More on that further down)
DataAssertionSteps.cs -- Step definitions asserting that data shows up, or doesn't show up in the database. These are all Then ... step definitions.
Scenario: Foo
Then a Foo should exist
In DataAssertionSteps.cs:
[Then(#"a Foo should exist")]
public void ThenAFooShouldExist()
{
// query the database for a record
// assert the record exists
}
DataSteps.cs -- Steps to seed the database with data, or remove data. These are all Given ... step definitions used to set up a scenario.
FormSteps.cs -- Step definitions for interacting with forms. These all tend to be When I ... steps
GeneralSteps.cs -- Realy generic step definitions. Things like When I click the "Foo" link go here.
PresentationAssertionSteps.cs -- Generic steps asserting that the UI is behaving properly. Things like Then I should see the text "Foo" go here.
Screen1Steps.cs -- When I needed steps for a particular screen, I created a step definition file for that screen. For example, if I needed steps for the "Blog Post" screen, then I created a file call BlogPostSteps.cs, which contained all those step definitions.
Tests/UI
The Tests/UI folder contains a bunch of custom written C# classes that we used to map label text found in our *.feature files to the names of form controls. You might not need this layer, but we did. This makes it easier to refactor your test project if form control names change, and especially for Web Projects because the HTML form field names change based on the <asp /> containers in our ascx files.
Example class:
namespace Tests.UI.FormMaps.Screen1FormMap
{
public static IDictionary<string, string> Fields = new Dictionary<string, string>()
{
{ "First Name", "UserControlA_PanelB_txtFirstName" },
{ ... },
...
};
}
Example Step:
When I enter "Joe" in the "First Name" textbox in the "Screen 1" form
Example Step Definition:
[When(#"I enter ""(.*)"" in the ""(.*)"" textbox in the ""(.*)"" form")]
public void WhenIEnterInTheTextboxInTheForm(string text, string labelText, string formName)
{
if (formName == "Screen 1")
{
// form control name: Screen1FormMap.Fields[labelText]
}
...
}
The step definition then used the Tests.UI.FormMaps.Screen1FormMap.Fields property to retrieve the form control name based on the label text in the *.feature files.
Tests.UI.FormMaps.Screen1FormMap.Fields["First Name"]
Tests/UI/UIMapLoader/User.cs
The other thing inside this folder is the UI/UIMapLoader/User.cs file. This class is a custom written class providing easy access to all the UIMap classes generated by the CodedUI Test framework.
namespace Tests.UI.UIMapLoader
{
public static class User
{
private static UIMap _general;
public static UIMap General
{
get { return _general ?? (_general = new UIMap()); }
set { _general = value; }
}
}
}
That way the Step Definition classes can easily access the UI maps via:
User.General.SomeCodedUITestRecordedMethod(...);
You saw a reference to this class in the BeforeScenario and AfterScenario methods in the CommonHooks.cs file referenced above.
Models Project
This is just a class lib to encompass the entities and repositories allowing the test project to access the database. Nothing special here except the ViewModels directory. Some of the screens have complex relationships with data in the database, so I created a ViewModel class to allow my SpecFlow step definitions to easily seed the database with data for these screens.

The class "The class "com.google.appengine.api.datastore.Key" is not persistable

I am trying to delete multiple entities given a List of Keys, I.e.:
List keys = obj.getKeys(); pm.deletePersistentAll(keys);
However, when I try to delete the entities I get the following exception:
javax.jdo.JDOUserException: One or more instances could not be deleted
at org.datanucleus.jdo.JDOPersistenceManager.deletePersistentAll(JDOPersistenceManager.java:809)
at org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager.access$301(DatastoreJDOPersistenceManager.java:39)
at org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager$2.call(DatastoreJDOPersistenceManager.java:112)
at org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager$2.call(DatastoreJDOPersistenceManager.java:110)
at org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager$BatchManagerWrapper.call(DatastoreJDOPersistenceManager.java:125)
at org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager$BatchManagerWrapper.access$200(DatastoreJDOPersistenceManager.java:121)
at org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager.deletePersistentAll(DatastoreJDOPersistenceManager.java:110)
NestedThrowablesStackTrace: org.datanucleus.jdo.exceptions.ClassNotPersistenceCapableException: The class "The class "com.google.appengine.api.datastore.Key" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found." is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data for the class is not found.
at org.datanucleus.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:241)
Has anyone experienced this before? I've made sure my classes are enhanced and that all Class's have been marked as PersistenceCapable.
Thanks
You can only delete a persistent object (what you pass in to pm.deletePersistentAll). A "Key" is not a persistent object
To delete an entity by key, try
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
ds.delete(key)

Error Application cast in WPF

i have 2 projects in my solution (main is A.WPF and secondary is B.WPF)
when i'm trying to access variables inside my App.xaml.cs in B.WPF:
filename = ((App)Application.Current).ErrorLogFileName;
i get the following error:
Unable to cast object of type 'A.App' to type 'B.App'.
i also tried the following:
filename = ((B.App)Application.Current).ErrorLogFileName;
but still the same error...
the definition in B.App is:
private string _errorLogFileName = "error log.xml";
public string ErrorLogFileName
{
get { return _errorLogFileName; }
}
please assist...
Looks like you need to do:
filename = ((A.App)Application.Current).ErrorLogFileName;
The error is saying the type is A.App, yet in both cases you are trying to cast to B.App.
There can only be one current application also.
Application.Current refers to the current application. The only way to be allowed to cast the current App to another App-type is when the other App-type is a base class of the current App-type.
Are A.App and B.App siblings or is B.App a base class of A.App?
If you don't want B to have a reference to A (or can't as you want A to reference B and that would cause a circular reference), then you need a common type defined in a third assembly that both A and B reference. In our implementation we tend to have a ConfigurationData type that is in a separate project referenced by both Wpf projects, e.g.
public static class ConfigurationData
{
private static string _errorLogFileName = "error log.xml";
public string ErrorLogFileName
{
get { return _errorLogFileName; }
}
}
Another approach would be to define an Interface for your ErrorLogFileName property in a 3rd assembly that both A and B reference, and then implement that interface on your Wpf Application class - A and B would then both be able to cast to that type. If you wanted your A project to set the values on that at runtime, you could make the ErrorLogFileName a read-write property instead and initialize it in your application startup.
I personally prefer using a separate ConfigurationData type from the Wpf app object for this kind of stuff (ErrorLogFileName etc.) as it can then also be used for code that might execute in a unit test and therefore might not be running under a Wpf application - it also avoids having to do casts all over the place (ConfigurationData.ErrorLogFileName instead of ((IAppConfigurationData)Application.Current).ErrorLogFileName.
BTW, if you have an Application object in both assemblies it sounds like you might have both assemblies configured to build as Output type: Windows Application in your project properties. You should only really have one assembly that is configured as the Windows Application and the rest should be Class Library to avoid confusing numbers of Application classes being generated - only the one in the main EXE (and it's related resources) will get created at runtime.

Silverlight 2 ArgumentException

I have a silverlight 2 app that has an ObservableCollection of a class from a separate assem/lib. When I set my ListBox.ItemsSource on that collection, and run it, I get the error code:
4004 "System.ArgumentException: Value does not fall within the expected range."
Here is part of the code:
public partial class Page : UserControl
{
ObservableCollection<Some.Lib.Owner> ooc;
public Page()
{
ooc = new ObservableCollection<Some.Lib.Owner>();
Some.Lib.Owner o1 = new Some.Lib.Owner() { FirstName = "test1" };
Some.Lib.Owner o2 = new Some.Lib.Owner() { FirstName = "test2" };
Some.Lib.Owner o3 = new Some.Lib.Owner() { FirstName = "test3" };
ooc.Add(o1);
ooc.Add(o2);
ooc.Add(o3);
InitializeComponent();
lb1.ItemsSource = ooc;
}
}
But when I create the Owner class within this same project, everything works fine.
Is there some security things going on behind the scenes? Also, I'm using the generate a html page option and not the aspx option, when I created this Silverlight 2 app.
Are you trying to use a standard class library or a "Silverlight Class Library"?
Because Silverlight 2 uses a subset of the CLR it cannot access standard class libraries that were compiled using the full CLR. To use an external assembly you must create it as a "Silverlight Class Library". This will create a project that only includes the namespaces available to Silverlight and will allow you to reference the assembly within your Silverlight project.
Check out the MSDN article ".NET Framework Class Library for Silverlight" for more info.
It may be because you're not handling a failure in SubmittedChanges(). See http://www.scottleckie.com/2010/04/code-4004-unhandled-error-in-silverlight-application/ for more info
Everything is in one project now.
Yes, but not like you just did it, instead, share, link to the file(s).
For this an old jedi mind trick of Silverlight when there is a need to share common entity code between the app and the service. This is done when the library could not be brought in due to the differences in .Net/CLR.
The trick is to include the file as a link into the other project. Here is how
In the target (Silverlight project) folder which needs the code file, right click and select Add then Existing Item... or shift alt A.
Browse to the location of the origins file(s) found and select the/those file(s).
Once the item(s) have been selected, then on the Add button select the drop down arrow.
Select Add as link to add the file(s) as a link into the folder.
Once done, there is only one copy, but built in two different places.
That will give access to the file as if the file was actually within the project's folder, but the file physically resides elsewhere...and avoids CLR issues.

Resources