ResourceBundle MissingResourceException Linux Specific Key - linux

I have been having this issue in iterating through an array of keys and calling the getString() method on the resource bundle. I have all the mappings I need in my bundle and for some reason one of the resource will not be fetched. This is only an issue in Linux Ubunthu 9. It works in Windows. It finds all the resources up until my "item" resource which is mapped correctly. As stated above I use the same jar on bot os's. All my resources work except this single key. I have tried changing the key and this resource, but it keeps throwing the MissingResourceException. My classpath is correct otherwise my other keys would not function. I have no idea what could be causing this. I have also tried reordering my bundle - no luck.
Any input would be appreciated.
String cols = new String[] {"name", "actor" , "requestor", "electronicFolder", "item", "dueOn", "finalOccurrenceOn"};
ResourceBundle rb = ResourceBundle.getBundle("application");
for (int i=0; i<cols.length; i++) {
if (rb==null) {
out.print("null");
} else {
try {
out.print(" " + rb.getString(cols[i]) + " : ");
} catch (MissingResourceException ee) {
ee.printStackTrace();
}
}
}
As stated above works perfectly in Windows, fails on item in Linnux Ubunthu. This is really an annoyance.

I found that this was working in my dev env, but not as a packaged EAR. The problem was that the included jsp utilized a bean tag. I removed this reference and utilize our custom tag similar to the bean tag and it worked.

Related

get attributes, even if they do not exist

Please don't hate me, yes I want to do something really stupid.
I want to get null on every attribute if it does not exist. I found out that I can create the propertyMissing method:
class User {
String name = "A"
}
Object.metaClass.propertyMissing() {
null
}
u = new User();
println u?.name
println u?.namee
This prints:
A
null
Now I have the "great" Hybris system in my back :D
If I add the propertyMissing part on top of my script and run this in the Hybris groovy console, I still get the MissingPropertyException.
Is there another way to avoid the MissingPropertyException exception without having to work with hundreds of try catch? (or hundreds of println u?.namee ? u.namee : null isn't working)
/Edit: 1
I have the following use case (for the Hybris system):
I want to get all necessary information in a dynamic output from some pages. Why dynamic? Some page components have the attribute headline other teaserHeadline and some other title. To avoid to create each time an try catch or if else, I created a function which loops through possible attributes and if it's null it skips that one. For that I need to return null on attributes which doesn't exist.
Here is an example which should work, but it doesn't (don't run it on your live system):
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.SearchResult;
flexibleSearch = spring.getBean("flexibleSearchService")
FlexibleSearchQuery query = new FlexibleSearchQuery("select {pk} from {ContentPage}");
SearchResult searchResult = flexibleSearch.search(query);
def i = 0;
def max = 1;
searchResult.result.each { page ->
if (i < max) {
gatherCMSPageInformation(page)
}
i++;
}
def gatherCMSPageInformation(page) {
page.class.metaClass.propertyMissing() {
null
}
println page.title2
}
Weird thing is, that if I run it a few times in a small interval, it starts to work. But I can't overwrite "null" to something else like "a". Also I noticed, to overwrite the Object class isn't working at all in Hybris.
/Edit 2:
I noticed, that I'm fighting against the groovy cache. Just try the first example, change null with a and then try to change it again to b in the same context, without restarting the system.
Is there a way to clear the cache?
why don't you use the groovy elvis operator?
println u?.namee ?: null

Catel Auto Register Attributes with multiple instances

we are developing a GUI Plug-In Framework using Catel.MVVM.
Single Plugins should be loaded dynamically using the "ServiceLocatorRegistration" Attribute.
Example:
[ServiceLocatorRegistration(typeof(IInitializable), ServiceLocatorRegistrationMode.SingletonInstantiateWhenRequired, "SamplePlugin")]
In our bootstrapper we load all Plugin assemblies into the default AppDomain:
Catel.Windows.Controls.MVVMProviders.Logic.UserControlLogic.DefaultSkipSearchingForInfoBarMessageControlValue = true;
Catel.Windows.Controls.MVVMProviders.Logic.UserControlLogic.DefaultCreateWarningAndErrorValidatorForViewModelValue = false;
IoCConfiguration.DefaultServiceLocator.AutoRegisterTypesViaAttributes = true;
IoCConfiguration.DefaultServiceLocator.CanResolveNonAbstractTypesWithoutRegistration = true;
foreach (
var file in
BaseDirectory.GetFiles("*.dll", SearchOption.AllDirectories)
.Where(f => IsNetAssembly(f.FullName))
.Where(f => !f.FullName.EndsWith("resources.dll"))
.AsParallel())
{
try
{
var asm = Assembly.ReflectionOnlyLoadFrom(file.FullName);
}
catch { }
}
Then we try to initialize them by calling
var initializables = ServiceLocator.Default.ResolveTypes();
foreach(var initializable in initializables)
initializable.Initialize();
But even if we have the plugin assemblies loaded in the AppDomain, we dont get all Classes with the ServiceLocatorRegistration attribute.
Is there any was to resolve all classes that have the example attribute set as above?
Thanks in advance!
The problem is probably because the assemblies containing the types that use the registration are not loaded into the AppDomain yet. There are a few things you can consider:
1) Use AppDomainExtensions.PreloadAssemblies
2) Use the type somehow (like Console.WriteLine(typeof(TypeFromAssembly).FullName))
I wouldn't recommend the second one because it goes against your plug-in architecture.
Resolved this issue myself. Mistake was probably the linevar asm = Assembly.ReflectionOnlyLoadFrom(file.FullName);
After replacing this line withAppDomain.CurrentDomain.LoadAssemblyIntoAppDomain(file.FullName); everything works as expected.
Thanks Geert for pointing to the right direction!

JDT SearchEngine throws a NullPointerException

I'm trying to use JDT SearchEngine to find references to a given object. But I'm getting a "NullPointerException" while invoking the "search" method of org.eclipse.jdt.core.search.SearchEngine.
Following is the error trace:
java.lang.NullPointerException at
org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:214)
at
org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:515)
at
org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:582)
And following is the method I'm using to perform search:
private static void search(String elementName) { //elementName -> a method Name
try {
SearchPattern pattern = SearchPattern.createPattern(elementName, IJavaSearchConstants.METHOD,
IJavaSearchConstants.REFERENCES, SearchPattern.R_PATTERN_MATCH);
IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
SearchRequestor requestor = new SearchRequestor() {
#Override
public void acceptSearchMatch(SearchMatch match) {
System.out.println("Element - " + match.getElement());
}
};
SearchEngine searchEngine = new SearchEngine();
SearchParticipant[] searchParticipants = new SearchParticipant[] { SearchEngine
.getDefaultSearchParticipant() };
searchEngine.search(pattern, searchParticipants, scope, requestor, null);
} catch (Exception e) {
e.printStackTrace();
}
}
Refer the "Variables" window of the following snapshot to check the values of the arguments passing to the "searchEngine.search()":
I think the the issue is because of the value of "scope" [Highlighted in 'BLACK' above].
Which means "SearchEngine.createWorkspaceScope()" doesn't return expected values in this case.
NOTE: Please note that this is a part of my program which runs as a stand-alone java program (not an eclipse plugin) using JDT APIs to parse a given source code (using JDT-AST).
Isn't it possible to use JDT SearchEngine in such case (non eclipse plugin program), or is this issue due to some other reason?
Really appreciate your answer on this.
No. You cannot use the search engine without openning a workspace. The reason is that the SearchEngine relies on the eclipse filesystem abstraction (IResource, IFile, IFolder, etc.). This is only available when the workspace is open.

TFS 2010 Building Sharepoint 2010 Solution With Custom Outputs

I have a very similar question to this SO post: TFS Build 2010 - Custom Binary Location and SharePoint WSP. There's no marked answer, but the only answer provided seemed to be the path to go.
I'm building several solutions and need the solutions and projects to be placed into their own folders. This lead to the build output change to the MSBuild call in the template that I'm using. I've been using this for sometime without any issues.
Recently a developer complained that the .wsp files were not being generated in our daily build. I looked into this and came across the fore mentioned SO post.
I followed the instructions and now have a new error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets (411): Method not found: 'Boolean Microsoft.VisualStudio.SharePoint.PathUtils.HasIllegalDeploymentPathCharacters(System.String)'.
I've looked at this line (411) in the targets file:
<PackageFiles LayoutPath="$(LayoutPath)%(EnumeratedFiles.Package)\" PackagePath="$(BasePackagePath)%(EnumeratedFiles.Package).$(PackageExtension)" />
The PackageFiles target is defined:
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="PackageFiles" />
I checked the GAC and didn't see it there so I added it. The TFS 2010 Build machine has Visual Studio 2010 and Sharepoint 2010 installed on it. I don't think I need to do anything other than changing this task:
<CreateSharePointProjectService Configuration="$(Configuration)"
Platform="$(Platform)"
ProjectFile="$(MSBuildProjectFile)"
ProjectReferences="#(SharePointProjectReference)"
OutDir="$(TargetDir)">
<Output PropertyName="ProjectService" TaskParameter="ProjectService" />
</CreateSharePointProjectService>
So that OutDir points to $(TargetDir).
Am I missing something as to why I'm getting this error where now a method cannot be found? This error is very exasperating as there is no information on the web regardless of the Google Fu employed!
Update
I've pulled apart the Microsoft.VisualStudio.SharePoint.dll that's on the build server. There is no PathUtils class or Namespace. Could I possibly have a bad version of this file? How can I detect this? Should I install the Sharepoint SDK on the build server. It already has Sharepoint 2010 installed on it.
Update 2
I checked the GAC. The Microsoft.VisualStudio.Sharepoint assembly shows up. However, I can only find it when I'm running the x64 version of the Visual Studio Command Prompt. When I run the normal one I get no assembly back. I'm assuming that is because the Sharepoint assembly is 64 bit. As far as I know TFS is setup to be 64bit. Is this going to be my problem?
The PathUtils.HasIllegalDeploymentPathCharacters method is present in version 10.0.40219.1 of Microsoft.VisualStudio.SharePoint.Designers.Models.dll and not in version 10.0.30319.1 (where I was seeing this error).
You are missing the assembly "Microsoft.VisualStudio.SharePoint.Designers.Models.dll"
The following assemblies must be copied to the GAC of the build system:
Microsoft.VisualStudio.SharePoint.Designers.Models.dll
Microsoft.VisualStudio.SharePoint.Designers.Models.Features.dll
Microsoft.VisualStudio.SharePoint.Designers.Models.Packages.dll
Microsoft.VisualStudio.SharePoint.dll
Please refer to the following article for more information about the required assemblies:
http://msdn.microsoft.com/en-us/ff622991.aspx
Regards,
Wes MacDonald
I found a solution to this issue. I don't think anyone has ever encountered this so I'm doubtful there will be a "correct" solution. I will post here what I have done to allow my .wsp files to build in the solution.
By all means, please post an answer (or comment on either this answer or the original question) if you think there is a better solution or if my manner of solving the problem is not up to par.
I will explain this in steps that I came up with to solve the problem.
First Step
The task PackageFiles was giving me the issue. This task was unable to find a method to invoke. Looking at the file C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets we can find this on line 56:
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="PackageFiles" />
I know knew where to look for the PackageFiles task/class.
Step Two
After knowing where to look I decompiled the task. I used Telerik's JustDecompile but I also came up with the same code in Reflector.
I could clearly see the line:
if (PathUtils.HasIllegalDeploymentPathCharacters(str2))
Which was erroring.
Step Three
I ended up deciding that the PathUtils.HasIllegalDeploymentPathCharacters method was just there as a safety check. I could recreate this task in my own custom library and then insert it into a custom targets file.
Here was the class I came up with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using Microsoft.VisualStudio.SharePoint.Tasks;
using Microsoft.Build.Framework;
namespace SharepointTaskLibrary
{
public class PackageFiles : BuildTask
{
[Required]
public ITaskItem LayoutPath
{
get;
set;
}
[Required]
public ITaskItem PackagePath
{
get;
set;
}
public PackageFiles()
{
}
protected override void OnCheckParameters()
{
if (this.LayoutPath == null)
{
throw new InvalidOperationException(Strings.GetString("LayoutPathNotSpecified"));
}
if (this.PackagePath == null)
{
throw new InvalidOperationException(Strings.GetString("PackagePathNotSpecified"));
}
}
protected override void OnExecute()
{
object[] objArray;
object[] objArray2;
object[] objArray3;
string metadata = this.LayoutPath.GetMetadata("FullPath");
string str1 = this.PackagePath.GetMetadata("FullPath");
Assembly sharepointTasksAss = Assembly.Load("Microsoft.VisualStudio.SharePoint.Tasks");
if (sharepointTasksAss != null)
base.Log.LogMessage(MessageImportance.High, "Found Tasks assembly!");
else
{
base.Log.LogError("Couldn't find the tasks assembly");
return;
}
if (!Directory.Exists(metadata))
{
base.Log.LogErrorFromResources("LayoutPathDoesNotExist", new object[] { metadata });
}
else
{
MethodInfo createCabMethod = GetStaticMethod(sharepointTasksAss, "Microsoft.VisualStudio.SharePoint.Tasks.Utilities.CabCreator", "CreateCabinet");
if (createCabMethod == null)
{
base.Log.LogError("the method could not be retrieved on type.");
return;
}
else
base.Log.LogMessage(MessageImportance.High, "Found method: " + createCabMethod.Name);
IEnumerable<string> strs = createCabMethod.Invoke(null, new object[] { metadata, str1 }) as IEnumerable<string>;
/*
* The following code would error in the original task.
*/
//foreach (string str2 in strs)
//{
// if (PathUtils.HasIllegalDeploymentPathCharacters(str2))
// {
// base.Log.LogWarningFromResources("FileNameContainsIllegalDeploymentPathCharacters", new object[] { str2 });
// }
//}
base.Log.LogMessage(MessageImportance.High, Strings.GetString("PackageCreatedSuccessfully"), new object[] { str1 });
}
Type codeMarkersType = null;
try
{
codeMarkersType = sharepointTasksAss.GetType("Microsoft.Internal.Performance.CodeMarkers", true);
}
catch (Exception e)
{
base.Log.LogErrorFromException(e, true);
}
if (codeMarkersType == null)
{
base.Log.LogError("Couldn't get the CodeMarkers class!");
return;
}
else
base.Log.LogMessage(MessageImportance.High, "Found the type: " + codeMarkersType.FullName);
/*
* This has yet to be added back in.
*/
//CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfSharePointPackageWspPackageEnd);
}
private MethodInfo GetStaticMethod(Assembly assembly, string typeName, string methodName)
{
Type type = null;
try
{
type = assembly.GetType(typeName, true);
}
catch (Exception e)
{
base.Log.LogErrorFromException(e, true);
}
if (type == null)
{
base.Log.LogError("Couldn't get the type: " + typeName);
return null;
}
else
base.Log.LogMessage(MessageImportance.High, "Found the type: " + type.FullName);
MethodInfo methodInfo = type.GetMethod(methodName, BindingFlags.Static);
if (methodInfo == null)
{
MethodInfo[] methods = type.GetMethods().Union(type.GetMethods(BindingFlags.Static)).ToArray();
base.Log.LogWarning(string.Format("Wasn't able to find {0} directly. Searching through the static {1} method(s) on {2}", methodName, methods.Length, type.FullName));
foreach (MethodInfo info in methods)
{
if (info.Name == methodName && methodInfo == null)
methodInfo = info;
}
if (methodInfo == null)
{
MemberInfo[] members =
type.GetMembers().Union(type.GetMembers(BindingFlags.Static | BindingFlags.NonPublic)).Union(type.GetMembers(BindingFlags.NonPublic)).ToArray();
base.Log.LogWarning(string.Format("Wasn't able to find {0}. Searching through the {1} members(s) on {2}", methodName, methods.Length, type.FullName));
MemberInfo createCabMember = null;
foreach (MemberInfo member in members)
{
if (member.Name == methodName)
{
createCabMember = member;
break;
}
else
base.Log.LogMessage(MessageImportance.High, "Found member: " + member.Name);
}
if (createCabMember == null)
base.Log.LogError("Still wasn't able to find " + methodName + " in the members!");
}
}
return methodInfo;
}
}
}
Since most of the classes and methods are marked as internal I had to make use reflection to get the type and method needed to actually build the cab/wsp files. This is done in the method: GetStaticMethod
Step Four
If you read over the decompiled code and my custom version of the class you'll notice the Strings class. It appears to be a resource accessor class. I decided that I'd just decompile that code as well and use it in my solution that makes the custom task instead of reflecting every time I wanted to access a string resource. This file ended up not being a straight decompile as it has a line this.GetType().Assembly it uses to get the current assembly containing the resources. This works fine within the original assembly but causes a problem in this custom assembly.
The original line:
internal Strings()
{
this.resources = new ResourceManager("Strings", this.GetType().Assembly);
}
This line had to be changed to:
Assembly sharepointTasksAss = Assembly.Load("Microsoft.VisualStudio.SharePoint.Tasks");
this.resources = new ResourceManager("Strings", sharepointTasksAss);
Step Five
After I had a custom build task that mimics the original I needed to now place that into the targets file. I then backed up the original targets file and made a custom one replacing the UsingTask section like this:
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="CreateSharePointProjectService" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumerateFiles" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumerateFeature" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumeratePackage" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumerateProjectItem" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="LayoutFiles" />
<!-- The next task is a mimic of the one from the other assembly. I decompiled it and recreated it so it wouldn't error. LOL -->
<UsingTask AssemblyFile="C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\SharepointTaskLibrary.dll" TaskName="PackageFiles" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="ResolveProjectMember" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="SetPackagingProperties" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="ValidatePackage" />
This made the task point to my DLL which contained the custom task. Specifically, this line:
<UsingTask AssemblyFile="C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\SharepointTaskLibrary.dll" TaskName="PackageFiles" />
FINALLY
I dropped the compiled DLL and edited targets file into the C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools directory (again backing up the original targets file).
This allowed me to build via TFS 2010 with custom outputs the wsp files generated by the SharePoint solutions!
I used this site as a resource:
http://blogs.like10.com/2011/08/04/team-build-2010-customized-output-directories-sharepoint-2010-wsps/
(I may have used another one or two sites as a resource, but I can find them in the browser history at the moment).
Your mileage may vary, but please let me know if anyone has this similar issue and is able to fix it in a non "hacked" way.
UPDATE
This whole issue seems to have came from the original TFS install I was administering. I recently moved our team to a proper TFS server (2012) with a completely fresh OS install and a new database server. Once I migrated the databases over and ran the upgrade tasks in TFS I was able to do some small build edits to make my build work with 2012 and I did not encounter this issue a second time. I believe that because the original 2010 TFS was on a converted dev machine it caused this problem.

How do I set an embedded Groovy scripts classpath?

I am trying to extend an Eclipse code builder (for generating DTOs from Hibernate VOs) - and it uses Groovy for its template system.
The code it uses to create the groovy Script is a little weird (not what I see in the Groovy docs) but it works, mostly:
GroovyShell shell = new GroovyShell();
script = shell.parse(source);
Then, later:
Binding binding = (bindings == null ? new Binding() : new Binding(bindings));
Script scriptInstance = InvokerHelper.createScript(script.getClass(), binding);
scriptInstance.setProperty("out", out);
scriptInstance.run();
out.flush();
Now, this works just fine, until it hits a reference to an object that is not directly in the project. In the script, it iterates through the properties of the Class that it is processing - when it does this, Groovy looks at all of the methods and when it can't find a Class definition for one of the method parameters, it craps out. In this case, it's dying when it finds any references to Hibernate, but I'm sure it will crap out with a lot more. It doesn't need to do anything to them, but it can't live without knowing what they are apparently.
Script doesn't appear to have a classloader that I can supply any classpath info, so I tried providing it to the GroovyShell - no difference.
What's the proper way to fix this so that the Groovy interpreter can find my projects referenced Jars?
I had this exact problem and solved it by creating my own URLClassLoader, and using reflection to call a protected method to add a new path to the ClassPath
// Specify the path you want to add
URL url = new URL("file://path/to/classes/here");
// Create a new class loader as a child of the default system class loader
ClassLoader loader = new URLClassLoader(System.getClass().getClassLoader());
// Get the AddURL method and call it
Method method = URLClassLoader.class.getDeclaredMethod("addURL",new Class[]{URL.class});
method.setAccessible(true);
method.invoke(loader,new Object[]{ url });
GroovyShell shell = new GroovyShell( loader );
The same as #James can be done without using reflection, loading all jar files from a certain folder:
URLClassLoader classLoader = new URLClassLoader( getExtraJarUrls(), getClass().getClassLoader() );
GroovyShell shell = new GroovyShell( classLoader, binding, compilerConfiguration );
private URL[] getExtraJarUrls() throws MalformedURLException
{
logger.debug( "Loading extra jars from {}", EXTRA_JARS_DIR.getAbsolutePath() );
URL[] result;
File[] files = EXTRA_JARS_DIR.listFiles( new JarFilenameFilter() );
if (files != null)
{
List<URL> urls = new ArrayList<URL>( files.length );
for (File file : files)
{
urls.add( file.toURI().toURL() );
}
result = urls.toArray( new URL[urls.size()] );
}
else
{
result = new URL[0];
}
logger.debug( "Adding URLs to classloader: {}", Arrays.toString( result ) );
return result;
}
private static class JarFilenameFilter implements FilenameFilter
{
public boolean accept( File dir, String name )
{
return name.endsWith( ".jar" );
}
}
I'm having the same problem trying to automate Gant scripts running. The solution I found is:
copy gant-starter.conf (or
groovy-starter.conf if it's just
groovy) from $GROOVY_HOME/conf to your
own dir;
add "load [directory]" or
"load [jar]" there, as described in
javadocs to
org.codehaus.groovy.tools.LoaderConfiguration,
found in Groovy source distribution;
before starting groovy set
groovy.starter.conf.override system
property to the name of that file,
like
-Dgroovy.starter.conf.override=[filename]

Resources