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.
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.
Im trying to learn how to consume a REST webservice using Jersey. Im using a get request to view data from the URI "https://api.fixer.io/latest" this URI displays a base, date and i believe a array/ArrayList. In my class below, i have managed to display the date and base of the resource. But I am having trouble displaying the list of items. When i run my code it gives this:
Date = 2017-12-15, base = EURlist = []
an example of what im looking for would be:
Date = 2017-12-15, base = EUR list = [AUD":1.5382,"BGN":1.9558 (etc)]
Here is my code:
restServiceClient.java
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.xml.ws.Response;
public class restServiceClient{
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
Exchange exchange = client.target("https://api.fixer.io/latest")
.request(MediaType.APPLICATION_XML)
.get(Exchange.class);
String base = exchange.getBase();
String date = exchange.getDate();
ArrayList<String> theList = exchange.getRates();
//String[] excArray = theList.toArray();
System.out.print(exchange);
client.close() ;
}
}
Exchange.java
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Admin
*/
public class Exchange {
private String base;
private String date;
private ArrayList<String> rates;
public ArrayList<String> getRates() {
return rates;
}
public void setRates(ArrayList<String> rates) {
this.rates = rates;
}
public void setBase(String base) {
this.base = base;
}
public void setDate(String date) {
this.date = date;
}
public String getBase() {
return base;
}
public String getDate() {
return date;
}
#Override
public String toString() {
return "Date = " + date + ", base = "
+ base + " list = " + rates;
}
}
First, program on interfaces (List, not ArrayList).
Second, look at the response at https://api.fixer.io/latest. It's JSON, not XML. So don't request XML.
Third, as you see, rates is not a list of Strings. It's an array of objects with a key of type String, and a value of type number. This would typically mapped by a JSON mapper as a Map<String, Double>, not as an ArrayList<String>.
I created two classes, but I do not know how to do the payload of my function which calculates the score of each terms.I don't know if i must create author classes , please someone can help me.
The first classe is:
import org.apache.lucene.analysis.payloads.PayloadHelper;
import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.util.BytesRef;
public class BoostingSimilarity extends DefaultSimilarity {
public float scorePayload(int docID, int start, int end, BytesRef payload) {
float pload = 1.0f;
if (payload != null) {
pload = PayloadHelper.decodeFloat(payload.bytes);
}
System.out.println("===> docid: " + docID + " payload: " + pload);
return pload;
}}
The seconde classe is:
I added my idflocal function as follows, But I'm not sure if what I'm doing is right :
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.TokenFilter;
import java.io.IOException;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.analysis.payloads.PayloadHelper;
import org.apache.lucene.util.BytesRef;
import static Package.FonctionIDFlocal.idflocal;
public class BulletinPayloadsFilter extends TokenFilter {
private PayloadAttribute attr;
BulletinPayloadsFilter(TokenStream in,float idflocal) {
super(in);
attr = addAttribute(PayloadAttribute.class);
}
public final boolean incrementToken() throws IOException {
if (input.incrementToken()) {
BytesRef p =new BytesRef(PayloadHelper.encodeFloat(idflocal));;
attr.setPayload(p);
} else {
attr.setPayload(null);
}
return false;
}
}
What exactly are you trying? It looks like some custom scoring mechanism that scores documents according to a float value in the payload.
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.
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.