Code compiles - throws java.lang.NullPointerException

This program is intended to build an array and populate it with inventory, then print out the inventory line item by line item. The code compiles but throws the NullPointerException error when the program is run. Here is the main method with 2 classes, as well as the text from the error and a pointer to the specific place in the code the error is from...
main method
import java.util.Scanner;
import static java.lang.System.out;
import java.io.*;
public class Inventory1
    private static void Exit() //set ability for program to exit on each loop
    { out.println("We hope this inventory program was " +
                       "helpful. Thank you for using our program.");
      System.exit(0);
  public static void main (String [] args)
      boolean validNumber;
      boolean validCount;
      boolean validDollars;
      //initialize scanner
  Scanner sc = new Scanner(System.in);        
  Music info = new Music();
  //declare and initialize variables
  int[] itemNumber = new int [5];
  String[] productName = new String[5];
  int[] stockAmount = new int[5];
  double[] productCost = new double[5];
  double[] totalValue = new double[5];
  while (true)
      for (int i=0; i<5; i++)
        out.println( "Enter CD name/description or 'exit' to stop the" +
                " program: "); //prompt - product name
           info.productName[i] = sc.next(); // input
           if (info.productName.equalsIgnoreCase("exit"))
out.println("Exit entered. ");
Exit();
else
do
out.println("Please enter CD number: "); //prompt - item number
info.itemNumber[i] = sc.nextInt();
validNumber = true;
if( (info.itemNumber[i] <1 ) )
{//make sure product number is positive number
validNumber = false;
out.println("All CDs have positive numbers and no other " +
"characters. Please enter a valid CD number.");
}while (!validNumber);
do
out.println("Quantity in stock: "); // prompt - quantity
info.stockAmount [i] = (sc.nextInt()); // capture temp number to verify
validCount = true;
if(( info.stockAmount[i] <1 ))
{ // ensure stock amount is positive number
validCount = false;
out.println( "Inventory numbers must be positive. Please " +
"enter a correct value." ); // prompt for correct #
} while (!validCount);
do
out.println("What is the product cost for each unit? "); // prompt - cost
info.productCost[i] = sc.nextDouble();
validDollars = true;
if (( info.productCost[i] <1 ))
validDollars = false;
out.println( "Product cost must be a positive dollar " +
"amount. Please enter correct product cost." );
} while (!validDollars);
out.println(totalValue);
@Override
public String toString()
return super.toString();
Music classclass Music
String productName[];
String title;
int itemNumber[];
int item;
int stockAmount[];
int amount;
double productCost[];
double cost;
double totalValue[];
double value;
int i;
public Music(String title, int item, int amount, double cost, double value,
int i)
this.productName[i] = title;
this.itemNumber[i] = item;
this.stockAmount[i] = amount;
this.productCost[i] = cost;
this.totalValue[i] = value;
public Music()
public void setTotalValue(double[] totalValue)
this.totalValue = totalValue;
public double[] getTotalValue()
return totalValue;
public void setStockAmount(int[] stockAmount)
this.stockAmount = stockAmount;
public int[] getStockAmount()
return stockAmount;
public void setProductCost(double[] productCost)
this.productCost = productCost;
public double[] getProductCost()
return productCost;
public void setProductName(String[] productName)
this.productName = productName;
public String[] getProductName()
return productName;
public void setItemNumber (int[] itemNumber)
this.itemNumber = itemNumber;
public int[] getItemNumber()
return itemNumber;
}TotalInventory classclass TotalInventory
double TotalInfo;
public int [] getStockAmount(int[] units)
int[] stockAmount = units;
return units;
public double[] getTotalValue(double[] cost)
double[] productCost = cost;
return cost;
error message
init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\Tammy\My Documents\School\JavaProgramming\Inventory\build\classes
compile:
run:
Enter CD name/description or 'exit' to stop the program:
here we go
Exception in thread "main" java.lang.NullPointerException
        at Inventory1.main(Inventory1.java:54)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
Inventory1.main(Inventory1.java:54) is this line of code in the main method: info.productName[i] = sc.next(); // input Any suggestions?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

I have not changed my code from when I supplied it in the first post - I am simply pointing out that I already initiated the String with 5 as the number...I've supplied you with everything I am getting. The three modules are in the original post, as is the error message being received - nothing has changed.
This means with the code posted in my original question I am getting an NPE. I compile the code and run it. I'm able to input the "title" (productName) after the prompt but then get the NPE. I'm not trying to make you read my mind, I'm just asking for help and make every effort to provide as much detail as possible to make that easier on all of us.

Similar Messages

  • Jax-ws 2.2.8 and ws-addressing: Client throwing java.lang.NullPointerException on receipt of HTTP 202 when using non-anonymous ReplyTo address

    Server: JBoss EAP 6.2.0
    Client: JDK 1.7.0_51 x64
    JAX-WS: RI 2.2.8 ( via -Djava.endorsed.dirs )
    I am getting a java.lang.NullPointerException when calling the operation on the WS endpoint from the client when using non-anonymous replyTo address.
    I have simplified the scenario into a small test case that hopefully others can replicate. Since the exception is happening on the client instead of the server, I would think that the container used is irrelevant, but I have specified it nonetheless.
    1) WebService:
    package test.webservice;
    import java.util.Random;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.jws.soap.SOAPBinding;
    import javax.xml.ws.soap.Addressing;
    @WebService(targetNamespace="http://services.nowhere.org/")
    @Addressing(required=true)
    @SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
    public class RandomTest {
        @WebMethod
        public long nextRandom(@WebParam boolean forceException) throws Exception {
            if( forceException ) {
                throw new Exception("Some exception");
            Random rand = new Random();
            return rand.nextLong();
    2) Generated WSDL by JBossEAP 6.2.2:
    <?xml version='1.0' encoding='UTF-8'?><wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:tns="http://webservice.test/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" name="RandomTestService" targetNamespace="http://webservice.test/">
      <wsdl:types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://webservice.test/" elementFormDefault="unqualified" targetNamespace="http://webservice.test/" version="1.0">
      <xs:element name="nextRandom" type="tns:nextRandom"/>
      <xs:element name="nextRandomResponse" type="tns:nextRandomResponse"/>
      <xs:complexType name="nextRandom">
        <xs:sequence/>
      </xs:complexType>
      <xs:complexType name="nextRandomResponse">
        <xs:sequence>
          <xs:element name="return" type="xs:long"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
      </wsdl:types>
      <wsdl:message name="nextRandom">
        <wsdl:part element="tns:nextRandom" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:message name="nextRandomResponse">
        <wsdl:part element="tns:nextRandomResponse" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:portType name="RandomTest">
        <wsdl:operation name="nextRandom">
          <wsdl:input message="tns:nextRandom" name="nextRandom" wsam:Action="http://webservice.test/RandomTest/nextRandomRequest" wsaw:Action="http://webservice.test/RandomTest/nextRandomRequest">
        </wsdl:input>
          <wsdl:output message="tns:nextRandomResponse" name="nextRandomResponse" wsam:Action="http://webservice.test/RandomTest/nextRandomResponse" wsaw:Action="http://webservice.test/RandomTest/nextRandomResponse">
        </wsdl:output>
        </wsdl:operation>
      </wsdl:portType>
      <wsdl:binding name="RandomTestServiceSoapBinding" type="tns:RandomTest">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsaw:UsingAddressing wsdl:required="true"/>
        <wsp:PolicyReference URI="#RandomTestServiceSoapBinding_WSAM_Addressing_Policy"/>
        <wsdl:operation name="nextRandom">
          <soap:operation soapAction="" style="document"/>
          <wsdl:input name="nextRandom">
            <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output name="nextRandomResponse">
            <soap:body use="literal"/>
          </wsdl:output>
        </wsdl:operation>
      </wsdl:binding>
      <wsdl:service name="RandomTestService">
        <wsdl:port binding="tns:RandomTestServiceSoapBinding" name="RandomTestPort">
          <soap:address location="http://localhost:8080/servertest/RandomTest"/>
        </wsdl:port>
      </wsdl:service>
        <wsp:Policy xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="RandomTestServiceSoapBinding_WSAM_Addressing_Policy"><wsam:Addressing><wsp:Policy/></wsam:Addressing></wsp:Policy>
    </wsdl:definitions>
    3) ant build.xml to generate the client code from WSDL
    <?xml version="1.0" encoding="UTF-8"?>
    <project default="build" basedir="..">
        <property name="jaxws.classpath" location="C://jaxws-2.2.8/jaxws-ri/lib/*.jar"/>
        <taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
               <classpath path="${jaxws.classpath}"/>
        </taskdef>
        <target name="build" >
            <!-- For these to work, the JAR files in tools/jaxws-ri must be included in Ant's classpath -->
            <wsimport wsdl="http://localhost:8080/servertest/RandomTest?wsdl"
                   verbose="true"
                   sourcedestdir="src"
                   destdir="bin"
                   keep="true">
                   <xjcarg value="-enableIntrospection"/>
            </wsimport>
        </target>
    </project>
    4) Client code
    4a) ClientTest.java - Actual client run from client
    package test.wsclient;
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.ws.BindingProvider;
    import javax.xml.ws.Endpoint;
    import javax.xml.ws.handler.Handler;
    import javax.xml.ws.soap.AddressingFeature;
    import org.nowhere.services.RandomTest;
    import org.nowhere.services.RandomTestService;
    public class ClientTest {
        public static void main(String args[]) throws Exception {
            ClientTest app = new ClientTest();
            app.testAddressing();
        public void testAddressing() throws Exception {
            String REPLY_TO_ADDRESS = "http://localhost:8082/servertest/RandomCallback";
            String FAULT_TO_ADDRESS = "http://localhost:8082/servertest/RandomCallbackFault";
            RandomTestService service = new RandomTestService();
            RandomTest port = service.getRandomTestPort(new AddressingFeature());
            BindingProvider provider = (BindingProvider) port;
            // pass the replyTo address to the handler
            provider.getRequestContext().put("ReplyTo", REPLY_TO_ADDRESS);
            provider.getRequestContext().put("FaultTo", FAULT_TO_ADDRESS);
            // Register handlers to set the ReplyTo and FaultTo on the SOAP request sent to the WS endpoint
            List<Handler> handlerChain = new ArrayList<Handler>();
            handlerChain.add(new ClientHandler());
            provider.getBinding().setHandlerChain(handlerChain);
            // Start endpoint to receive callbacks from WS
            Endpoint endpoint = Endpoint.publish(REPLY_TO_ADDRESS, new CallbackSEI());
            try {
                port.nextRandom(false);
            } catch( Exception ex ) {
                ex.printStackTrace();
            } finally {
                Thread.sleep(10000);
            endpoint.stop();
            System.exit(0);
    4b) ClientHandler.java - Used to set the wsa ReplyTo address and FaultTo address when sending SOAP request from client to server
    package test.wsclient;
    import java.util.Set;
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.MessageContext.Scope;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class ClientHandler implements SOAPHandler<SOAPMessageContext> {
        public ClientHandler() {};
        @Override
        public Set<QName> getHeaders() {
            return null;
        @Override
        public void close(MessageContext arg0) {
        @Override
        public boolean handleFault(SOAPMessageContext context) {
            return true;
        protected void setAnAddress(SOAPHeader header, String tagName, String address) {
            NodeList nodeListReplyTo = header.getElementsByTagName(tagName);
            NodeList nodeListAddress = nodeListReplyTo.item(0).getChildNodes();
            for (int i = 0; i < nodeListAddress.getLength(); i++) {
                Node node = nodeListAddress.item(i);
                if ("Address".equals(node.getLocalName())) {
                    node.setTextContent(address);
                    break;
        protected String getMessageID(SOAPHeader header) {
            NodeList nodeListMessageId = header.getElementsByTagName("MessageID");
            return nodeListMessageId.item(0).getTextContent();
        @Override
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean isOutbound = (Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (isOutbound) {
                try {
                    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                    SOAPHeader header = envelope.getHeader();
                    /* extract the generated MessageID */
                    String messageID = getMessageID(header);
                    context.put("MessageID", messageID);
                    context.setScope("MessageID", Scope.APPLICATION);
                    /* change ReplyTo address */
                    setAnAddress(header, "ReplyTo", (String) context.get("ReplyTo"));
                    setAnAddress(header, "FaultTo", (String) context.get("FaultTo"));
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
            return true;
    4c) CallbackSEI.java - endpoint on the client for server to send the SOAP response back to the client
    package test.wsclient;
    import javax.annotation.Resource;
    import javax.jws.Oneway;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.ws.Action;
    import javax.xml.ws.RequestWrapper;
    import javax.xml.ws.WebServiceContext;
    import javax.xml.ws.soap.Addressing;
    @WebService
    @Addressing
    //@HandlerChain(file = "/handler-chain.xml")
    public class CallbackSEI {
        @Resource
        private WebServiceContext context;
         * If there is no namespace specified in the method below, then the CallbackSEI needs to be in the same package as the
         * WS endpoint.
        @Oneway
        @Action(input="http://services.nowhere.org/RandomTest/nextRandomResponse")
        @RequestWrapper(localName="nextRandomResponse", targetNamespace="http://services.nowhere.org/")
        public void handleNotification(@WebParam(name="return")long random) {
            System.out.println("Asynch response received");
            System.out.println( random );
            //System.out.println("This response relates to the message ID: "+ getMessageID());
    In summary:
    Server is listening on port 8080
    Client will listen in port 8082 for the callback from the server for the SOAP response
    Now when I run the client, I see that the proper behaviour as far as ws-addressing is concerned. That is:
    client  -- SOAP request ( on port 8080 ) --> server
    client <-- HTTP 202 ( empty HTTP body )  --- server
    client <-- SOAP response ( on port 8082 )  --- server
    All well and good, except that I am getting a NullPointerException on the client side when I call the operation.
    With debugging of the SOAP request and responses, I get the following output:
    ---[HTTP request - http://localhost:8080/servertest/RandomTest]---
    Accept: text/xml, multipart/related
    Content-Type: text/xml; charset=utf-8
    SOAPAction: "http://services.nowhere.org/RandomTest/nextRandomRequest"
    User-Agent: JAX-WS RI 2.2.8 svn-revision#13980
    <?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><S:Header><To xmlns="http://www.w3.org/2005/08/addressing">http://localhost:8080/servertest/RandomTest</To><Action xmlns="http://www.w3.org/2005/08/addressing">http://services.nowhere.org/RandomTest/nextRandomRequest</Action><ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
        <Address>http://localhost:8082/servertest/RandomCallback</Address>
    </ReplyTo><FaultTo xmlns="http://www.w3.org/2005/08/addressing">
        <Address>http://localhost:8082/servertest/RandomCallbackFault</Address>
    </FaultTo><MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:bcd2f6ef-3034-49e8-b837-dbd6a772fb93</MessageID></S:Header><S:Body><ns2:nextRandom xmlns:ns2="http://services.nowhere.org/"><arg0>false</arg0></ns2:nextRandom></S:Body></S:Envelope>--------------------
    ---[HTTP response - http://localhost:8080/servertest/RandomTest - 202]---
    null: HTTP/1.1 202 Accepted
    Content-Length: 0
    Content-Type: text/xml;charset=UTF-8
    Date: Fri, 18 Jul 2014 08:34:36 GMT
    Server: Apache-Coyote/1.1
    java.lang.NullPointerException
        at com.sun.proxy.$Proxy38.nextRandom(Unknown Source)
        at test.wsclient.ClientTest.testAddressing(ClientTest.java:43)
        at test.wsclient.ClientTest.main(ClientTest.java:18)
    ---[HTTP request]---
    Cache-control: no-cache
    Host: localhost:8082
    Content-type: text/xml; charset=UTF-8
    Content-length: 704
    Connection: keep-alive
    Pragma: no-cache
    User-agent: Apache CXF 2.7.7.redhat-1
    Accept: */*
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><Action xmlns="http://www.w3.org/2005/08/addressing">http://services.nowhere.org/RandomTest/nextRandomResponse</Action><MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:65d8d7fc-09e4-494a-a9c5-0a01faf4d7e6</MessageID><To xmlns="http://www.w3.org/2005/08/addressing">http://localhost:8082/servertest/RandomCallback</To><RelatesTo xmlns="http://www.w3.org/2005/08/addressing">uuid:bcd2f6ef-3034-49e8-b837-dbd6a772fb93</RelatesTo></soap:Header><soap:Body><ns2:nextRandomResponse xmlns:ns2="http://services.nowhere.org/"><return>2870062781194370669</return></ns2:nextRandomResponse></soap:Body></soap:Envelope>--------------------
    Asynch response received
    2870062781194370669
    As you can see from the output above, the proxy is throwing an Exception when it receives the HTTP 202 response.
    Any ideas ?

    I think I have found when I get this error and probably I have found a bug. I will appreciate if someone can confirm this.
    In my BPEL project setup, my BPEL process's wsdl file imports another wsdl from different namespace. Here is sample snippet -
    <wsdl:definitions targetNamespace="http://namespace/1">
    <wsdl:import namespace="http://namespace/2" location="resources/another.wsdl"/>
    <plnk:partnerLinkType....../>
    </wsdl:definitions>
    Please let me know. I checked the bundled samples with Oracle BPEL PM and did not find any similar case where process wsdl imports another wsdl.
    Thank you.
    Meghana

  • My servlet throws java.lang.NullPointerException when calling service()

    i can't determine which part exactly is null and the exception log is:
    Jun 28, 2009 1:28:11 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet CheckLog threw exception
    java.lang.NullPointerException
    at LoginSer.processRequest(LoginSer.java:37)
    at LoginSer.doPost(LoginSer.java:85)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Thread.java:619)
    and here is the code can anyone help me please:
    import java.io.*;
    import java.net.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import com.microsoft.sqlserver.jdbc.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.xml.ws.Dispatch;
    public class RegForm extends HttpServlet {
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String fName=request.getParameter("fName");
            String lName=request.getParameter("lName");
            String addr=request.getParameter("address");
            int x=0;
            if(!(fName.equals(null) && lName.equals(null) && addr.equals(null))){
            try {
                  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                String url="jdbc:sqlserver://localhost:1433;databaseName=MyDB1;userName=sa;password=iszecson;";
                Connection conn=DriverManager.getConnection(url);
                Statement st=conn.createStatement();
            //System.out.println("----> "+conn.toString());  
          int rs=st.executeUpdate("insert into Employee (FirstName,LastName,Address) values ('"+fName+"','"+lName+"','"+addr+"')");
             x=rs; 
            } catch (Exception ex) {
                ex.printStackTrace();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Added</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(x+" rows affected");
            out.println("</body>");
            out.println("</html>");
            out.close();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        }

    abulseed wrote:
    if(!(fName.equals(null) && lName.equals(null) && addr.equals(null))){
    Is this line 37?
    If so, if any of fName, lName or addr are null you will get a NullPointerException.
    This is not how you check whether something is null.
    Use '=='.

  • Oracle Agent Manager throwing java.lang.NullPointerException.

    Hi folks,
    When i am trying to execute the test scripts on my machine, after adding it in test manager. The agent service on the client machine is throwing up the below error message.
    As the scripts are EBS scripts, I am using command line for invoking the JVM. I am able to run the scripts on the server machine successfully using the same command line.
    C:\OracleATS\agentmanager\bin\AgentManagerService.exe -c C:\OracleATS\agentmanager\bin\AgentManagerService.conf
    Error:
    wrapper | --> Wrapper Started as Console
    wrapper | Launching a JVM...
    jvm 1 | Wrapper (Version 3.0.3)
    jvm 1 |
    jvm 1 | java.lang.NullPointerException
    jvm 1 | at oracle.oats.empstart.Messenger.endConnection(Messenger.java:1
    59)
    jvm 1 | at oracle.oats.empstart.EmpStartMain.<init>(EmpStartMain.java:51
    3)
    jvm 1 | at oracle.oats.empstart.EmpStartMain.main(EmpStartMain.java:392)
    jvm 1 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    jvm 1 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAcces
    sorImpl.java:39)
    jvm 1 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMet
    hodAccessorImpl.java:25)
    jvm 1 | at java.lang.reflect.Method.invoke(Method.java:597)
    jvm 1 | at org.tanukisoftware.wrapper.WrapperSimpleApp.run(WrapperSimple
    App.java:105)
    jvm 1 | at java.lang.Thread.run(Thread.java:662)
    Regards,
    Nishant

    Yes, you do that...

  • Persistence.getPersistenceUtil().isLoaded method throws java.lang.NullPointerException

    Why the java.lang.NullPointerException exception occurs when J call Persistence.getPersistenceUtil().isLoaded(entityA, "list") method for multitenant entities?
    @Entity
    @Table(name = "entity_a")
    @Multitenant(MultitenantType.TABLE_PER_TENANT)
    @TenantTableDiscriminator(type= TenantTableDiscriminatorType.SCHEMA)
    public class EntityA implements Serializable {
        @OneToMany(cascade = CascadeType.ALL,
                mappedBy = "ea",
                fetch = FetchType.LAZY)
        private List<EntityB> list= new ArrayList<EntityB>();
    @Entity
    @Table(name = "entity_b")
    @Multitenant(MultitenantType.TABLE_PER_TENANT)
    @TenantTableDiscriminator(type= TenantTableDiscriminatorType.SCHEMA)
    public class EntityB implements Serializable {
    @JoinColumns({...})
        @ManyToOne
        private EntityA ea;
    Main.java
    EntityManager em = Persistence.createEntityManagerFactory("PersistenceUnit")
                    .createEntityManager();
            em.getTransaction().begin();
            em.setProperty(
                    EntityManagerProperties.MULTITENANT_PROPERTY_DEFAULT,
                    "schema"
        EntityA entityA = em.find(EntityA.class, "1");
            Persistence.getPersistenceUtil().isLoaded(entityA, "list");
            em.getTransaction().commit();
    Exception in thread "main" Local Exception Stack:
    Exception [EclipseLink-69] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DescriptorException
    Exception Description: A NullPointerException was thrown while extracting a value from the instance variable [list] in the object [jpatest.EntityA].
    Internal Exception: java.lang.NullPointerException
    Mapping: org.eclipse.persistence.mappings.OneToManyMapping[otherTaxableIncomeItemList]
    Descriptor: RelationalDescriptor(jpatest.EntityA --> [DatabaseTable(entity_a)])
        at org.eclipse.persistence.exceptions.DescriptorException.nullPointerWhileGettingValueThruInstanceVariableAccessor(DescriptorException.java:1275)
        at org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor.getAttributeValueFromObject(InstanceVariableAttributeAccessor.java:88)
        at org.eclipse.persistence.mappings.DatabaseMapping.getAttributeValueFromObject(DatabaseMapping.java:579)
        at org.eclipse.persistence.mappings.ForeignReferenceMapping.getAttributeValueFromObject(ForeignReferenceMapping.java:974)
        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.isLoaded(EntityManagerFactoryImpl.java:172)
        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.isLoaded(EntityManagerFactoryImpl.java:153)
        at org.eclipse.persistence.jpa.PersistenceProvider.isLoadedWithReference(PersistenceProvider.java:439)
        at javax.persistence.Persistence$1.isLoaded(Persistence.java:83)
        at jpatest.JPATest.main(JPATest.java:45)
    Caused by: java.lang.NullPointerException
        at org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor.getAttributeValueFromObject(InstanceVariableAttributeAccessor.java:76)
        ... 7 more
    Java Result: 1
    Thank you, Dragan.

    I have found the bug. Thx ^o^

  • Throwing java.lang.NullPointerException

    Hi there.
    In many code samples and throughout the JDK you can find the following kind of code:
    public void doSomething(Object arg) {
        if (arg == null) {
            throw new NullPointerException("arg is null");
        // now do something
    }This is bad coding style in my opinion. If a parameter is passed to a method which violates the methods "contract with the caller" an IllegalArgumentException (or a subclass) should be thrown - since it is an illegal argument. A NullPointerException should just be thrown by the JVM if a null is dereferenced in some way.
    I would rather need an
    public class IllegalNullArgumentException extends IllegalArgumentExceptionYour opinions?
    Klaus

    Yes, you do that...

  • Urgent :-Need Help in DOtnet Dll integration with CFM 8. for error "java.lang.NullPointerException"

    Hi Everyone,
    I am trying to intergrate Dotnet DLL with coldfusion. The basic perpose of this DLL is putting value in cache.
    My code is working fine on my local machine but it giving me problem on live server.
    It is throwing "java.lang.NullPointerException" error.
    Description of task:-
    DLL:-
    made in : Dotnet 3.0
    Functions:-
    setCache:- setting a string into cache.
    getCache:- getting value from cache.
    ClearCache:- Clearing all value from Cache.
    Local Machine:-
    OS: window server 2003
    Coldfusion version :MX8
    coldfusion Product level:-Developer
    Result:-Task is working fine.No error what so ever.
    Live server:-
    OS: window server 2003
    Coldfusion version :MX8
    coldfusion Product level:-Standred
    Result:-Task is throwing error "java.lang.NullPointerException"

    Thanks for your response, but surely if the .NET Services was not running how can CF instantiate and dump the object with all the correct methods?
    Anyway for some strange reason there is no Coldfusion .NET service in my services control panel even though I am running CF8. I have since downloaded the .NET service installer, run it and done a restart but I can still see no such service and the error continues?
    I am running CF8 Dev on IIS 6 – Window XP pro and here is debug
    java.lang.NullPointerException
                   at com.jnbridge.jnbcore.clientTransports.d$b.close(Unknown Source)
                   at java.net.Socket.<init>(Socket.java:368)
                   at java.net.Socket.<init>(Socket.java:209)
                   at com.jnbridge.jnbcore.clientTransports.d$b.<init>(Unknown Source)
                   at com.jnbridge.jnbcore.clientTransports.d.if(Unknown Source)
                   at com.jnbridge.jnbcore.clientTransports.c.a(Unknown Source)
                   at com.jnbridge.jnbcore.clientTransports.f.a(Unknown Source)
                   at com.jnbridge.jnbcore.DotNetSideProxy.int(Unknown Source)
                   at com.jnbridge.jnbcore.DotNetSideProxy.getObjectStaticProperty(Unknown Source)
                   at System.Environment.Get_CurrentDirectory()
                   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
                   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
                   at java.lang.reflect.Method.invoke(Method.java:597)
                   at coldfusion.runtime.java.JavaProxy.invoke(JavaProxy.java:87)
                   at coldfusion.runtime.dotnet.DotNetProxy.invoke(DotNetProxy.java:38)
                   at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:2272)
                   at cftestDotNet2ecfm215937280.runPage(C:\Inetpub\wwwroot\his_clothing\testDotNet.cfm:20)
                   at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196)
                   at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370)
                   at coldfusion.filter.CfincludeFilter.invoke(CfincludeFilter.java:65)
                   at coldfusion.filter.ApplicationFilter.invoke(ApplicationFilter.java:273)
                   at coldfusion.filter.MonitoringFilter.invoke(MonitoringFilter.java:40)
                   at coldfusion.filter.PathFilter.invoke(PathFilter.java:86)
                   at coldfusion.filter.LicenseFilter.invoke(LicenseFilter.java:27)
                   at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:70)
                   at coldfusion.filter.BrowserDebugFilter.invoke(BrowserDebugFilter.java:74)
                   at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:28)
                   at coldfusion.filter.BrowserFilter.invoke(BrowserFilter.java:38)
                   at coldfusion.filter.NoCacheFilter.invoke(NoCacheFilter.java:46)
                   at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38)
                   at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22)
                   at coldfusion.CfmServlet.service(CfmServlet.java:175)
                   at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89)
                   at jrun.servlet.FilterChain.doFilter(FilterChain.java:86)
                   at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42)
                   at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46)
                   at jrun.servlet.FilterChain.doFilter(FilterChain.java:94)
                   at jrun.servlet.FilterChain.service(FilterChain.java:101)
                   at jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106)
                   at jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42)
                   at jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286)
                   at jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543)
                   at jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203)
                   at jrunx.scheduler.ThreadPool$DownstreamMetrics.invokeRunnable(ThreadPool.java:320)
                   at jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428)
                   at jrunx.scheduler.ThreadPool$UpstreamMetrics.invokeRunnable(ThreadPool.java:266)
                   at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)

  • Java.lang.NullPointerException at org.apache.struts.taglib.tiles.InsertTag

    I am using tiles with JSF.
    my starting page is template.jsp which is like this..
    <f:view>
    <f:subview id="header">
    <tiles:insert attribute="header" flush="false"/>
    </f:subview>
    <f:subview id="menu">
    <tiles:insert attribute="menu" flush="false"/>
    </f:subview>
    </f:view>
    when ever the page is rendered, im not getting the value for attribute header or content. its throwing java.lang.NullPointerException at org.apache.struts.taglib.tiles.InsertTag.processAttribute(InsertTag.java:689)
    Below is my faces-config.xml
    <?xml version="1.0"?>
    <!DOCTYPE faces-config PUBLIC
    "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
    "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
    <faces-config>
    <application>
    <view-handler>org.apache.myfaces.application.jsp.JspTilesViewHandlerImpl</view-handler>
    </application>
    </faces-config>
    Below is my web.xml
    <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <init-param>
    <param-name>javax.faces.application.CONFIG_FILES</param-name>
    <param-value>/ApplianceMgr/conf/faces-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
    <servlet-name>Tiles Servlet</servlet-name>
    <servlet-class>org.apache.struts.tiles.TilesServlet</servlet-class>
    <init-param>
    <param-name>tiles-definitions</param-name>
    <param-value>/ApplianceMgr/conf/tiles.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
    </servlet>
    <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
    </context-param>
    Below is my tiles.xml
    <tiles-definitions>
    <definition name="main.template" path="/template/template.jsp" >
    <put name="header" value="test from template" />
    <put name="menu" value="test from template" />
    </definition>

    Please post the tiles-config.xml, layout and tiles.
    Please refer
    http://www.oracle.com/technology/pub/articles/vohra_tiles.html

  • Jdev for R12.1.1 fails with java.lang.NullPointerException

    Hi All,
    We upgraded our 11i environment to R12 version 12.1.1
    As mentioned in metalink note 787209.1, I downloaded Patch 8431482 10G Jdeveloper with OA Extension ARU for R12.1.1 and followed all the setup steps.
    When I run the Tutorial.jpr, the page is throwing java.lang.NullPointerException. I tried this on 3 different dev boxes and am getting the same error.
    Wondering if any one was able to successfully install this version of Jdeveloper (Jdeveloper: Studio Edition Version 10.1.3.3.0.3,
    Build JDEVADF_10.1.3.3.0_NT_RELEASE)
    I made sure that:
    1) The user account has got OA Framework ToolBox Tutorial and OA Framework ToolBox Tutorial Labs responsibility attached to it.
    2) There is no problem with the database connection.
    3) Preferences --> Embeded oc4j and the Default Local IP Address is checked
    4) Am using updated DBC file and removed "/" from DBC file.
    Error Message
    =========
    You have encountered an unexpected error. Please contact the System Administrator for assistance
    =========
    Exception Details.
    oracle.apps.fnd.framework.OAException: Application: FND, Message Name: FND_GENERIC_MESSAGE. Tokens: MESSAGE = java.lang.NullPointerException;
         at oracle.apps.fnd.framework.OAException.wrapperException(Unknown Source)
         at oracle.apps.fnd.framework.CreateIcxSession.getEncryptedSessId(Unknown Source)
         at oracle.apps.fnd.framework.CreateIcxSession.createSession(Unknown Source)
         at test_fwktutorial._jspService(_test__fwktutorial.java:74)
         at com.orionserver.http.OrionHttpJspPage.service(OrionHttpJspPage.java:59)
         at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:462)
         at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:594)
         at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:518)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:713)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:370)
         at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:871)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:453)
         at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:221)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:122)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:111)
         at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
         at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(ServerSocketAcceptHandler.java:239)
         at oracle.oc4j.network.ServerSocketAcceptHandler.access$700(ServerSocketAcceptHandler.java:34)
         at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(ServerSocketAcceptHandler.java:880)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:298)
         at java.lang.Thread.run(Thread.java:595)
    ## Detail 0 ##
    java.lang.NullPointerException
         at oracle.apps.fnd.security.SessionManager.recordSuccess(SessionManager.java:3820)
         at oracle.apps.fnd.security.SessionManager.validateLogin(SessionManager.java:2082)
         at oracle.apps.fnd.security.SessionManager.validateLogin(SessionManager.java:1946)
         at oracle.apps.fnd.framework.CreateIcxSession.getEncryptedSessId(Unknown Source)
         at oracle.apps.fnd.framework.CreateIcxSession.createSession(Unknown Source)
         at test_fwktutorial._jspService(_test__fwktutorial.java:74)
         at com.orionserver.http.OrionHttpJspPage.service(OrionHttpJspPage.java:59)
         at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:462)
         at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:594)
         at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:518)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:713)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:370)
         at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:871)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:453)
         at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:221)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:122)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:111)
         at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
         at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(ServerSocketAcceptHandler.java:239)
         at oracle.oc4j.network.ServerSocketAcceptHandler.access$700(ServerSocketAcceptHandler.java:34)
         at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(ServerSocketAcceptHandler.java:880)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:298)
         at java.lang.Thread.run(Thread.java:595)
    java.lang.NullPointerException
         at oracle.apps.fnd.security.SessionManager.recordSuccess(SessionManager.java:3820)
         at oracle.apps.fnd.security.SessionManager.validateLogin(SessionManager.java:2082)
         at oracle.apps.fnd.security.SessionManager.validateLogin(SessionManager.java:1946)
         at oracle.apps.fnd.framework.CreateIcxSession.getEncryptedSessId(Unknown Source)
         at oracle.apps.fnd.framework.CreateIcxSession.createSession(Unknown Source)
         at test_fwktutorial._jspService(_test__fwktutorial.java:74)
         at com.orionserver.http.OrionHttpJspPage.service(OrionHttpJspPage.java:59)
         at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:462)
         at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:594)
         at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:518)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:713)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:370)
         at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:871)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:453)
         at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:221)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:122)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:111)
         at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
         at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(ServerSocketAcceptHandler.java:239)
         at oracle.oc4j.network.ServerSocketAcceptHandler.access$700(ServerSocketAcceptHandler.java:34)
         at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(ServerSocketAcceptHandler.java:880)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:298)
         at java.lang.Thread.run(Thread.java:595)
    Thanks
    Suman.

    Just an update:
    I was able to successfully setup and run the earlier version of Jdev from "Patch 7523554 10G Jdeveloper With OA Extension ARU for R12 RUP6" against R12.1.1.
    I still am getting the same error when I try to reinstall "Patch 8431482 10G Jdeveloper with OA Extension ARU for R12.1.1".
    Hoping to hear from anyone out there who has R12.1.1 and is able to run 8431482 Jdev.
    Also is there any downside in using Jdev for R12.0.6 against R12.1.1?

  • ServletFileUpload java.lang.NullPointerException

    Hi
    I have a File upload on a jsp page, if I do not upload and press submit, it throws java.lang.NullPointerException
    I use
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if(isMultipart)
    then upload file
    Can ServletFileUpload == null then redirect to another jsp page?

    See the link: http://www.jguru.com/faq/view.jsp?EID=160

  • Java.lang.NullPointerException when trying to compile

    Hi everybody!
    I'm trying to compile a file using javax.tools.JavaCompiler but I get a java.lang.NullPointerException when running the program.
    Here is my code:
    public boolean CompExecFile(File filename){
              boolean compRes = false;
              try {
                   System.out.println(filename.getAbsolutePath());
                   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
                   StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); //line where I get the error
                   Iterable<? extends JavaFileObject> compilationUnits2 = fileManager.getJavaFileObjects(filename);
                   compRes = compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();
                   fileManager.close();
                 if (compRes) {
                     System.out.println ("Compilation was successful");
                 } else {
                     System.out.println ("Compilation failed");
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return compRes;
         }There error on the line "StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);":
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException+
    I've seen several examples using the parameters "null,null,null" but I don't know if it's good :(
    Many thanks for your help.

    I've found something which could maybe be what I need to do but I'm not sure:
    // Build a new ClassLoader using the given URLs, replace current Classloader
    ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
    ClassLoader newCL = new URLClassLoader(myClasspathURLs, oldCL);
    Thread.currentThread().setContextClassLoader(newCL);
    System.out.println("Successfully replaced ClassLoader");
    Class fooClass = newCL.loadClass(appClass); //which replaces the line "Class<?> tempFileClass = Class.forName("TempFile");" ?!Is that what I need to do?
    EDIT: I've tried that but I still have the same problem:
                      File classFile = new File ("TempFile.class");
                      ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
                      ClassLoader newCL = new URLClassLoader(new URL[] {classFile.toURL()}, oldCL);
                      Thread.currentThread().setContextClassLoader(newCL);
                      System.out.println("Successfully replaced ClassLoader");
                      Class tempFileClass = newCL.loadClass("TempFile");
                      Method main = tempFileClass.getMethod("main", String[].class);
                      main.invoke(null,new String[0]); Edited by: Foobrother on Jul 28, 2008 8:18 AM

  • About  java.lang.NullPointerException in struts code

    Hi friends...
    I am working on the java struts in my healthcare project.I have used the following IDEs & environments
    1) Eclipse
    2) Tomcat 5.5
    3) Servlet 2.4
    I have created all the necessary jsp files & action ,form classes but i can't get my code compiled
    Also i obtainned a sample source code of File Upload in struts.But it don't get compiled
    The content of my struts-config.xml file is as follows
    <form-beans>
    <form-bean name="FileUpload" type="India.Beans.StrutsUploadForm"/>
    </form-beans>
    <global-forwards>
    </global-forwards>
    <!-- Upload Action Mapping -->
    <action-mappings>
    <action path="/FileUpload" type="India.Beans.StrutsUploadAction" name="FileUpload" scope="request" validate="true" input="/pages/FileUpload.jsp">
    <forward name="success" path="/pages/uploadsuccess.jsp">
    </forward>
    </action>
    </action-mappings>
    it shows exception as
    java.lang.NullPointerException
    So please guide me ..

    hi,
        If you are loading a resource (property) file from a jar file you can use
    getResourceAsStream("com/test/test.properties").
        if the propery file is in outside of your jar file . you can use
    Property portalProps = new Property ();
    try {
                   FileInputStream fileInputStream = new FileInputStream("<FilePath + FileName>");
                   portalProps.load(fileInputStream);
                   fileInputStream.close();
              } catch (IOException e) {
                   //Log the error
    refer the following link for more details
    http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

  • Java.lang.NullPointerException   in the code to read a properties file

    I have written the following code to read a properties file...........
    <b>
    public Property(String fileName)
        try
           InputStream is = MyClassName.class.getClass().getClassLoader().getResourceAsStream(fileName);     
           prop.load(is);
           is.close();
        catch (Exception ex)
            System.out.println("The Exception is:        " + ex.getMessage());
            ex.printStackTrace();
    </b>
    But this code is giving <b> java.lang.NullPointerException </b> at <b> prop.load(is) </b>
    please help me....
    regards
    Brahmachaitanya

    hi,
        If you are loading a resource (property) file from a jar file you can use
    getResourceAsStream("com/test/test.properties").
        if the propery file is in outside of your jar file . you can use
    Property portalProps = new Property ();
    try {
                   FileInputStream fileInputStream = new FileInputStream("<FilePath + FileName>");
                   portalProps.load(fileInputStream);
                   fileInputStream.close();
              } catch (IOException e) {
                   //Log the error
    refer the following link for more details
    http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

  • Reply activity throwing a java.lang.NullPointerException

    I have a synchronous process that includes a FileAdapter read. When the FileAdapter finds the file to read, the process is kicked off. If the process errors out, I call a Reply activity to the client to end the process. My Reply activity throws a "java.lang.NullPointerException", even when I assign a value to it's variable.
    Is this because the "client" is never instantiated because the process is kicked off by a FileAdapter and not from a call to the client?
    Can anyone help me? This is rather important...
    I'm using v. 10.1.3.1

    I am using the fault handlers.
    I've since solved my problem, though. There was no reason I needed a Reply activity to begin with. My problem was, I was validating, then when the validation failed, i wanted a database table to be updated and then have the process quit. I was trying to use a Reply activity to automatically end the process, but the Reply was throwing the "nullPointerException" which was then caught by my fault handlers, and the afore mentioned database was updated again, which it shouldn't have been. I believe the problem, though, was that since my process was being kicked off from a FileAdapter and not the client, when I tried to reply to the client, it simply wasn't there.
    So in the end, i don't need the Reply activity at all. Basically, it was lousy logic on my part.
    Thank you for your reply though. I'm grateful for the suggestiion.

  • Java.lang.NullPointerException throwed when doing Hibernate Persistence

    Im using Hibernate3.
    I am trying to add a record of "orderdetail", also setting its many-2-one association "order", which include a many-2-one association with "employer".
    Mycode is:
    public class OrderdetailDaoTest {
       public static void main(String[] args) {
          // TODO Auto-generated method stub
          try{
             Orderdetails vo = new Orderdetails();
             IOrdersDAO orderdao = new OrdersDAO();
             Integer orderid = new Integer("1");
             System.out.println("orderid is "+orderid.intValue());
             Orders order = (Orders)orderdao.getOrderByid(orderid);
             vo.setOrders(order);
             IEmployeesDAO eedao = new EmployeesDAO();
             Integer eeid = new Integer("1");
             Employees employee = eedao.getEmployeeByid(eeid);
             vo.setEmployees(employee);
             Calendar startdate = Calendar.getInstance();
             startdate.set(2007, 5, 15);
             //System.out.println("time is "+startdate.getTime());
             vo.setStartDate(startdate.getTime());
             Calendar enddate = Calendar.getInstance();
             startdate.set(2007, 6, 15);
             //System.out.println("time is "+enddate.getTime());
             vo.setEndDate(enddate.getTime());
             Calendar arrdate = Calendar.getInstance();
             arrdate.set(2007, 6, 16);
             //System.out.println("time is "+arrdate.getTime());
             vo.setArrivalDate(arrdate.getTime());
             vo.setArrivalStatus("Experienced Named");
             Calendar repatdate = Calendar.getInstance();
             repatdate.set(2007, 7, 16);
             //System.out.println("time is "+arrdate.getTime());
             vo.setRepatDate(repatdate.getTime());
             vo.setRepatStatus("Other");
             vo.setTransferStatus("Named Transfer");
             Calendar transferdate = Calendar.getInstance();
             transferdate.set(2007, 7, 1);
             //System.out.println("time is "+arrdate.getTime());
             vo.setDateTransferred(transferdate.getTime());
             vo.setNotes("This is a long test note!");
             IArrivalmanifesttblDAO arrivaldao = new ArrivalmanifesttblDAO();
             Arrivalmanifesttbl arrival = arrivaldao.getArrivalByAMNO("am01");
             vo.setArrivalmanifest(arrival);
             IRepatmanifesttblDAO repatdao = new RepatmanifesttblDAO();
             Repatmanifesttbl repat = repatdao.getRepatByRMNO("rm01");
             vo.setRepatmanifest(repat);
             vo.setRepatDetail("This is long test repat detail!");
             vo.setIncludeInArrivalManifest(new Byte("0"));
             vo.setIncludeInRepatManifest(new Byte("0"));
             vo.setTransferred(new Byte("1"));
             vo.setDelete(new Byte("0"));
             vo.setSno(new Short("100"));
             IOrderdetailsDAO dao = new OrderdetailsDAO();
             dao.add(vo);
          catch(ApplicationException e){
             e.getStackTrace();
             System.out.println("Exception throwed!");
    }The stack print like following:
    Exception in thread "main" java.lang.NullPointerException
       at com.farm.vo.Employers.hashCode(Employers.java:270)
       at com.farm.vo.Orders.hashCode(Orders.java:168)
       at java.util.HashMap.put(Unknown Source)
       at java.util.HashSet.add(Unknown Source)
       at java.util.AbstractCollection.addAll(Unknown Source)
       at org.hibernate.collection.PersistentSet.endRead(PersistentSet.java:273)
       at org.hibernate.engine.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:183)
       at org.hibernate.engine.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:268)
       at org.hibernate.engine.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:249)
       at org.hibernate.loader.Loader.endCollectionLoad(Loader.java:866)
       at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:853)
       at org.hibernate.loader.Loader.doQuery(Loader.java:717)
       at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
       at org.hibernate.loader.Loader.loadCollection(Loader.java:1919)
       at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:36)
       at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:520)
       at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:60)
       at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1676)
       at org.hibernate.collection.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:454)
       at org.hibernate.engine.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:755)
       at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:229)
       at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
       at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
       at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
       at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
       at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
       at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
       at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
       at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:177)
       at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:87)
       at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
       at org.hibernate.impl.SessionImpl.get(SessionImpl.java:799)
       at org.hibernate.impl.SessionImpl.get(SessionImpl.java:792)
       at com.farm.dao.OrdersDAO.getOrderByid(OrdersDAO.java:98)
       at com.farm.unitTest.daotest.OrderdetailDaoTest.main(OrderdetailDaoTest.java:33)The mapping file for orderdetail is like:
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!--
        Mapping file autogenerated by MyEclipse - Hibernate Tools
    -->
    <hibernate-mapping>
        <class name="com.farm.vo.Orderdetails" table="orderdetails" catalog="llbv1" lazy="false">
            <id name="orderDetailId" type="java.lang.Integer">
                <column name="OrderDetailID" />
                <generator class="native" />
            </id>
            <many-to-one name="employees" class="com.farm.vo.Employees"  lazy="false">
                <column name="EmployeeID" />
            </many-to-one>
            <many-to-one name="orders" class="com.farm.vo.Orders" lazy="false">
                <column name="OrderID" />
            </many-to-one>
            <many-to-one name="repatmanifest" class="com.farm.vo.Repatmanifesttbl" cascade="all" lazy="false">
                <column name="RepatManifestNo" length="50" />
            </many-to-one>
            <many-to-one name="arrivalmanifest" class="com.farm.vo.Arrivalmanifesttbl" cascade="all" lazy="false">
                <column name="ArrivalManifestNo" length="50" />
            </many-to-one>
            <property name="startDate" type="java.util.Date">
                <column name="StartDate" length="19" />
            </property>
            <property name="endDate" type="java.util.Date">
                <column name="EndDate" length="19" />
            </property>
            <property name="arrivalDate" type="java.util.Date">
                <column name="ArrivalDate" length="19" />
            </property>
            <property name="arrivalStatus" type="java.lang.String">
                <column name="ArrivalStatus" length="21" />
            </property>
            <property name="repatDate" type="java.util.Date">
                <column name="RepatDate" length="19" />
            </property>
            <property name="repatStatus" type="java.lang.String">
                <column name="RepatStatus" length="18" />
            </property>
            <property name="transferStatus" type="java.lang.String">
                <column name="TransferStatus" length="16" />
            </property>
            <property name="dateTransferred" type="java.util.Date">
                <column name="DateTransferred" length="19" />
            </property>
            <property name="notes" type="java.lang.String">
                <column name="Notes" />
            </property>
            <property name="repatDetail" type="java.lang.String">
                <column name="RepatDetail" />
            </property>
            <property name="includeInArrivalManifest" type="java.lang.Byte">
                <column name="IncludeInArrivalManifest" />
            </property>
            <property name="includeInRepatManifest" type="java.lang.Byte">
                <column name="IncludeInRepatManifest" />
            </property>
            <property name="transferred" type="java.lang.Byte">
                <column name="Transferred" />
            </property>
            <property name="iomRemarks" type="java.lang.String">
                <column name="IOM_Remarks" />
            </property>
            <property name="observations" type="java.lang.String">
                <column name="Observations" />
            </property>
            <property name="mitigatingFactors" type="java.lang.String">
                <column name="MitigatingFactors" />
            </property>
            <property name="delete" type="java.lang.Byte">
                <column name="isDelete" />
            </property>
            <property name="employeeRemarks" type="java.lang.String">
                <column name="EmployeeRemarks" />
            </property>
            <property name="nbstatus" type="java.lang.String">
                <column name="NBStatus" length="50" />
            </property>
            <property name="sno" type="java.lang.Short">
                <column name="SNo" />
            </property>
            <property name="userComment" type="java.lang.String">
                <column name="UserComment" />
            </property>
        </class>
    </hibernate-mapping>I am stuck with this problem for several days. Any seggestion is appreciated!
    Thanks in advance.

    It seems that the exception throwed on the hashcode() for NULL value field include in the association.... The many-2-one assciation is bidirectional, by the way.
    Is my hibernate mapping file somewhere implicitly restrict the association fields can not be NULL? If it is, can somebody tells me where?
    Following is "orderdetail"'s bidirectinal association definition, "order" mapping file:
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!--
        Mapping file autogenerated by MyEclipse - Hibernate Tools
    -->
    <hibernate-mapping>
        <class name="com.farm.vo.Orders" table="orders" catalog="llbv1">
            <id name="orderId" type="java.lang.Integer">
                <column name="OrderID" />
                <generator class="native" />
            </id>
            <many-to-one name="employer"  class="com.farm.vo.Employers" lazy="false">
                <column name="EmployerID"/>
            </many-to-one>
            <property name="hrdcorderCode" type="java.lang.String">
                <column name="HRDCOrderCode" length="50" />
            </property>
            <property name="farmsorderCode" type="java.lang.String">
                <column name="FARMSOrderCode" length="50" />
            </property>
            <property name="orderDate" type="java.util.Date">
                <column name="OrderDate" length="19" />
            </property>
            <property name="startDate" type="java.util.Date">
                <column name="StartDate" length="19" />
            </property>
            <property name="endDate" type="java.util.Date">
                <column name="EndDate" length="19" />
            </property>
            <property name="orderType" type="java.lang.String">
                <column name="OrderType" length="20" not-null="true" />
            </property>
            <property name="noOfWorker" type="java.lang.Short">
                <column name="NoOfWorker" />
            </property>
            <property name="orderStatus" type="java.lang.String">
                <column name="OrderStatus" length="12" />
            </property>
            <property name="notes" type="java.lang.String">
                <column name="Notes" />
            </property>
            <set name="orderdetails" inverse="true" cascade="all-delete-orphan" lazy="false">
               <key column="OrderId"/>
             <one-to-many class="com.farm.vo.Orderdetails"/>
          </set>
        </class> Thank you!

Maybe you are looking for

  • Windows 8.1 laptop running slow, high memory and disk utilization

    When I restart my laptop its memory utilization is around 50%. If I run several programs(may be 2 or 3) like Internet browser and IDE like Netbeans my pc become very slow. When I was working in my other laptop which runs Windows 7(with 4GB RAM) I nev

  • Connect to two wireless networks simultaneously

    Here's the scenario: I would like to have my airport express connect to my stereo and I'd like to have my mac connect to that via air tunes while at the same time connecting to a time capsule or other wireless router for internet use and have them bo

  • .wmv into FCP back to .wmv - best workflow with Flip4Mac?

    Apologies if this has been asked before, can't find a specific answer to this. My client has provided a .wmv (windows media video 9) source file that needs to be edited. The client needs the final format to also be .wmv with the WMV9 codec. I've down

  • Where is download for acrobat 9 standard

    I am having to reinstall acrobat 9 standard and cannot locate the file on the website.

  • Missing Web Service Input Parameters

    Hi, I am creating a form on web services. The source of the webservice is BEPL. When I register the webservice, I see the in and the out parameters. Operations       Operation Name     process Input Parameters Operation     Parameter Name     Paramet