How to escape from ClassCastException - java

This is my collection:
db.power.find().pretty()
{
"_id" : ObjectId("513e4022cc6d8d7ff2c83239"),
"Indicator" : "One",
"sex" : "male"
}
How to escape from ClassCastException?
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
public class Test {
public static void main(String args[]) throws UnknownHostException {
Mongo mongo = new Mongo();
DB db = mongo.getDB("at");
DBCollection testdata = db.getCollection("power");
BasicDBObject query = new BasicDBObject();
query.put("Indicator", "One");
PowerData data = (PowerData) testdata.findOne(query);
System.out.println(data.getSize());
}
}
import com.mongodb.BasicDBObject;
public class PowerData extends BasicDBObject{
public String getSize() {
return (String) get("sex");
}
public void setSize(String sex) {
put("sex", sex);
}
public String getIndicator() {
return (String) get("Indicator");
}
public void setIndicator(String Indicator) {
put("Indicator", Indicator);
}
public String getId() {
return (String) get("_id");
}
public void setId(String _id) {
put("_id", _id);
}
}
Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to PowerData
at Test.main(Test.java:19)

You could change your PowerData class like this:
public class PowerData extends BasicDBObject{
private BasicDBObject wrapped;
public PowerData(BasicDBObject o) {
this.wrapped = o;
}
public String getSize() {
return (String) o.get("sex");
}
public void setSize(String sex) {
o.put("sex", sex);
}
public String getIndicator() {
return (String) o.get("Indicator");
}
public void setIndicator(String Indicator) {
o.put("Indicator", Indicator);
}
public String getId() {
return (String) o.get("_id");
}
public void setId(String _id) {
o.put("_id", _id);
}
}
And in your main method, replace PowerData data = (PowerData) testdata.findOne(query); with following:
PowerData data = new PowerData(testdata.findOne(query));

Related

Return value is getting null from model

Hi i am creating a service of Invoice PO to get the json reponse after verification from classes of service package.
First I have created a model package and classes according to json.
InvoiceRequest is like this--
package com.InvoicePO.newmodel;
import java.util.List;
public class InvoiceRequest {
private List<Records> records;
public List<Records> getRecords() {
return records;
}
public void setRecords(List<Records> records) {
this.records = records;
}
}
Records Class--
package com.InvoicePO.newmodel;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Records {
private String Vecv_plant;
private String DBM_Plant;
private String VECV_SO;
private String DBM_PO;
private String VBELN;
private String FKDAT;
private String LRDATE;
private String PFCHARGE;
private String OCHARGE;
private String DISC;
private String TAXTYPE;
private String TAX;
private String TAXAMT;
private String INVAMT;
private String WAERK;
private String INVCNT;
private String ODN;
private List<LineItemTable> lineItemTables;
public String getVecv_plant() {
return Vecv_plant;
}
public void setVecv_plant(String vecv_plant) {
Vecv_plant = vecv_plant;
}
public String getDBM_Plant() {
return DBM_Plant;
}
public void setDBM_Plant(String dBM_Plant) {
DBM_Plant = dBM_Plant;
}
public String getVECV_SO() {
return VECV_SO;
}
public void setVECV_SO(String vECV_SO) {
VECV_SO = vECV_SO;
}
public String getDBM_PO() {
return DBM_PO;
}
public void setDBM_PO(String dBM_PO) {
DBM_PO = dBM_PO;
}
public String getVBELN() {
return VBELN;
}
public void setVBELN(String vBELN) {
VBELN = vBELN;
}
public String getFKDAT() {
return FKDAT;
}
public void setFKDAT(String fKDAT) {
FKDAT = fKDAT;
}
public String getLRDATE() {
return LRDATE;
}
public void setLRDATE(String lRDATE) {
LRDATE = lRDATE;
}
public String getPFCHARGE() {
return PFCHARGE;
}
public void setPFCHARGE(String pFCHARGE) {
PFCHARGE = pFCHARGE;
}
public String getOCHARGE() {
return OCHARGE;
}
public void setOCHARGE(String oCHARGE) {
OCHARGE = oCHARGE;
}
public String getDISC() {
return DISC;
}
public void setDISC(String dISC) {
DISC = dISC;
}
public String getTAXTYPE() {
return TAXTYPE;
LineItemTable--
package com.InvoicePO.newmodel;
public class LineItemTable {
private String VBELN1;
private String DEALER1;
private String POSEX;
private String MATNR;
private String INVQTY;
private String RATE;
private String TOTAL;
private String DISC;
private String TAXTYPE;
private String PURCH_NO;
private String PURCH_DATE;
private String SALES_NO;
private String PGIX;
public String getVBELN1() {
return VBELN1;
}
public void setVBELN1(String vBELN1) {
VBELN1 = vBELN1;
}
public String getDEALER1() {
return DEALER1;
}
public void setDEALER1(String dEALER1) {
DEALER1 = dEALER1;
}
public String getPOSEX() {
return POSEX;
}
public void setPOSEX(String pOSEX) {
POSEX = pOSEX;
}
public String getMATNR() {
return MATNR;
}
public void setMATNR(String mATNR) {
MATNR = mATNR;
}
public String getINVQTY() {
return INVQTY;
}
public void setINVQTY(String iNVQTY) {
INVQTY = iNVQTY;
}
public String getRATE() {
return RATE;
}
public void setRATE(String rATE) {
RATE = rATE;
}
public String getTOTAL() {
return TOTAL;
}
public void setTOTAL(String tOTAL) {
TOTAL = tOTAL;
}
public String getDISC() {
return DISC;
}
public void setDISC(String dISC) {
DISC = dISC;
}
public String getTAXTYPE() {
return TAXTYPE;
}
public void setTAXTYPE(String tAXTYPE) {
TAXTYPE = tAXTYPE;
}
public String getPURCH_NO() {
return PURCH_NO;
}
public void setPURCH_NO(String pURCH_NO) {
PURCH_NO = pURCH_NO;
}
public String getPURCH_DATE() {
return PURCH_DATE;
}
public void setPURCH_DATE(String pURCH_DATE) {
PURCH_DATE = pURCH_DATE;
}
public String getSALES_NO() {
return SALES_NO;
}
public void setSALES_NO(String sALES_NO) {
SALES_NO = sALES_NO;
}
public String getPGIX() {
return PGIX;
}
public void setPGIX(String pGIX) {
PGIX = pGIX;
}
}
Invoice Controller--
package com.InvoicePO.controller;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.InvoicePO.newmodel.InvoiceRequest;
import com.InvoicePO.service.DTRECCPOVCPLINVOICE;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO.Records;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO.Records.LineItemTable;
import com.InvoicePO.service.SISVCPLINVOICETOECCPO;
import com.InvoicePO.service.SISVCPLINVOICETOECCPOService;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
#RestController
public class InvoiceController {
public static String getJsonFromObject(Object obj) {
ObjectMapper Obj = new ObjectMapper();
Obj.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
Writer strWriter = new StringWriter();
try {
Obj.writeValue(strWriter,obj);
return strWriter.toString();
} catch (Exception e) {
return "";
}
}
#RequestMapping(value = "/invoicepo", method=RequestMethod.POST)
public #ResponseBody DTRECCPOVCPLINVOICE VerficationDetails(#RequestBody InvoiceRequest data) {
System.out.println("/Data Recieved" + getJsonFromObject(data));
DTRECCPOVCPLINVOICE response = null;
DTSVCPLINVOICETOECCPO soapobj = new DTSVCPLINVOICETOECCPO();
List<Records> objc = new ArrayList<>();
for(com.InvoicePO.newmodel.Records records : data.getRecords())
{
// RECORD records = data;
Records rec = new Records();
rec.setVecvPlant(records.getVecv_plant());
rec.setDBMPlant(records.getDBM_Plant());
rec.setVECVSO(records.getVECV_SO());
rec.setDBMPO(records.getDBM_PO());
rec.setVBELN(records.getVBELN());
rec.setFKDAT(records.getFKDAT());
rec.setLRDATE(records.getLRDATE());
rec.setPFCHARGE(records.getPFCHARGE());
rec.setOCHARGE(records.getOCHARGE());
rec.setDISC(records.getDISC());
rec.setTAXTYPE(records.getTAXTYPE());
rec.setTAX(records.getTAX());
rec.setTAXAMT(records.getTAXAMT());
rec.setINVAMT(records.getINVAMT());
rec.setWAERK(records.getWAERK());
rec.setINVCNT(records.getINVCNT());
rec.setODN(records.getODN());
List<LineItemTable> line = new ArrayList<>();
for(com.InvoicePO.newmodel.LineItemTable table : records.getLineItemTables()) {
// LineItemTable table = data;
LineItemTable lin = new LineItemTable();
lin.setDEALER1(table.getDEALER1());
lin.setPOSEX(table.getPOSEX());
lin.setMATNR(table.getMATNR());
lin.setINVQTY(table.getINVQTY());
lin.setRATE(table.getRATE());
lin.setTOTAL(table.getTOTAL());
lin.setDISC(table.getDISC());
lin.setTAXTYPE(table.getTAXTYPE());
lin.setPURCHNO(table.getPURCH_NO());
lin.setPURCHDATE(table.getPURCH_DATE());
lin.setSALESNO(table.getSALES_NO());
lin.setPGIX(table.getPGIX());
line.add(lin);
}
rec.setLineItemTable(line);
rec.setLineItemTable(line);
objc.add(rec);
}
System.out.println("\nRequest for PI:" +getJsonFromObject(soapobj));
SISVCPLINVOICETOECCPOService sisservice= new SISVCPLINVOICETOECCPOService();
SISVCPLINVOICETOECCPO port = sisservice.getHTTPSPort();
// DTSVCPLINVOICETOECCPO eccpo = new DTSVCPLINVOICETOECCPO();
// eccpo.setRecords(objc);
BindingProvider provider = (BindingProvider)port;
provider.getRequestContext().put("javax.xml.ws.security.auth.username", "pisuper");
provider.getRequestContext().put("javax.xml.ws.security.auth.password", "Xidvecv#123");
response = port.siSVCPLINVOICETOECCPO(soapobj);
System.out.println("\nResponse for PI:" +getJsonFromObject(soapobj));
return response ;
}
}
The json i am hitting in Postman --
{
"Records": {
"Vecv_plant": 1110,
"DBM_Plant": "C001",
"VECV_SO": 5110000139,
"DBM_PO": "5900000069",
"VBELN": 91297393,
"FKDAT": 20221208,
"LRDATE": 0,
"PFCHARGE": 0,
"OCHARGE": 0,
"DISC": 0,
"TAXTYPE": "IGST",
"TAX": 0,
"TAXAMT": 364.04,
"INVAMT": 2386.46,
"WAERK": "INR",
"INVCNT": 0,
"ODN": "IN9220800004",
"LineItemTable": [
{
"VBELN1": 91297393,
"DEALER1": "C001",
"POSEX": 10,
"MATNR": "IM300124L",
"INVQTY": 9,
"RATE": 2022,
"TOTAL": 2386,
"DISC": "",
"TAXTYPE": "IGST",
"PURCH_NO": 3000041178,
"PURCH_DATE": 20221121,
"SALES_NO": 1050022,
"PGIX": ""
},
{
"VBELN1": 91297393,
"DEALER1": "C001",
"POSEX": 20,
"MATNR": "IM300262L",
"INVQTY": 8,
"RATE": 1030,
"TOTAL": 1386,
"DISC": "",
"TAXTYPE": "IGST",
"PURCH_NO": 3000041178,
"PURCH_DATE": 20221121,
"SALES_NO": 1050022,
"PGIX": ""
}
]
}
}
The error I am getting = Cannot invoke java.util.List.iterator() because the return value of com.InvoicePO.newmodel.InvoiceRequest.getRecords() is null

Problem trying to read a json file in Java with the MVC pattern

I'm trying to print some JSONObjects from a JSONArray in JAVA using the MVC pattern and the json.simple library, but when I run it the program just print the last JSONObject.
This is my Main class:
package Main;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import Controlador.Controlador;
import Vista.Vista;
import Modelo.Modelo;
public class Main {
private static String ID;
public static void main(String[] args) throws IOException, InterruptedException {
Modelo modelo = llenarDatosModelo();
Vista vista = new Vista();
//se crea un objeto controlador y se le pasa el modelo y la vista
Controlador controlador = new Controlador(modelo, vista);
// se muestra los datos
controlador.actualizarVista();
}
//método estático que retorna el autor con sus datos
private static Modelo llenarDatosModelo() {
JSONParser jsonParser = new JSONParser ();
try(FileReader reader = new FileReader ("datos.json")) {
JSONObject documento = (JSONObject) jsonParser.parse(reader);
JSONObject resultados = (JSONObject)documento.get("search-results");
JSONArray Entrys = (JSONArray) resultados.get("entry");
for(Object Entry: Entrys) {
mostrarInformacionEntry ((JSONObject) Entry);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ParseException e) {
e.printStackTrace();
}
Modelo autor = new Modelo();
autor.setID(ID);
return autor;
}
private static void mostrarInformacionEntry(JSONObject entry) {
ID = (String) entry.get("dc:identifier");
}
This is my model:
package Modelo;
public class Modelo {
private String ID;
private String url;
private String eid;
private String document_count;
private String cited_by_count;
private String citation_count;
private String affiliation;
private String give_name;
private String classification;
private String publication_start;
private String publication_end;
public Modelo() {
}
public String getID() {
return ID;
}
public void setID(String string) {
this.ID = string;
}
public String geturl() {
return url;
}
public void seturl(String url) {
this.url = url;
}
public String geteid() {
return eid;
}
public void seteid(String eid) {
this.eid = eid;
}
public String getdocument_count() {
return document_count;
}
public void setdocument_count(String document_count) {
this.document_count = document_count;
}
public String getcited_by_count() {
return cited_by_count;
}
public void setcited_by_count(String cited_by_count) {
this.cited_by_count = cited_by_count;
}
public String getcitation_count() {
return citation_count;
}
public void setcitation_count(String citation_count) {
this.citation_count = citation_count;
}
public String getaffiliation() {
return affiliation;
}
public void setaffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getgive_name() {
return give_name;
}
public void setgive_name(String give_name) {
this.give_name = give_name;
}
public String getclassification() {
return classification;
}
public void setclassification(String classification) {
this.classification = classification;
}
public String getpublication_start() {
return publication_start;
}
public void setpublication_start(String publication_start) {
this.publication_start = publication_start;
}
public String getpublication_end() {
return publication_end;
}
public void setpublication_end(String publication_end) {
this.publication_end = publication_end;
}
}
This is my View:
package Vista;
public class Vista {
public void imprimirDatos(String string,String url, String eid, String document_count, String cited_by_count, String citation_count, String affiliation, String give_name, String classification, String publication_start, String publication_end) {
System.out.println("\n****AUTOR****");
System.out.println("ID: "+string);
System.out.println("url: "+url);
System.out.println("eid: "+eid);
System.out.println("document_count: "+document_count);
System.out.println("cited_by_count: "+cited_by_count);
System.out.println("citation_count: "+citation_count);
System.out.println("affiliation: "+affiliation);
System.out.println("give_name: "+give_name);
System.out.println("classification: "+classification);
System.out.println("publication_start: "+publication_start);
System.out.println("publication_end: "+publication_end);
}
}
And this is my controller:
package Controlador;
import Modelo.Modelo;
import Vista.Vista;
public class Controlador {
//objetos vista y modelo
private Vista vista;
private Modelo modelo;
//constructor para inicializar el modelo y la vista
public Controlador(Modelo modelo, Vista vista) {
this.modelo = modelo;
this.vista = vista;
}
//getters y setters para el modelo
public String getID() {
return modelo.getID();
}
public void setID(String ID) {
this.modelo.setID(ID);
}
public String geturl() {
return modelo.geturl();
}
public void seturl(String url) {
this.modelo.seturl(url);
}
public String geteid() {
return modelo.geteid();
}
public void seteid(String eid) {
this.modelo.seteid(eid);
}
public String getdocument_count() {
return modelo.getdocument_count();
}
public void setdocument_count(String document_count) {
this.modelo.setdocument_count(document_count);
}
public String getcited_by_count() {
return modelo.getcited_by_count();
}
public void setcited_by_count(String cited_by_count) {
this.modelo.setcited_by_count(cited_by_count);
}
public String getcitation_count() {
return modelo.getcitation_count();
}
public void setcitation_count(String citation_count) {
this.modelo.setcitation_count(citation_count);
}
public String getaffiliation() {
return modelo.getaffiliation();
}
public void setaffiliation(String affiliation) {
this.modelo.setaffiliation(affiliation );
}
public String getgive_name() {
return modelo.getgive_name();
}
public void setgive_name(String give_name) {
this.modelo.setgive_name(give_name);
}
public String getclassification() {
return modelo.getclassification();
}
public void setclassification(String classification) {
this.modelo.setclassification(classification);
}
public String getpublication_start() {
return modelo.getpublication_start();
}
public void setpublication_start(String publication_start) {
this.modelo.setpublication_start(publication_start);
}
public String getpublication_end() {
return modelo.getpublication_end();
}
public void setpublication_end(String publication_end) {
this.modelo.setpublication_end(publication_end);
}
//pasa el modelo a la vista para presentar los datos
public void actualizarVista() {
vista.imprimirDatos(modelo.getID(),modelo.geturl(), modelo.geteid(), modelo.getdocument_count(), modelo.getcited_by_count(), modelo.getcitation_count(), modelo.getaffiliation(), modelo.getgive_name(), modelo.getclassification(), modelo.getpublication_start(), modelo.getpublication_end());
}
}
When I run it the console shows this:
****AUTOR****
ID: SCOPUS_ID:85137292444
url: null
eid: null
document_count: null
cited_by_count: null
citation_count: null
affiliation: null
The JSONArray Entrys have multiple articles, I want the program to print them all. Does anyone know what I'm doing wrong?
The JSON File is:
https://drive.google.com/file/d/1t53qiU64eJVUupDA-Ie2ZR1Xakz7npGI/view?usp=sharing
Your method mostrarInformacionEntry is reading the fields of one JSON array entry. Your problem is, that this method isn't creating a new model per entry. Instead it assigns the read value dc:identifier to the class variable ID. This is done for all entries in the array. An entry overwrites the saved ID of the previous entry. At the end you create a model with the ID of the last loaded entry. But you should create a model for each entry.
You need a custom entry class/POJO:
public class ModeloEntry {
private String ID;
private String url;
private String eid;
private String document_count;
private String cited_by_count;
private String citation_count;
private String affiliation;
private String give_name;
private String classification;
private String publication_start;
private String publication_end;
public ModeloEntry() {
}
public String getID() {
return ID;
}
public void setID(String string) {
this.ID = string;
}
public String geturl() {
return url;
}
public void seturl(String url) {
this.url = url;
}
public String geteid() {
return eid;
}
public void seteid(String eid) {
this.eid = eid;
}
public String getdocument_count() {
return document_count;
}
public void setdocument_count(String document_count) {
this.document_count = document_count;
}
public String getcited_by_count() {
return cited_by_count;
}
public void setcited_by_count(String cited_by_count) {
this.cited_by_count = cited_by_count;
}
public String getcitation_count() {
return citation_count;
}
public void setcitation_count(String citation_count) {
this.citation_count = citation_count;
}
public String getaffiliation() {
return affiliation;
}
public void setaffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getgive_name() {
return give_name;
}
public void setgive_name(String give_name) {
this.give_name = give_name;
}
public String getclassification() {
return classification;
}
public void setclassification(String classification) {
this.classification = classification;
}
public String getpublication_start() {
return publication_start;
}
public void setpublication_start(String publication_start) {
this.publication_start = publication_start;
}
public String getpublication_end() {
return publication_end;
}
public void setpublication_end(String publication_end) {
this.publication_end = publication_end;
}
}
And you need a model in the context of MVC, holding all entries:
public class Modelo {
private List<ModeloEntry> entries = new ArrayList<>();
public void addEntry(ModeloEntry entry) {
this.entries.add(entry);
}
public List<ModeloEntry> getEntries() {
return entries;
}
}
Then you can do the following:
public class Main() {
// ...
private static Modelo llenarDatosModelo() {
Modelo autor = new Modelo(); // Create the MVC model first
JSONParser jsonParser = new JSONParser ();
try(FileReader reader = new FileReader ("datos.json")) {
JSONObject documento = (JSONObject) jsonParser.parse(reader);
JSONObject resultados = (JSONObject)documento.get("search-results");
JSONArray Entrys = (JSONArray) resultados.get("entry");
for(Object Entry: Entrys) {
ModeloEntry entry = mostrarInformacionEntry ((JSONObject) Entry); // Create a entry instance per JSON array entry
author.addEntry(entry); // Add the entry to your MVC model
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ParseException e) {
e.printStackTrace();
}
return autor; // Return your MVC model
}
private static ModeloEntry mostrarInformacionEntry(JSONObject entry) {
ModeloEntry entry = new ModeloEntry(); // Create a entry instance
entry.setId((String) entry.get("dc:identifier"));
return entry;
}
}
Your for-each loop is then outsourced to your controller class:
public class Controlador {
private Vista vista;
private Modelo modelo;
public void actualizarVista() {
// Print each entry of your MVC model line by line
for(ModeloEntry entry : modelo.getEntries()) {
vista.imprimirDatos(modelo.getID(),modelo.geturl(), modelo.geteid(), modelo.getdocument_count(), modelo.getcited_by_count(), modelo.getcitation_count(), modelo.getaffiliation(), modelo.getgive_name(), modelo.getclassification(), modelo.getpublication_start(), modelo.getpublication_end());
}
}
}

Empty List in Drools rule

I ran into a problem in a rule called "Due date for test1". I pass the list called "tests" as a parameter to
check it for Test.Test1, but the list is empty, despite the fact that before that I filled it in the rule "test for type1". What is the problem?
here is code of entity "Machine":
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Machine {
private String type;
public ArrayList<Test> tests= new ArrayList<Test>();
private List<String> functions = new ArrayList<String>();
private Date creationTime =null;
private Date testTime = null;
public Machine (String type) {
this.type= type;
}
public void setType(String type) {
this.type= type;
}
public String getType() {
return type;
}
public void setTests(ArrayList<Test> tests) {
this.tests = tests;
}
public void setFunctions(List<String> functions) {
this.functions = functions;
}
public List<String> functions() {
return functions;
}
public List<Test> getTests() {
return tests;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Date getCreationTime() {
return creationTime;
}
public void setTestTime(Date testTime) {
this.testTime = testTime;
}
public Date getTestTime() {
return testTime;
}
}
here is code of entity "Test":
package com.sample;
import java.util.Calendar;
public enum Test {
Test1(1),Test2(2),Test3(3);
private Integer id;
Test(Integer id) {
this.id=id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setTestsDueTime(Machine m,int numOfDays) {
setTest(m,Calendar.DAY_OF_YEAR,numOfDays);
}
public void setTest(Machine m,int calendarType,int numOfDays) {
Calendar c = Calendar.getInstance();
c.setTime(m.getCreationTime());
c.add(calendarType, numOfDays);
m.setTestTime(c.getTime());
}
}
here is drl code:
package com.sample
import com.sample.Machine;
import com.sample.Test;
rule "test for type1"
when
m : Machine(type == "type1");
then
Test t1=Test.Test1;
Test t2 = Test.Test2;
Test t3 = Test.Test3;
m.getTests().add(t1);
m.getTests().add(t2);
m.getTests().add(t3);
insert(m);
insert(m);
insert(m) ;
end
rule "Due date for test1"
when
m:Machine(type == "type1", tests contains Test.Test1);
then
System.out.print("условие прошло");
//t.setTestsDueTime( m,3);
end
main class code:
package com.sample;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class DroolsTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
// go !
Machine m = new Machine("type1");
kSession.insert(m);
kSession.fireAllRules();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
insert(m);
insert(m);
insert(m);
This doesn't make any sense. m is already in Working Memory.
What you need is one
update(m);
instead.

SpringMVC+Hibernate :criteria.list() return empty

Spring:version 3.2.9
Hibernate:version 4.2.19
BaseDaoImpl.java
public class BaseDaoImpl<T> implements BaseDao<T> {
public SessionFactory sessionFactory;
protected Class<T> entityClass;
#Override
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public BaseDaoImpl() {
Class c = getClass();
Type type = c.getGenericSuperclass();
if (type instanceof ParameterizedType) {
Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
this.entityClass = (Class<T>) parameterizedType[0];
}
}
#Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public boolean save(T entity) {
try {
getSession().save(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean delete(T entity) {
try {
getSession().delete(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean update(T entity) {
try {
getSession().update(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#SuppressWarnings("unchecked")
#Override
public T get(Integer id) {
return (T) getSession().get(entityClass, id);
}
#SuppressWarnings("unchecked")
#Override
public List<T> findByIdSet(Integer[] ids) {
Criteria criteria=getSession().createCriteria(entityClass);
criteria.add(Restrictions.in("id", ids));
return (List<T>)criteria.list();
}
#SuppressWarnings("unchecked")
#Override
public List<T> findAllList() {
return getSession().createCriteria(entityClass).list();
}
#SuppressWarnings("unchecked")
#Override
public Pager findByPager(Pager pager) {
Criteria criteria=getSession().createCriteria(entityClass);
criteria.setProjection(Projections.rowCount());
int totalCount = ((Long) criteria.uniqueResult()).intValue();
pager.setTotalCount(totalCount);
criteria.setProjection(null);
pager.init();
criteria.setFirstResult((pager.getPageIndex()-1)*pager.getPageSize());
criteria.setMaxResults(pager.getPageSize());
List<T> te =(List<T>)criteria.list();
pager.setDatas((List<T>)criteria.list());
return pager;
}
}
Pager.java
import java.util.List;
public class Pager {
private int pageSize;
private int pageIndex;
private int totalCount;
private int totalPage;
private List<?> datas;
private boolean hasNextPage;
private boolean hasPreviousPage;
public void init(){
pageIndex=1;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<?> getDatas() {
return datas;
}
public void setDatas(List<?> datas) {
this.datas = datas;
}
public boolean isHasNextPage() {
return hasNextPage;
}
public void setHasNextPage(boolean hasNextPage) {
this.hasNextPage = hasNextPage;
}
public boolean isHasPreviousPage() {
return hasPreviousPage;
}
public void setHasPreviousPage(boolean hasPreviousPage) {
this.hasPreviousPage = hasPreviousPage;
}
}
Entity:Student.java
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="student")
public class Student {
private int stu_id;
private String stu_name;
private String stu_password;
private Department department;
private Major major;
private String stu_sex;
private String stu_per_sig;
private String stu_head_img;
private Date stu_regist_time;
private String stu_attn_crs_ids;
private String stu_pw_question;
private String stu_pw_answer;
public Student() {
}
public Student(int stu_id, String stu_name, String stu_password,
Department department, Major major, String stu_sex,
String stu_per_sig, String stu_head_img, Date stu_regist_time,
String stu_attn_crs_ids, String stu_pw_question,
String stu_pw_answer) {
this.stu_id = stu_id;
this.stu_name = stu_name;
this.stu_password = stu_password;
this.department = department;
this.major = major;
this.stu_sex = stu_sex;
this.stu_per_sig = stu_per_sig;
this.stu_head_img = stu_head_img;
this.stu_regist_time = stu_regist_time;
this.stu_attn_crs_ids = stu_attn_crs_ids;
this.stu_pw_question = stu_pw_question;
this.stu_pw_answer = stu_pw_answer;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getStu_id() {
return stu_id;
}
public void setStu_id(int stu_id) {
this.stu_id = stu_id;
}
#Column(length=20,nullable=false)
public String getStu_name() {
return stu_name;
}
public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}
#Column(length=20,nullable=false)
public String getStu_password() {
return stu_password;
}
public void setStu_password(String stu_password) {
this.stu_password = stu_password;
}
#Column(length=2,nullable=false)
public String getStu_sex() {
return stu_sex;
}
public void setStu_sex(String stu_sex) {
this.stu_sex = stu_sex;
}
#Column(length=255,nullable=true)
public String getStu_per_sig() {
return stu_per_sig;
}
public void setStu_per_sig(String stu_per_sig) {
this.stu_per_sig = stu_per_sig;
}
#Column(length=255,nullable=false)
public String getStu_head_img() {
return stu_head_img;
}
public void setStu_head_img(String stu_head_img) {
this.stu_head_img = stu_head_img;
}
#Temporal(value=TemporalType.TIMESTAMP)
#Column(nullable=false)
public Date getStu_regist_time() {
return stu_regist_time;
}
public void setStu_regist_time(Date stu_regist_time) {
this.stu_regist_time = stu_regist_time;
}
#Column(length=255,nullable=true)
public String getStu_attn_crs_ids() {
return stu_attn_crs_ids;
}
public void setStu_attn_crs_ids(String stu_attn_crs_ids) {
this.stu_attn_crs_ids = stu_attn_crs_ids;
}
#Column(length=64,nullable=false)
public String getStu_pw_question() {
return stu_pw_question;
}
public void setStu_pw_question(String stu_pw_question) {
this.stu_pw_question = stu_pw_question;
}
#Column(length=64,nullable=false)
public String getStu_pw_answer() {
return stu_pw_answer;
}
public void setStu_pw_answer(String stu_pw_answer) {
this.stu_pw_answer = stu_pw_answer;
}
#ManyToOne()
#JoinColumn(name="stu_dept_id",nullable=false)
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#ManyToOne()
#JoinColumn(name="stu_major_id",nullable=false)
public Major getMajor() {
return major;
}
public void setMajor(Major major) {
this.major = major;
}
}
I write BaseDaoImpl.java to implement the interface BaseDao.java
When I debug the project ,I found that the size of te list is 0 .
In findByPager method of BaseDaoImpl.java.
Why the method criteria.list() return a empty list?
Why is it not a List<Student> list ?
It puzzles me a long time.I'm a fresh man,who can help me to solve this problem.
The problem of your code is this line:
Criteria criteria=getSession().createCriteria(entityClass);
Because when you use criteria queries, you are building a query against a reference of a particular persistent class and your variable entityClass isn't.
protected Class<T> entityClass;
The correct way to build a criteria query is:
Criteria criteria=getSession().createCriteria(Entity.class);
Then you need to change that line of your code. You need to add the .class to your variable:
Criteria criteria=getSession().createCriteria(entityClass.class);
I share you some links about criteria queries.
https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Criteria.html
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html
I hope this information helps you.
Good luck.

JSON Parsing with GSON

I have the following Json string.How to parse this kind of Json using Gson in Java?Any help would be appreciated.
{
"acclst":[{
"accountInfoData":[{
"userId":9,
"rid":"1-Z5S3",
"acnme":"acc_1234.",
"actpe":"Fabricator / Distributor",
"mph":"2660016354",
"euse":"Biofuels",
"com":"0",
"sta":"Active",
"stem":"BBUSER5",
"wsite":"",
"fax":"",
"zone":"",
"crted":"BBUSER4",
"statusX":1,
"partyId":0,
"address":[]
}
]
}
],
"conlst":[],
"actlst":[],
"prolst":[],
"code":"200"
}
your Gson getter/Setter class will be
sample.java
public class sample {
public String code="";
ArrayList<String> conlst;
ArrayList<String> actlst;
ArrayList<innerObject> prolst;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ArrayList<String> getConlst() {
return conlst;
}
public void setConlst(ArrayList<String> conlst) {
this.conlst = conlst;
}
public ArrayList<String> getActlst() {
return actlst;
}
public void setActlst(ArrayList<String> actlst) {
this.actlst = actlst;
}
public ArrayList<innerObject> getProlst() {
return prolst;
}
public void setProlst(ArrayList<innerObject> prolst) {
this.prolst = prolst;
}
}
innerObject.java
public class innerObject {
ArrayList<String> accountInfoData;
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
secondInnerObject.java
public class secondInnerObject {
public String userId="";
public String rid="";
public String acme="";
public String actpe="";
public String mph="";
public String euse="";
public String com="";
public String sta="";
public String stem="";
public String wsite="";
public String fax="";
public String zone="";
public String crted="";
public String statusX="";
public String partyId="";
ArrayList<String> address;
ArrayList<String> accountInfoData;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getAcme() {
return acme;
}
public void setAcme(String acme) {
this.acme = acme;
}
public String getActpe() {
return actpe;
}
public void setActpe(String actpe) {
this.actpe = actpe;
}
public String getMph() {
return mph;
}
public void setMph(String mph) {
this.mph = mph;
}
public String getEuse() {
return euse;
}
public void setEuse(String euse) {
this.euse = euse;
}
public String getCom() {
return com;
}
public void setCom(String com) {
this.com = com;
}
public String getSta() {
return sta;
}
public void setSta(String sta) {
this.sta = sta;
}
public String getStem() {
return stem;
}
public void setStem(String stem) {
this.stem = stem;
}
public String getWsite() {
return wsite;
}
public void setWsite(String wsite) {
this.wsite = wsite;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getCrted() {
return crted;
}
public void setCrted(String crted) {
this.crted = crted;
}
public String getStatusX() {
return statusX;
}
public void setStatusX(String statusX) {
this.statusX = statusX;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public ArrayList<String> getAddress() {
return address;
}
public void setAddress(ArrayList<String> address) {
this.address = address;
}
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
to fetch
String json= "your_json_string";
Gson gson= new Gson();
sample objSample=gson.fromJson(json,sample.getClass());
thats it
You have to use JSONObject to parse this json in android.
Take a look at the following link.
http://developer.android.com/reference/org/json/JSONObject.html
Android already contains the required JSON libraries. You can use a valid string or a file for input. Here is code and explanation taken from here:
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonParser extends Activity {
private JSONObject jObject;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";//write your JSON String here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(jString);
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);
String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
}
}
Here you have a tutorial which answers your needs - Android + Gson

Categories

Resources