JSF JAVA NullPointerException Карта - PullRequest
       2

JSF JAVA NullPointerException Карта

0 голосов
/ 20 ноября 2011

Я пытался отлаживать это часами, но не смог понять, почему это происходит.У меня есть предположение, что карта вернулась null?на самом деле не уверенВот код:

Управляемый компонент FormBean:

package core.smd.classes;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.Date;
import org.joda.time.DateTime;
import java.util.List;
 import java.util.ArrayList;


@ManagedBean
@SessionScoped
public class FormBean {

/** Creates a new instance of FormBean */

int counter=0;
String eventTitle;
Date startDate;
Date endDate;
String requestType;
String trainingOption;
String projectOption;
int terminals;
String lastName;
String firstName;
String middleInitials;
int badgeNo;
String networkID;
String telephoneNo;
String orgCode;
String orgName;
String justification;

public FormBean(){

}

public String getEventTitle() {
    return eventTitle;
}

public void setEventTitle(String eventTitle) {
    this.eventTitle = eventTitle;
}

public Date getEndDate() {
    return endDate;
}

public void setEndDate(Date endDate) {
    this.endDate = endDate;

}

public Date getStartDate() {
    return startDate;
}

public void setStartDate(Date startDate) {
    this.startDate = startDate;

}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getMiddleInitials() {
    return middleInitials;
}

public void setMiddleInitials(String middleInitials) {
    this.middleInitials = middleInitials;
}

public String getRequestType() {
    return requestType;
}

public void setRequestType(String requestType) {
    this.requestType = requestType;
}

public int getTerminals() {
    return terminals;
}

public void setTerminals(int terminals) {
    this.terminals = terminals;
}

public String getProjectOption() {
    return projectOption;
}

public void setProjectOption(String projectOption) {
    this.projectOption = projectOption;
}

public String getTrainingOption() {
    return trainingOption;
}

public void setTrainingOption(String trainingOption) {
    this.trainingOption = trainingOption;
}

public int getBadgeNo() {
    return badgeNo;
}

public void setBadgeNo(int badgeNo) {
    this.badgeNo = badgeNo;
}

public String getJustification() {
    return justification;
}

public void setJustification(String justification) {
    this.justification = justification;
}

public String getNetworkID() {
    return networkID;
}

public void setNetworkID(String networkID) {
    this.networkID = networkID;
}

public String getOrgCode() {
    return orgCode;
}

public void setOrgCode(String orgCode) {
    this.orgCode = orgCode;
}

public String getOrgName() {
    return orgName;
}

public void setOrgName(String orgName) {
    this.orgName = orgName;
}

public String getTelephoneNo() {
    return telephoneNo;
}

public void setTelephoneNo(String telephoneNo) {
    this.telephoneNo = telephoneNo;
}

public String createInstance(){
    Reservation rsv = new Reservation();
    boolean success = rsv.checkRange();
    counter = rsv.counter;
    if(success == true)
        return "Successful";
    else
        return "Failed!";
}

}

Тогда вот класс резервирования:

package core.smd.classes;


import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.Map;

import org.joda.time.DateTime;


public class Reservation {



public int counter;
String eventTitle;
public Date startDate;
public Date endDate;
String requestType;
public int terminals;
String lastName;
String firstName;
String middleInitials;
int badgeNo;
String networkID;
String telephoneNo;
String orgCode;
String orgName;
String trainingOption;
String projectOption;
String justification;
public TreeMap<DateTime, Integer> map = new TreeMap<DateTime, Integer>();

public Reservation(String eventTitle, Date startDate, Date endDate, String requestType, int
terminals, String lastName, String firstName, String middleInitials, int badgeNo, String
networkID, String telephoneNo, String orgCode, String trainingOption, String justification) {
    this.eventTitle = eventTitle;
    this.startDate = startDate;
    this.endDate = endDate;
    this.requestType = requestType;
    this.terminals = terminals;
    this.lastName = lastName;
    this.firstName = firstName;
    this.middleInitials = middleInitials;
    this.badgeNo = badgeNo;
    this.networkID = networkID;
    this.telephoneNo = telephoneNo;
    this.orgCode = orgCode;
    this.trainingOption = trainingOption;
    this.justification = justification;
}

public Date getEndDate() {
    return endDate;
}

public void setEndDate(Date endDate) {
    this.endDate = endDate;
}
public Reservation(){

}
public Date getStartDate() {
    return startDate;
}

public void setStartDate(Date startDate) {
    this.startDate = startDate;
}


//generate all dates for the year
public  List<DateTime> getDateRange(DateTime start, DateTime end)
{  
    List<DateTime> ret = new ArrayList<DateTime>();
    DateTime tmp = start;
    while(tmp.isBefore(end) || tmp.equals(end)) {
        ret.add(tmp);
        tmp = tmp.plusDays(1);
    }
    return ret;
}


/*This function iterates through the list of dates and store them
 in the TreeMap for further use*/
public TreeMap<DateTime, Integer> getDatesTreeMap()
{

   // List<DateTime> dateList = new ArrayList<DateTime>();
    DateTime startx = new DateTime(startDate.getTime());
    DateTime endx = new DateTime(endDate.getTime());
    //dateList = getDateRange(dateToStart, dateToEnd);

     TreeMap<DateTime, Integer> map = new TreeMap<DateTime, Integer>();


    List<DateTime> between = getDateRange(startx, endx);

    for (DateTime d : between) {
        //System.out.println(" " + d);
        map.put(d, 46);

    }

    for (Map.Entry<DateTime, Integer> entry : map.entrySet())
    {
       System.out.println(entry.getKey() + "/" + entry.getValue());
       counter++;
    }

    return map;
}

/*This function will return the number of elements/keys 
 prouced in the TreeMap hence reflecting the correct
 date generation*/
/*public static int returnCounter()
{
    TreeMap<DateTime, Integer> tree2 = getDatesTreeMap();

    return counter;
}
*/

 public boolean checkRange() {          
        //tree2 is the map containing all the dates
        TreeMap<DateTime, Integer> tree2 = getDatesTreeMap();
        //convert Date instances into DateTime
        DateTime startx = new DateTime(startDate.getTime());
        DateTime endx = new DateTime(endDate.getTime());

        //booking status
        boolean possible = false;
        //variable for testing
        int testValue = 0;
        //Booking type: 1 = Project, 2 = Training
        int bookingType = 1;
        //produces submap

        if(bookingType == 1)
        {
            //Project
            //fetch all values for keys in the map between start and end
                for (Integer capacity : tree2.subMap(startx, endx).values()) {
                    //Provides an insight into capacity accomodation possibility
                    //testValue++;
                    //check if capacity required could be accommodated
                    terminals = 20;
                    if(capacity >= terminals)
                        //yes then its possible, set to true
                        possible = true;
                    else if(capacity < terminals)
                        //not then set it to false
                        possible = false;

                }

                if(possible == true)
                {
                    //if it is possible to accomodate request
                    for (DateTime x : tree2.subMap(startx, endx).keySet()) {
                    {
                        //for dates n, update value for next operation
                        tree2.put(x, tree2.get(x) - terminals);
                    }
                }
                }else{
                 //nothing now
                }
        }else if(bookingType == 2){
            //Training
             for (Integer capacity : tree2.subMap(startx, endx).values()) {
                    //Provides an insight into capacity accomodation possibility
                    //testValue++;
                    terminals = 20;
                    if(capacity >= terminals)
                        possible = true;
                    else if(capacity < terminals)
                        possible = false;

                }

                if(possible == true)
                {
                    for (DateTime x : tree2.subMap(startx, endx).keySet()) {
                    {
                        //46 so that all seats are reserved
                        tree2.put(x, tree2.get(x) - 46);

                    }
                }
                }else{
                 //nothing now
                }

        }


        return possible;
}//end of checkRange method 

//untested method
public boolean freeReservedSeats()
{
    //A reservation instance is passed then deal with freeing the seats

    //variable created to mock reserved seats: Later this will be derived from
    //reservation instance

    int reservedSeats = 10;
    boolean seatsFreed = false;
    TreeMap<DateTime, Integer> tree2 = getDatesTreeMap();
    DateTime startx = new DateTime(startDate.getTime());
    DateTime endx = new DateTime(endDate.getTime());
    //retrieve the map to be updated
    for (DateTime x : tree2.subMap(startx, endx).keySet()) 
    {
                //this will update the dates affected by recovered seats
                tree2.put(x, tree2.get(x)+ reservedSeats);
                seatsFreed = true;
    }

 return seatsFreed;
}
}

согласно странице xhtml, на которую отправляются данные,Я проверил, что все поля попадают на следующую страницу через геттеры и сеттеры.Так что не беспокойтесь ... Показанная здесь ошибка выглядит следующим образом:

java.lang.NullPointerException
at core.smd.classes.Reservation.getDatesTreeMap(Reservation.java:103)
at core.smd.classes.Reservation.checkRange(Reservation.java:140)
at core.smd.classes.FormBean.createInstance(FormBean.java:178)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:467)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246)
at com.sun.el.parser.AstValue.getValue(AstValue.java:111)
at com.sun.el.parser.AstValue.getValue(AstValue.java:163)

Это все, что я получил, и не уверен, почему это происходит :( Заранее спасибо за поддержку

Ответы [ 2 ]

1 голос
/ 20 ноября 2011

Исключение происходит в течение getDatesTreeMap до того, как оно сможет вернуться.

Если мое чтение правильное, проблема должна быть в одной из следующих строк:

DateTime startx = new DateTime(startDate.getTime());
DateTime endx = new DateTime(endDate.getTime());
...
List<DateTime> between = getDateRange(startx, endx);
for (DateTime d : between) {
  • Если startDate равно null, вы получите NPE в первой строке.

  • Если endDate равно null, вы получитеNPE во второй строке.

  • Если getDateRange(...) returns a null`, вы получите NPE в следующем выражении.

Вы можете различитьтри случая, глядя на строку, в которой генерируется исключение ... оно находится в трассировке стека.Как только вы это сделаете, вам нужно выяснить, откуда взялся null.Например, если startDate равно null, это должно быть потому, что:

  • что-то вызывает setStartDate(...) с параметром null, или
  • ничего не вызывает setStartDate(...) на этом Reservation объекте, и он создается с null начальной датой.
1 голос
/ 20 ноября 2011

Исключение возникает в методе getDatesTreeMap. Здесь вы вызываете методы для трех объектов: map, startDate и endDate. Поскольку карта четко инициализируется перед использованием, проверьте, не являются ли значения startDate и / или endDate пустыми внутри этого метода.

Редактировать: из вашего комментария, детализирующего строку 103, я могу сделать вывод, что действительно startDate равно нулю. Проверьте, как вызывается конструктор класса. Вы можете передавать null вместо startDate.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...