I'm trying to externalize a properties file. Right now, I'm testing by placing my properties file under my user profile folder, but I'm getting a NullPointerException. To be more specific, the System.out.println statement isn't being displayed in the console, which leads me to think that maybe it's the environment variable that's triggering the NullPointerException. I have also ensured that I placed the properties file in the correct path. Here is part of the code:  @PropertySource("file:${USERPROFILE}/test.properties") public MyClass{   private static Environment e;   public static void main(String[] args){     System.out.println("Test properties file: " + e.getProperty("myKey");  }  }   Properties file:  myKey=testvalue   And this line in my dispatcher servlet xml file :  &lt;context:property-placeholder location="classpath*:query.properties, file:${USERPROFILE}/test.properties"/&gt;   Where am I going wrong here? Any help would be greatly appreciated.
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
94370
Now, before you say it: I did Google and my hbm.xml file is an Embedded Resource.   Here is the code I am calling:  ISession session = GetCurrentSession(); var returnObject =  session.Get&lt;T&gt;(Id);   Here is my mapping file for the class:  &lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"&gt;   &lt;class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true"&gt;     &lt;id name="ID" column="ID" unsaved-value="0"&gt;       &lt;generator class="identity" /&gt;     &lt;/id&gt;      &lt;property name="Name" column="Name" /&gt;     &lt;property name="NumberOfBuckets" column="NumberOfBuckets"  /&gt;     &lt;property name="SearchCriteriaOne" column="SearchCriteriaOne" /&gt;      &lt;bag name="_Businesses" cascade="all"&gt;       &lt;key column="SubCategoryId"/&gt;       &lt;one-to-many           class="HQData.Objects.Business, HQData"/&gt;     &lt;/bag&gt;      &lt;bag name="_Buckets" cascade="all"&gt;       &lt;key column="SubCategoryId"/&gt;       &lt;one-to-many          class="HQData.Objects.Bucket, HQData"/&gt;     &lt;/bag&gt;    &lt;/class&gt; &lt;/hibernate-mapping&gt;   Has anyone run to this issue before?  Here is the full error message:   MappingException: No persister for:  HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)  in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()  in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)  in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436   Update, here's what the solution for my scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime.
93297
I wanted to set environment variables JAVA_HOME and PATH. So I wanted to open ~/.pam_environment since it is the best place to set environment variables relevant to a particular user according to the link . The link states:  Session-wide environment variables Environment variable settings that should affect just a particular user (rather then the &gt;system as a whole) should be set into: ~/.pam_environment - This file is specifically meant for setting a user's  environment. It is not a script file, but rather consists of assignment expressions, one per line.  The problem I have is that I am not able to open the file ~/.pam_environment by using the command gedit ~/.pam_environment. I do not know whether this is the right way to open this file, please point me in the right direction.
39983
I recently discovered /etc/environment, which seems a more standard way to setup simple environment variables than scripts, but I was wondering if there was a way to back-reference environment variables in the /etc/environment file.  That is, I have this:  JAVA_HOME="/tools/java" GRAILS_HOME="/tools/grails" GROOVY_HOME="/tools/groovy" GRADLE_HOME="/tools/gradle" PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"   If I try to add $JAVA_HOME/bin to the PATH definition, however, I get $JAVA_HOME/bin, and not the interpolated variable. To remedy this, I'm creating environment.sh in profile.d to add the /bin entries to the path, but this seems sloppy and disorganized.  Is there a way to backreference the environment variables in /etc/environment?
3956
Im creating a community user from an Apex code. When our internal users (non-admins) run the code they are getting following error. (This was working fine when we test the feature in sandbox)     SObjectException: Field is not writeable: User.ProfileId   The code is       //Grab Community User Profile     Profile p = [Select Id, Name from Profile where Name = :COMMUNITY_PROFILE LIMIT 1];       User PortalUser = new User();          PortalUser.UserName = Con.Email+'-POC';         PortalUser.ContactId = Con.Id;         PortalUser.ProfileId = p.id;         PortalUser.Email = Con.Email;         PortalUser.EmailEncodingKey = 'UTF-8';         PortalUser.FirstName = Con.FirstName;         PortalUser.LastName = Con.LastName;         PortalUser.TimeZoneSidKey = 'America/Los_Angeles';         PortalUser.LocaleSidKey = 'en_US';         PortalUser.LanguageLocaleKey = 'en_US';          if (Con.LastName.length() &gt;= 8){             PortalUser.Alias = Con.LastName.substring(0, 7);             }else{             PortalUser.Alias = Con.LastName;         }             SObjToInsert.add(PortalUser);
56271
C#6 Update  In :  // C#1-5 propertyValue1 = myObject != null ? myObject.StringProperty : null;   // C#6 propertyValue1 = myObject?.StringProperty;   The question below still applies to older versions, but if developing a new application using the new ?. operator is far better practice.  Original Question:  I regularly want to access properties on possibly null objects:  string propertyValue1 = null; if( myObject1 != null )     propertyValue1 = myObject1.StringProperty;  int propertyValue2 = 0; if( myObject2 != null )     propertyValue2 = myObject2.IntProperty;   And so on...  I use this so often that I have a snippet for it.  You can shorten this to some extent with an inline if:  propertyValue1 = myObject != null ? myObject.StringProperty : null;   However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:  propertyValue1 = myObject != null ?      (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;   What I really want is ?? style syntax, which works great for directly null types:  int? i = SomeFunctionWhichMightReturnNull(); propertyValue2 = i ?? 0;   So I came up with the following:  public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action, TResult valueIfNull )     where T : class {     if ( input != null ) return action( input );     else return valueIfNull; }  //lets us have a null default if the type is nullable public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action )     where T : class     where TResult : class { return input.IfNotNull( action, null ); }   This lets me us this syntax:  propertyValue1 = myObject1.IfNotNull( x =&gt; x.StringProperty ); propertyValue2 = myObject2.IfNotNull( x =&gt; x.IntProperty, 0);  //or one with multiple levels propertyValue1 = myObject.IfNotNull(      o =&gt; o.ObjectProp.IfNotNull( p =&gt; p.StringProperty ) );   This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.  This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:  if( ( obj1 == null &amp;&amp; obj2 == null ) ||      ( obj1 != null &amp;&amp; obj2 != null &amp;&amp; obj1.Property == obj2.Property ) )     ...  //becomes if( obj1.NullCompare( obj2, (x,y) =&gt; x.Property == y.Property )      ...   What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?    I guess what I really want here is a compiler/language extension:  propertyValue1 = myObject != null ? myObject.StringProperty : null;  //becomes propertyValue1 = myObject?StringProperty;   This would make the complex case far easier:  propertyValue1 = myObject != null ?      (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null  //becomes propertyValue1 = myObject?ObjectProp?StringProperty;   This would only work for value types, but you could return nullable equivalents:  int? propertyValue2 = myObject?ObjectProp?IntProperty;  //or  int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
37684
I'm trying create a Map using a name field as key.  Sample code:  Set&lt;String&gt; priceBooksNames = new Set&lt;String&gt;(); priceBooksNames.add('LN-200'); priceBooksNames.add('LN-100');  Map&lt;string,PriceBook2&gt; priceBooks = new Map&lt;string,PriceBook2&gt;([SELECT name,id FROM PriceBook2 WHERE name=:priceBooksNames ]); system.debug(priceBooks.get('LN-100')); //this is returning NULL   I can see on console that setId on map is not getting the name field value.  VARIABLE_ASSIGNMENT [5]|priceBooks|{"serId":1,"value":{"01sb0000000hiqQAAQ":{"serId":2,"value":{"Name":"LN-100 ADULTOS","Id":"01sb0000000hiqQAAQ"}},"01sb0000000hiqGAAQ":{"serId":3,"value":{"Name":"LN-200 EMPRESAS","Id":"01sb0000000hiqGAAQ"}}}}   What I'm going wrong?
111070
I've been trying to run a jar file - let's call it test.jar - that uses the Sybase jconn3.jar on a Unix system.  I have created a MANIFEST.MF file that has the following:  Class-Path: $SYBASE/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar   This gives a ClassNotFoundError. $SYBASE is the system variable that points to /opt/sybase13; I've also tried the following:  Class-Path: /opt/sybase13/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar   and  Class-Path: opt/sybase13/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar   However, if I copy the jconn3.jar file from the $SYBASE/jConnect-6_0/classes to the same directory as test.jar, and update my MANIFEST.MF to read as follows:  Class-Path: jconn3.jar commons-net-1.3.0.jar   The application runs as expected.  Now, I've been able to verify the jconn3.jar file works by copying it locally; my MANIFEST.MF file includes the path to my Main-Class, so that's not at issue here.  What do you think could be the problem? I've been looking at this thing for too long now. Thanks!
7441
Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value, then why can't we do the same for local variables?  And it also leads to problems as explained in :     Well this rule is most frustrating when trying to close a resource in a finally block. If I instantiate the resource inside a try, but try to close it within the finally, I get this error. If I move the instantiation outside the try, I get another error stating that a it must be within a try.      Very frustrating.
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
18475
I am trying to build an executable jar program which depends on external jar downloaded. In my project, I included them in the build path and can be run and debug within eclipse.  When I tried to export it to a jar, I can run the program but I can't when I try to press a button which includes function calls and classes from the external jar. I have edited the environment variables (Windows XP) CLASSPATH to include paths of all the external jar, but it doesn't work.  A point to note is that I got compile warnings while exporting my executable jar, but it doesn't show up any description about the warnings.  Would someone kindly provide a thorough guide on how to include an external jar program using eclipse?
53765
When I parse my xml file (variable f) in this method, I get an error      C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified)   I know I do not have the dtd, nor do I need it.  How can I parse this File object into a Document object while ignoring DTD reference errors?  private static Document getDoc(File f, String docId) throws Exception{     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();     DocumentBuilder db = dbf.newDocumentBuilder();     Document doc = db.parse(f);       return doc; }
7576
I have a lookup to a custom object called Project on my Opportunity object. I am trying to write a trigger that updates an Active, Awarded, and Title on the Project object whenever the Active, Awarded, or Title field is updated on Opportunity based some on more logic that isn't in my code below. This is my first trigger and needing a little help due to a NullPointerException where I try to set Project__r.Active__c = true. Any thoughts?      trigger ProjectFieldsTrigger on Opportunity (before insert, before update) {       //List&lt;Opportunity&gt; opp = [SELECT Name, Active__c, Funded__c, Title__c, Project__r.Name, Project__r.Active__c, Project__r.Awarded__c      //  FROM Opportunity WHERE Id IN :Trigger.New];      for(Opportunity o: Trigger.New){          if(o.Project__c != null){              if(o.Active__c == 'Y'){                 o.Project__r.Active__c = true;             }      }  }
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
646
For the longest time I have been using System.debug(JSON.Serialize(o)) to output objects to the debug log for troubleshooting purposes. This has worked up until my most recent project. Even existing code seems to be having this behavior.  I've tested API versions 41-45 with no luck. The actual line of code I'm using is:  system.debug(json.serialize(accountsToInsert)); // This is a map   I have also tried:  system.debug(json.serialize(accountsToInsert.get(Key)));   AND   Account test = accountsToInsert.get(Key); system.debug(json.serialize(test));   The code is called from a method defined in a VF page action attribute.  Is this just a thing that we have to live with now? Is there another way to get a  full look into the state of an object at run time?
61570
I would like to know what would be the best way to do unit testing of a servlet.   Testing internal methods is not a problem as long as they don't refer to the servlet context, but what about testing the doGet/doPost methods as well as the internal method that refer to the context or make use of session parameters?  Is there a way to do this simply using classical tools such as JUnit, or preferrably TestNG? Did I need to embed a tomcat server or something like that?
86355
My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments. eg.  /// &lt;summary&gt;Summary here&lt;/summary&gt; /// &lt;example&gt;Here is an example  &lt;code&gt;example code here&lt;/code&gt; &lt;/example&gt; public void SomeFunction()    We then use Sandcastle and build the help files we need (chm and an online website).  It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.  Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?