Cannot create Java List - java

I want to use this code and create JSF 2.0 table.
This is the Java Code of the Managed bean:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/* include SQL Packages */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// or import javax.faces.bean.ManagedBean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.glassfish.osgicdi.OSGiService;
#Named("ApplicationController")
#SessionScoped
public class Application implements Serializable {
private List<Item> list;
private transient DataModel<Item> model;
private Item item = new Item();
private boolean edit;
#PostConstruct
public void init() {
// list = dao.list();
// Actually, you should retrieve the list from DAO. This is just for demo.
list = new ArrayList<Item>();
list.add(new Item(1L, "item1"));
list.add(new Item(2L, "item2"));
list.add(new Item(3L, "item3"));
}
public void add() {
// dao.create(item);
// Actually, the DAO should already have set the ID from DB. This is just for demo.
item.setId(list.isEmpty() ? 1 : list.get(list.size() - 1).getId() + 1);
list.add(item);
item = new Item(); // Reset placeholder.
}
public void edit() {
item = model.getRowData();
edit = true;
}
public void save() {
// dao.update(item);
item = new Item(); // Reset placeholder.
edit = false;
}
public void delete() {
// dao.delete(item);
list.remove(model.getRowData());
}
public List<Item> getList() {
return list;
}
public DataModel<Item> getModel() {
if (model == null) {
model = new ListDataModel<Item>(list);
}
return model;
}
public Item getItem() {
return item;
}
public boolean isEdit() {
return edit;
}
}
I get this problem when I import the code into Netbeans:
How I can declare the Java list in order to work?
Best wishes
EDIT I edited the code this way:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/* include SQL Packages */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// or import javax.faces.bean.ManagedBean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.glassfish.osgicdi.OSGiService;
#Named("ApplicationController")
#SessionScoped
public class Application implements Serializable {
public Application() {
}
private List<Application> list;
private transient DataModel<Application> model;
private Application item = new Application();
private boolean edit;
private Application(long l, String string) {
throw new UnsupportedOperationException("Not yet implemented");
}
#PostConstruct
public void init() {
// list = dao.list();
// Actually, you should retrieve the list from DAO. This is just for demo.
list = new ArrayList<Application>();
list.add(new Application(1L, "item1"));
list.add(new Application(2L, "item2"));
list.add(new Application(3L, "item3"));
}
public void add() {
// dao.create(item);
// Actually, the DAO should already have set the ID from DB. This is just for demo.
item.setId(list.isEmpty() ? 1 : list.get(list.size() - 1).getId() + 1);
list.add(item);
item = new Application(); // Reset placeholder.
}
public void edit() {
item = model.getRowData();
edit = true;
}
public void save() {
// dao.update(item);
item = new Application(); // Reset placeholder.
edit = false;
}
public void delete() {
// dao.delete(item);
list.remove(model.getRowData());
}
public List<Application> getList() {
return list;
}
public DataModel<Application> getModel() {
if (model == null) {
model = new ListDataModel<Application>(list);
}
return model;
}
public Application getItem() {
return item;
}
public boolean isEdit() {
return edit;
}
private void setId(int i) {
throw new UnsupportedOperationException("Not yet implemented");
}
private int getId() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
Do you see any mistakes?

You have to define the Item class.
UPDATE:
To keep the code in the first form. You should have a Item class.
public class Item {
private long id;
private String name;
public Item() {}
public Item(long id, String name) {
this.id = id;
this.name = name;
}
//getters and setters for the attributes...
}
Now, in your updated code, you're using a list of Application objects. So your Application class should have 2 attributes of long and String type:
//annotations here...
public class Application implements Serializable {
private long id;
private String name;
//getters and setters for these attributes...
public Application() {
//keep your actual code here
}
//we have to add a constructor that receives a long and a String
//to initialize the attributes values.
public Application(long id, String name) {
this.id = id;
this.name = name;
}
//your actual code...
}
Second option is not a good practice, I recommend you separate the Backing Bean (Managed Bean) class from your model classes (in this case, the Item class).

Do not focus on article's code examples only. Read the article's text as well. The text is not written for decoration only :)
The Item class is just a simple model object, its code should be straightforward enough. A Serializable Javabean with two properties Long id and String value, a default constructor and a constructor filling both properties, a bunch of appropriate getters/setters, equals() and hashCode() overriden.
You can almost autogenerate it in its entirety with a bit decent IDE like Eclipse.

From this version of the API, the Item constructor requires a String parameter, which you are not providing. I think your IDE has pulled in that class by accident.
Reading the example from the link in the question I believe you need to supply your own Item class (and import it correctly) which will need a no-argument constructor and one that takes a long and a String.

Related

Getting a method not found in class, when I already have the method declared?

I'm trying to create objects of the classes I have in the main method, I'm implementing the lazy simpleton pattern, but I keep getting the error cannot find symbol in class. I've checked to see if I've written the import package statements correctly as well.
This is my main class
package control;
import java.io.File;
import java.io.FileNotFoundException;
import model.ApplicationModel;
import java.util.* ;
import model.Shop;
import view.ApplicationViewer;
import model.ApplicationModel;
public class ApplicationControl {
public static void main (String[] args) throws FileNotFoundException{
ApplicationModel apm = new ApplicationModel.getInstance();
}
}
This is my Singleton class ApplicationModel
package model;
// needed for ArrayLists
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ApplicationModel {
private static ApplicationModel instance = null;
private ApplicationModel()
{
}
public static ApplicationModel getInstance (){
if (instance == null){
instance = new ApplicationModel();
}
return instance;
}
private List<Shop> shops = new ArrayList<Shop>();
public List<Shop> getShops(){
return this.shops;
}
public void setShops(List<Shop> shops){
this.shops = shops;
}
public Shop createShop(String csvString){
String[] attributes = csvString.split(",");
Shop shop = new Shop(attributes[0],attributes[1],attributes[2],
attributes[3],attributes[4]);
return shop;
}
public List<Shop> readShops(String shopFileName){
ApplicationModel am = new ApplicationModel();
List<Shop> shopList = new ArrayList<>();
try{
Scanner naughty = new Scanner(new File(shopFileName));
if (naughty.hasNext()) naughty.nextLine();
while(naughty.hasNext()){
shopList.add(am.createShop(naughty.nextLine()));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ApplicationModel.class.getName()).log(Level.SEVERE, null, ex);
}
return shopList;
}
public String printShops(){
String listOfShops ="";
for(Shop shop : shops ){
listOfShops = listOfShops +'\n'+ shop.toString().trim() + '\n';
}
return listOfShops.trim();
}
}
Whenever I type in ApplicationModel in the main class, the import statement error stating that the import has not been used goes away too, I'm not sure what's wrong (I'm using netbeans). Can anyone help?
Remove "new" from your code:
ApplicationModel apm = ApplicationModel.getInstance();
Being static, getInstance() is a class method (not an instance method). This syntax is how you call class methods.

GWT RPC array access

I'm writing an application in which data from a text file is saved to the array and late transferred to the widget GWT Highcharts as an array of Number type. I wrote a servlet that writes data from a file into an array, and I'm stuck here. I don't know how to pass the contents of the array to the client part of the application. Is there a quick and easy way to do this?
This code written by me:
DataPointsImpl.java:
package com.pwste.gwt.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.pwste.gwt.client.DataPoints;
public class DataPointsImpl extends RemoteServiceServlet implements DataPoints {
private static final long serialVersionUID = 1L;
#Override
public Number[] getDataPoints() throws IOException {
File dataFile = new File("points.txt");
FileReader dataFileReader = new FileReader(dataFile);
BufferedReader dataBufferedReader = new BufferedReader(dataFileReader);
Number[] arrayNumber = new Number[10000];
String dataString = dataBufferedReader.readLine();
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = Integer.parseInt(dataString);
dataString = dataBufferedReader.readLine();
}
dataBufferedReader.close();
return arrayNumber;
}
}
DataPoints.java:
package com.pwste.gwt.client;
import java.io.IOException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("dataPoints")
public interface DataPoints extends RemoteService {
Number[] getDataPoints() throws IOException;
}
DataPointsAsync.java:
package com.pwste.gwt.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface DataPointsAsync {
void getDataPoints(AsyncCallback<Number[]> callback);
}
You have to use the Async-Interface on the client side:
private DataPointsAsync dataPointsService = GWT.create(DataPoints.class);
you can use the service in this way:
dataPointsService.getDataPoints(AsyncCallback<Number[]>(){
#Override
public void onSuccess(Number[] result) {
// result contains the returning values
}
#Override
public void onFailure(Throwable caught) {
Window.alert("panic");
}
});

JAX-RS / JAXB : equals()

I'm creating a little webservice with JAX-RS and I cannot access to my GET request http://localhost:8080/MyProject/resources/agenda/{jour}
Here is my code :
package com.project.test;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.xml.bind.annotation.*;
#XmlRootElement(name = "activite")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(propOrder = {"but","trancheHoraire", "lieu"})
public class Activite
{
//-----------------------------------------------------------------------------
// #XmlElement(name="nomactivite")
private String but;
private TrancheHoraire trancheHoraire;
private String lieu;
//-----------------------------------------------------------------------------
public Activite(){
}
public Activite(String but,TrancheHoraire trancheHoraire, String lieu)
{
this.but = but;
this.trancheHoraire = trancheHoraire;
this.lieu = lieu;
}
//-----------------------------------------------------------------------------
public String getBut() { return but; }
public TrancheHoraire getTrancheHoraire() {
return trancheHoraire;
}
public String getLieu() { return lieu; }
public void setBut(String but) {
this.but = but;
}
public void setTrancheHoraire(TrancheHoraire trancheHoraire) {
this.trancheHoraire = trancheHoraire;
}
public void setLieu(String lieu) {
this.lieu = lieu;
}
public Date getDate (){
return this.getTrancheHoraire().getDate();
}
}
TrancheHoraire class :
package com.project.test;
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
//#XmlType(name = "trancheHoraire", propOrder = {"date", "part_journee"})
public class TrancheHoraire
{
//-----------------------------------------------------------------------------
// #XmlElement(required = true)
private Date date;
// #XmlElement(required = true)
private int part_journee;
public String part_journee_v;
//-----------------------------------------------------------------------------
public TrancheHoraire(){
}
public TrancheHoraire(Date date, int part_journee)
{
this.date = date;
this.part_journee = part_journee;
}
//-----------------------------------------------------------------------------
public Date getDate() { return date; }
public int getpart_journee()
{
return part_journee;
}
}
My Database :
package com.project.test;
import java.util.ArrayList;
import java.util.List;
public class ActiviteBD {
private static List<Activite> activites = new ArrayList<Activite>();
static {
activites.add(new Activite("RĂ©union", new TrancheHoraire(new Date(01, 10, 2015), 2), "Paris"));
activites.add(new Activite("Vacances", new TrancheHoraire(new Date(02, 10, 2015), 2), "Marseille"));
activites.add(new Activite("Resto", new TrancheHoraire(new Date(03, 10, 2015), 2), "Lyon"));
}
public static List<Activite> getActivites() {
return activites;
}
}
And I call webservices with this class :
package com.project.test;
import java.util.List;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
/**
*
* #author rcaboni
*/
#Path("/agenda")
public class Resource
{
#GET
#Produces("application/xml")
public List<Activite> getActivites() {
return ActiviteBD.getActivites();
}
#GET
#Path("{jour}")
#Produces("application/xml")
public Activite getActiviteByDate(#PathParam("jour") int jour){
System.out.println("getActivite");
Activite tranche = new Activite("RĂ©union", new TrancheHoraire(new Date(jour, 10, 2015), 2), "Marseille");
TrancheHoraire th = tranche.getTrancheHoraire();
System.out.println(tranche.getDate());
for (Activite _current : ActiviteBD.getActivites()) {
System.out.println(_current.getTrancheHoraire());
if (th.equals(_current.getTrancheHoraire())) {
System.out.println(_current.getTrancheHoraire());
return _current;
}
}
return null;
}
}
If I call /agenda, it returns all my activities.
Like this :
However, if I call /agenda/1 , it should return my first activitie...
In my console : getTrancheHoraire returns something like this : com.project.test.TrancheHoraire#75a630fb
I've read plugin on Equals() class is the only one solution.
Could you help me ? :)
"I've read plugin on Equals() class is the only one solution."
I guess "plugin on" means override. If not, then that's you it should mean. You need to override it, and describe how the objects will be determined equal. (It should also be noted, when override equals, you should also override hashcode).
See when should I override Equals function?
That being said, most IDEs, will be able to generate this for you. For example, with Netbeans, I just right click the class, select "Insert Code" and select equals() and hashcode(). Then select the properties I want to include in the comparison. I selected all, and got this
#Override
public int hashCode() {
int hash = 5;
hash = 79 * hash + Objects.hashCode(this.date);
hash = 79 * hash + this.part_journee;
hash = 79 * hash + Objects.hashCode(this.part_journee_v);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TrancheHoraire other = (TrancheHoraire) obj;
if (!Objects.equals(this.date, other.date)) {
return false;
}
if (this.part_journee != other.part_journee) {
return false;
}
if (!Objects.equals(this.part_journee_v, other.part_journee_v)) {
return false;
}
return true;
}
I know Eclipse has similar feature.
As an aside, your comparison looks kind of odd. Why do you need to create a new Activite? The method is getActiviteByDate, so why don't you just look for Activites with the date.
Try adding a / before your {jour} declaration in the #Path annotation, like so:
#Path("/{jour}")
The mapping you've got currently looks like it may be routing requests to /agenda1.

How can I create a HashMap that dynamically calls other Java classes?

I am attempting to create a HashMap<Integer, Class>, and am not being successful. Essentially, all I want to do is have the ability to dynamically load the classes into the Map.
My managed Bean looks like this:
package Demo;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
/**
*
* #author kbarnett
*/
#Named(value = "facePalmBean")
#Dependent
public class FacePalmBean {
private HashMap<Integer, Class> chimpanzee;
private NewClass0 NewClass0;
private NewClass1 NewClass1;
private NewClass2 NewClass2;
/**
* Creates a new instance of FacePalmBean
*/
public FacePalmBean() {
chimpanzee = new HashMap<>();
NewClass0 = new NewClass0(0);
NewClass1 = new NewClass1(1);
NewClass2 = new NewClass2(2);
}
public HashMap<Integer, Class> getChimpanzee() {
for (int i = 0; i < 3; i++) {
try {
String tmpstring = "NewClass"+i;
System.out.println(tmpstring);
Class tmpclass = Class.forName(tmpstring);
System.out.println(tmpclass);
chimpanzee.put(i, tmpclass);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FacePalmBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println(chimpanzee.toString());
return chimpanzee;
}
public void setChimpanzee(HashMap<Integer,Class> chimpanzee) {
this.chimpanzee=chimpanzee;
}
}
and the NewClasses look like this:
package Demo;
public class NewClass0 {
Integer MyNumber;
NewClass0(int num){
MyNumber=num;
}
public Integer getMyNumber() {
return MyNumber;
}
}
All of the NewClasses are identical except for the number (i.e. 0, 1, and 2).
In order to load a class with the Class.forName() method, you must specify a fully qualified package name. In this case it must be Demo.NewClass0, for example.

incopatible types: cannot be converted to

I have a class, NewBeautifulKiwi, that has getters and setters.
When I try to set the:
public void setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
}
with values from a TextField like:
#FXML
TextField KIWITextField;
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi()
.setKiwi(KIWITextField.getText());
I get the error message:
incopatible types: cannot be converted to NewBeautifulKiwi
Here are the classes in full (the necessary extracts for this question)
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import wakiliproject.Forms.AddNew.DB.NewBeautifulKiwi;
public class SampleController implements Initializable, ControlledScreen {
#FXML
TextField KIWITextField;
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi().setKiwi(KIWITextField.getText());
}
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class NewBeautifulKiwi implements Serializable {
#Id
#GeneratedValue
private int KiwiId;
private String Kiwi;
public int getKiwiId() {
return KiwiId;
}
public void setKiwiId(int KiwiId) {
this.KiwiId = KiwiId;
}
public String getKiwi() {
return Kiwi;
}
public void setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
}
}
How can I pass the TextField value to the setter?
The return value of new NewBeautifulKiwi().setKiwi(KIWITextField.getText()); is determined by the signature of setKiwi, which is: public void setKiwi(String Kiwi).
So that expression returns nothing (void) and you can't assign it to a variable. You can either split the two statements:
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi();
newBeautifulKiwi.setKiwi(KIWITextField.getText());
Or use a fluent interface style (my personal preference in that case because it allows you to chain setters):
public NewBeautifulKiwi setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
return this;
}
//Now that will compile
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi().setKiwi(KIWITextField.getText());
NewBeautifulKiwi newBeautifulKiwi = new
NewBeautifulKiwi().setKiwi(KIWITextField.getText());
Here setKiwi is void method. not returning any thing. You can change your code as follows
new NewBeautifulKiwi().setKiwi(KIWITextField.getText());`
You can use your current code if your setKiwi method in following way.
public NewBeautifulKiwi setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
return kiwi;
}
NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi();
newBeautifulKiwi.setKiwi(KIWITextField.getText());

Categories

Resources