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.
Related
I have two enums AttributesProperty and ResourceAttributesMapping each referencing each other as shown below:
import org.apache.commons.collections.map.HashedMap;
import test.xsd.Attribute;
public enum AttributesProperty {
ACP_RESOURCETYPE(ResourceAttributesMapping.ACCESSCONTROLPOLICY,"resourceType"),
ACP_RESOURCEID(ResourceAttributesMapping.ACCESSCONTROLPOLICY,"resourceID"),
.............
private ResourceAttributesMapping resource;
private String attributeName;
private AttributesProperty(ResourceAttributesMapping resource, String attributeName)
{
this.resource = resource;
this.attributeName = attributeName;
}
public static Map<ResourceAttributesMapping, List<Attribute>> getResTypeMapForAttrName(List<Attribute> attributesList) {
Map<ResourceAttributesMapping, List<Attribute>> attributeMap = new HashedMap();
List<Attribute> attrList = null;
List<ResourceAttributesMapping> resTypes = new ArrayList<ResourceAttributesMapping>();
for (Attribute attr : attributesList) {
boolean flag = false;
for (AttributesProperty attrProp : AttributesProperty.values()) {
if (attr.getName().equals(attrProp.getAttributeName())) {
if (attributeMap.get(attrProp.getResourceType()) == null) {
.........// Some logic
}
}
Referenced Enum: ResourceAttributesMapping.java
This enum as seen in imports statically importing the AttributesProperty enum.
import static xsd.enums.AttributesProperty.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.map.HashedMap;
public enum ResourceAttributesMapping
{
ACCESSCONTROLPOLICY(1, Arrays.asList(ACP_RESOURCETYPE,ACP_RESOURCEID,............)),
AE(2, Arrays.asList(AE_RESOURCETYPE,AE_RESOURCEID,...........)),
....
private int resourceType;
private List<AttributesProperty> attrList;
private ResourceAttributesMapping(int resourceType, List<AttributesProperty> attrList) {
this.resourceType = resourceType;
this.attrList = attrList;
}
public int getM2MResourceTypes() {
return resourceType;
}
public List<AttributesProperty> getAttributeList(){
return attrList;
}
......// accessor methods
}
This code was running succesfully on JDK 8, WildFly 15 but after migrating to JDK 11 WildFly 20, I am getting a NullPointerException in the AttributesProperty 's enums accessor method:
public static Map<ResourceAttributesMapping, List<Attribute>> getResTypeMapForAttrName(List<Attribute> attributesList) {
Map<ResourceAttributesMapping, List<Attribute>> attributeMap = new HashedMap();
List<Attribute> attrList = null;
List<ResourceAttributesMapping> resTypes = new ArrayList<ResourceAttributesMapping>();
for (Attribute attr : attributesList) {
boolean flag = false;
for (AttributesProperty attrProp : AttributesProperty.values()) {
if (attr.getName().equals(attrProp.getAttributeName())) {
if (attributeMap.get(attrProp.getResourceType()) == null) {
.........// Some logic
attrProp.getResourceType() is giving null.
The test scenario is such that on first iteration of running the accesor methods in the enum it runs successfully, however on second iteration I get the NullPointerException.
Is there some change in Enums accessing from JDK 8 to 11?
Or the static access of second enum causing the issue.
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.
am new to Java. I am trying to decouple the Responder class from the WeatherSystem Class. But I get an error at Public NewResponder in the Responder class (invalid method declaration; return type required), I am really stuck at this point. I have tried changing all the class points at NewResponder and responder but can't rectify it. Could anyone point out why I am getting this issue, please?
(I also have InputReader class but that's not included below).
WeatherSystem Class
import java.util.HashSet;
public class WeatherSystem
{
private InputReader reader;
private NewResponder responder;
public WeatherSystem(NewResponder responder)
{
reader = new InputReader();
this.responder = new Responder();
}
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
HashSet<String> input = reader.getInput();
if(input.contains("exit")) {
finished = true;
}
else {
String response = this.responder.generateResponse(input);
System.out.println(response);
}
}
printGoodbye();
.............................................
Class Responder
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import WeatherSystem.NewResponder
public class Responder implements NewResponder
{
private HashMap<String, String> responseMap;
private ArrayList<String> defaultResponses;
private Random randomGenerator;
public NewResponder()
{
responseMap = new HashMap<>();
defaultResponses = new ArrayList<>();
fillResponseMap();
fillDefaultResponses();
randomGenerator = new Random();
}
public String generateResponse(HashSet<String> words)
{
for (String word : words) {
String response = this.responseMap.get(word);
if(response != null) {
return response;
}
}
return pickDefaultResponse();
....................................................
You really need to check whether you need interface NewResponder inside WeatherSystem. Which you are implementing in Responder class with wrong constructor name.
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");
}
});
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.