Getting a whole event instead of a part in Java - java

Actually I have two probles. One of them is that I am getting empty fields in my RSS Reader. I get just:
screenshot
I was trying to found what's wrong with my code and I noticed that method which should read title, describtion and other stuff singly, its reading all of them together. I mean that my String which should have just single object like title, have everyting like: screenshot
And I have no idea why. Can you help me? I know that there's a lot of code but the problem is in reedFeed in RSSFeedParser class.
Main:
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.Scanner;
/**
* Created by Maciek on 2015-11-12.
*/
public class ReadTest {
private static Scanner scanner = new Scanner(System.in);
private static RSSList rssList = new RSSList();
private static String url;
public static String righturl;
public static void main(String[] args) throws XMLStreamException, IOException, ClassNotFoundException {
MENU();
}
public static void MENU() throws IOException, ClassNotFoundException, XMLStreamException {
int choice;
System.out.println("MENU:");
System.out.println(" 1 = Wydrukuj RSS");
System.out.println(" 2 = Pokaz liste dodanych RSS");
System.out.println(" 3 = Dodaj link RSS");
System.out.println(" 4 = Usun link RSS");
System.out.println(" 5 = Wydrukuj historie");
System.out.println("5 = zakoncz");
choice = scanner.nextInt();
switch (choice) {
case 1:
rssList.readCurrentlyList();
printRSS();
MENU();
break;
case 2:
rssList.readCurrentlyList();
printList();
MENU();
break;
case 3:
rssList.readCurrentlyList();
rssList.readHistory();
feedURL();
checkCurrentyList();
rssList.saveCurrentlyList();
MENU();
break;
case 4:
rssList.readCurrentlyList();
System.out.println("Ktory link chcesz usunac?");
printList();
deleteIndex();
rssList.saveCurrentlyList();
MENU();
break;
case 5:
rssList.readHistory();
readHistory();
MENU();
break;
}
}
public static void printRSS() throws XMLStreamException {
for (int i = 0; i < rssList.RSSList.size(); i++) {
righturl = rssList.RSSList.get(i);
RSSFeedParser parser = new RSSFeedParser(righturl);
Feed feed = parser.readFeed();
System.out.println(feed);
for (FeedMessage message : feed.getMessages()) {
System.out.println(message);
}
}
}
public static void printList(){
for(int i = 0; i<rssList.RSSList.size(); i++){
System.out.println(i+1 +". "+rssList.RSSList.get(i));
}
}
public static void deleteIndex(){
int index = scanner.nextInt();
rssList.RSSList.remove(index-1);
}
public static void feedURL(){
scanner.nextLine();
url = scanner.nextLine();
}
public static void addToHistory(){
boolean thereAlreadyIs = false;
for(int i = 0; i<rssList.RSSHistory.size(); i++){
if(rssList.RSSHistory.get(i).equals(url)){
thereAlreadyIs = true;
}
}
if(thereAlreadyIs==false){
rssList.RSSHistory.add(url);
}
}
public static void checkCurrentyList() throws IOException, ClassNotFoundException {
boolean thereAlreadyIs = false;
rssList.readCurrentlyList();
for (int i = 0; i < rssList.RSSList.size(); i++) {
if (url.equals(rssList.RSSList.get(i))) {
thereAlreadyIs = true;
}
}
if (thereAlreadyIs == true) {
System.out.println("Juz jest dodany RSS o takim adresie!");
}
else{
addRSS();
}
}
public static void addRSS(){
rssList.RSSList.add(url);
addToHistory();
}
public static void readHistory() throws IOException, ClassNotFoundException {
rssList.readHistory();
for(int i =0; i<rssList.RSSHistory.size(); i++){
System.out.println("1. "+rssList.RSSHistory.get(i));
}
}
}
Class which collecting reader data.
import java.util.ArrayList;
import java.util.List;
/**
* Created by Maciek on 2015-11-11.
*/
public class Feed {
final String title;
final String description;
final String link;
final String language;
final String copyright;
final String pubDate;
final List<FeedMessage> entries = new ArrayList<FeedMessage>();
public Feed(String title, String description, String link, String language, String copyright, String pubDate){
this.title=title;
this.description=description;
this.link=link;
this.language=language;
this.copyright=copyright;
this.pubDate=pubDate;
}
public List<FeedMessage> getMessages(){
return entries;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
public String getLink(){
return link;
}
public String getLanguage(){
return language;
}
public String getCopyright(){
return copyright;
}
public String getPubDate(){
return pubDate;
}
public String toString(){
return "Freed: [Title: " +title+", Description: "+description+", Copyright: "+copyright+", Language: "+language+", PubDate: "+pubDate;
}
}
Class which is using to print RSS
public class FeedMessage {
String title;
String description;
String link;
String author;
String guid;
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return title;
}
public void setDescription(String description){
this.description=description;
}
public String getDescription(){
return description;
}
public void setLink(String link){
this.link=link;
}
public String getLink(){
return link;
}
public void setAuthor(String author){
this.author=author;
}
public String getAuthor(){
return author;
}
public void setGuid(String guid){
this.guid=guid;
}
public String getGuid(){
return guid;
}
public String toString(){
return "FeedMessage: [title= "+title+", Description= "+description+", Link= "+link+", Author: "+author+", Guid= "+guid;
}
}
FeedParser class:
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Created by Maciek on 2015-11-15.
*/
public class RSSFeedParser {
public static final String ITEM = "item";
public static String description = "";
public static String title = "";
public static String link = "";
public static String language = "";
public static String copyright = "";
public static String author = "";
public static String pubDate = "";
public static String guid = "";
public Feed feed;
public boolean isFeedHeader;
public InputStream in;
public XMLInputFactory inputFactory = XMLInputFactory.newInstance();
public XMLEventReader eventReader;
public XMLEvent event;
final URL url;
TITLE tytul = new TITLE();
AUTHOR autor = new AUTHOR();
COPYRIGHT prawa = new COPYRIGHT();
DESCRIPTION opis = new DESCRIPTION();
GUID identyfikacja = new GUID();
LANGUAGE jezyk = new LANGUAGE();
LINK linskon = new LINK();
PUB_DATE publikajca = new PUB_DATE();
ITEM itemson = new ITEM();
public RSSFeedParser(String feedUrl) {
try {
url = new URL(feedUrl);
in = read();
eventReader = inputFactory.createXMLEventReader(in);
event = eventReader.nextEvent();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Feed readFeed() throws XMLStreamException {
try {
isFeedHeader = true;
event = eventReader.nextEvent();
while(eventReader.hasNext()) {
itemson.feedData(this);
tytul.feedData(this);
opis.feedData(this);
System.out.println(description);
linskon.feedData(this);
identyfikacja.feedData(this);
jezyk.feedData(this);
autor.feedData(this);
publikajca.feedData(this);
prawa.feedData(this);
eventReader.close();
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return feed;
}
public Feed setAllElements() throws XMLStreamException {
FeedMessage message = new FeedMessage();
message.setAuthor(author);
message.setDescription(description);
message.setGuid(guid);
message.setLink(link);
message.setTitle(title);
feed.getMessages().add(message);
return feed;
}
private InputStream read() throws XMLStreamException {
try {
return url.openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getCharacterData(XMLEvent event, XMLEventReader eventReader) throws XMLStreamException {
String results = "";
if (event instanceof Characters) {
results = event.asCharacters().getData();
}
return results;
}
}
And I'll paste here just a one of classes which implements after:
public interface Case {
void feedData(RSSFeedParser rss) throws XMLStreamException;
}
Important class is ITEM:
public class ITEM implements Case {
#Override
public void feedData(RSSFeedParser rss) throws XMLStreamException {
if (rss.isFeedHeader) {
rss.isFeedHeader = false;
rss.feed = new Feed(rss.title, rss.link, rss.description, rss.language, rss.copyright, rss.pubDate);
}
rss.event = rss.eventReader.nextEvent();
if (rss.event.isEndElement()) {
if (rss.event.asEndElement().getName().getLocalPart() == (rss.ITEM)) {
try {
rss.setAllElements();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
}
}
and as I said one of these class:
for example title:
public class TITLE implements Case {
#Override
public void feedData(RSSFeedParser rss) throws XMLStreamException {
rss.title = rss.getCharacterData(rss.event, rss.eventReader);
rss.eventReader.close();
}
}
Thanks so much for every help!

Related

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());
}
}
}

Chatbot problems

For some reasons i get null pointer errors in the code down. I'm working with a book of examples and trying to make smth mine, but seems like theres a change in java or mistake in book.
I'm making a Chatbot(sort of AI) and can't get it working in java. When i run the program it lets me only write Hi and then it replays.
When i try to give him another word like engi he acts like i always say hi.
If i restart and write first engi, then the error pops up, null pointer for some reason.
Can anyone help?
import java.io.IOException;
import java.util.Scanner;
import org.apache.http.client.ClientProtocolException;
import com.google.gson.*;
public class engibot
{
JsonObject context;
public static void main (String[] args) {
engibot c= new engibot();
Scanner scanner= new Scanner(System.in);
String userUtterance;
do {
System.out.print("User:");
userUtterance=scanner.nextLine();
//end conversation
if (userUtterance.equals("QUIT")) {break;}
JsonObject userInput=new JsonObject();
userInput.add("userUtterance", new JsonPrimitive(userUtterance));
JsonObject botOutput = c.process(userInput);
String botUtterance = "";
if(botOutput !=null && botOutput.has("botUtterance")) {
botUtterance = botOutput.get("botUtterance").getAsString();
}
System.out.println("Bot:" + botUtterance);
}while(true);
scanner.close();
}
public engibot() {
context =new JsonObject();
}
public JsonObject process(JsonObject userInput) {
//step 1: process user input
JsonObject userAction = processUserInput(userInput);
//step 2: update context
updateContext(userAction);
//step 3: identify bot intent
identifyBotIntent();
//step 4: structure output
JsonObject out = getBotOutput();
return out;
}
public JsonObject processUserInput(JsonObject userInput) {
String userUtterance = null;
JsonObject userAction = new JsonObject();
//default case
userAction.add("userIntent", new JsonPrimitive(""));
if(userInput.has("userUtterance")) {
userUtterance= userInput.get("userUtterance").getAsString();
userUtterance=userUtterance.replaceAll("%2C", ",");
}
if (userUtterance.matches("(hi)|(hi | hello)( there)?")) {
userAction.add("userIntent", new JsonPrimitive("greet"));
}
else if (userUtterance.matches("(thanks)|(thank you)")) {
userAction.add("userIntent", new JsonPrimitive("thank"));
}
else if(userUtterance.matches("(engi) | (engagment)")) {
userAction.add("userIntent", new JsonPrimitive("request_engi"));
}
else {
//contextual processing
String currentTask = context.get("currentTask").getAsString();
String botIntent = context.get("botIntent").getAsString();
if(currentTask.equals("requestEngi") && botIntent.equals("requestUserName")) {
userAction.add("userIntent", new JsonPrimitive("inform_name"));
userAction.add("userName", new JsonPrimitive(userUtterance));
}
}
return userAction;
}
public void updateContext(JsonObject userAction) {
//copy userIntent
context.add("userIntent", userAction.get("userIntent"));
String userIntent = context.get("userIntent").getAsString();
if(userIntent.equals("greet")) {
context.add("currentTask", new JsonPrimitive("greetUser"));
}else if (userIntent.equals("request_engi")) {
context.add("currentTask", new JsonPrimitive("requestEngi"));
}else if (userIntent.equals("infrom_city")) {
String userName = userAction.get("userName").getAsString();
Engi userInfo = DB.getUserInfo(userName);
if(!userInfo.get("userName").isJsonNull()) {
context.add("placeOfWeather", userInfo.get("cityCode"));
context.add("placeName", userInfo.get("cityName"));
}
}else if (userIntent.equals("thank")) {
context.add("currenTask", new JsonPrimitive("thankUser"));
}
}
public void identifyBotIntent() {
String currentTask = context.get("currentTask").getAsString();
if(currentTask.equals("greetUser")) {
context.add("botIntent", new JsonPrimitive("greetUser"));
}else if(currentTask.equals("thankUser")) {
context.add("botIntent", new JsonPrimitive("thankUser"));
}else if (currentTask.equals("requestEngi")) {
if (context.get("userName").getAsString().equals("unknown")) {
context.add("botIntent", new JsonPrimitive("requestUserName"));
}
else {
Integer time = -1;
if (context.get("").getAsString().equals("current")) {
time=0;
}
Engi userReport =null;
userReport = DB.getUserInfo(
context.get("userName").getAsString());
if(userReport !=null) {
context.add("userReport", new JsonPrimitive("userReport"));
context.add("botIntent", new JsonPrimitive("informUser"));
}
}
}else {
context.add("botIntent", null);
}
}
public JsonObject getBotOutput() {
JsonObject out=new JsonObject();
String botIntent = context.get("botIntent").getAsString();
String botUtterance="";
if(botIntent.equals("greetUser")) {
botUtterance= "Hi there! I am EngiMan, your engagement bot! " + "What would you like to do? Engage someone or something else?";
}else if(botIntent.equals("thankUser")) {
botUtterance="Thanks for talking to me! Have a great day!!";
}else if (botIntent.equals("requestName")) {
botUtterance="Ok. What's his name?";
}else if(botIntent.equals("informUser")) {
String userDescription= getUserDescription(context.get("userName").getAsString());
String engiIndex= getEngiIndex();
botUtterance = "Ok. "+"Engagment index of "+userDescription+" is"+engiIndex+".";
}
out.add("botIntent", context.get("botIntent"));
out.add("botUtterance", new JsonPrimitive(botUtterance));
return out;
}
private String getEngiIndex() {
return context.get("engiIndex").getAsString();
}
private String getUserDescription(String userName) {
if (userName.equals("current")) {
return "current";
}
return null;
}
}
import com.google.gson.JsonElement;
public class Engi {
private String Name;
private String LastName;
private int Age;
private double EngiIndex;
private String Firm;
private String Team;
public JsonElement get(String string) {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lasteName) {
LastName = lasteName;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public double getEngiIndex() {
return EngiIndex;
}
public void setEngiIndex(double engiIndex) {
EngiIndex = engiIndex;
}
public String getFirm() {
return Firm;
}
public void setFirm(String firm) {
Firm = firm;
}
public String getTeam() {
return Team;
}
public void setTeam(String team) {
Team = team;
}
}

error with scanner object java.util.NoSuchElementException [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 6 years ago.
I have an issue with my program.
The error is "java.util.NoSuchElementException: No line found". I'm search a solution on stack overflow and google but i haven't find a solution.
My source code is :
FormInscreption.java
package ihm;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class FormInscription {
private String nom;
private String prenom;
private Date date_de_naissance;
private String numero_etudiant;
private String adresse;
private String courriel ;
private int numero_passport;
private int numero_permis;
private String role;
private Scanner test2 = new Scanner(System.in);
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDate_de_naissance() {
return date_de_naissance;
}
public void setDate_de_naissance(Date date_de_naissance) {
this.date_de_naissance = date_de_naissance;
}
public String getNumero_etudiant() {
return numero_etudiant;
}
public void setNumero_etudiant(String numero_etudiant) {
this.numero_etudiant = numero_etudiant;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getCourriel() {
return courriel;
}
public void setCourriel(String courriel) {
this.courriel = courriel;
}
public int getNumero_passport() {
return numero_passport;
}
public void setNumero_passport(int numero_passport) {
this.numero_passport = numero_passport;
}
public int isNumero_Permis() {
return numero_permis;
}
public void setNumero_Permis(int numero_permis) {
this.numero_permis = numero_permis;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public void readDate() throws Exception{
String dateFormat = "dd/MM/yyyy";
setDate_de_naissance(new SimpleDateFormat(dateFormat).parse(test2.nextLine()));
test2.close();
}
public FormInscription() {
try {
System.out.println("Entrer le nom :");
this.nom = test2.nextLine();
test2.close();
}
catch(Exception e){
System.out.println("erreur : "+e);
}
}
}
Menu.java
package ihm;
import java.util.Scanner;
public class Menu {
private int choix;
private Scanner sc = new Scanner(System.in);
public Menu(){
System.out.println("==== MENU ====");
System.out.println("1. Inscription");
System.out.println("2. Consultation");
System.out.println("3.Exit");
System.out.println("==============");
System.out.println("Entrez votre choix :");
try{
choix = sc.nextInt();
sc.close();
System.in.close();
}
catch(Exception e){
System.out.println("Erreur :"+e);
}
switch(choix){
case 1 :
app.System.inscription();
break;
case 2 :
System.out.println("Choix encore indisponible...");
break;
case 3 :
System.exit(0);
break;
}
}
}
System.java
package app;
//import java.io.*;
import ihm.*;
public class System {
// Fonction inscription
public static void inscription(){
FormInscription test = new FormInscription();
}
public static void main(String[] args)
{
java.lang.System.out.println("Bienvenue sur le gestionnaire du 4L Trophy");
// On affiche le menu
Menu menu = new Menu();
}
}
Thank you for help,
You should not close the System.in. when you close the Scanner, it internally closes the System.in. Try commenting
sc.close();
in Menu.Java
for more detailed answer check this out Exception in thread "main" java.util.NoSuchElementException: No line found - Using scanner input

How to get Java Object from Json returned by Google Custom Api search

I have following code for retrieving web search results through google custom api
package google.custom.api.results.google.custom.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import com.google.gson.Gson;
public class handler {
public static boolean searchAndSaveGoogleCustomSearch() throws UnsupportedEncodingException
{
String apiKey="AIzaSyB21aUCd8HYMsHgo7APH-98ah-8tLgkPFM";
String cxId="005621018181405156379:yvdukowvdte";
String keyToSearch="News";
String urlToSearch="https://www.googleapis.com/customsearch/v1?key=" +apiKey+ "&cx="+cxId
+"&alt=json"+"&q="+keyToSearch;
try {
URL url=new URL(urlToSearch);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader ( ( conn.getInputStream() ) ) );
GoogleCustomApiResult result = new Gson().fromJson(br, GoogleCustomApiResult.class);
System.out.println(result);
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
public static void main(String[] args) throws UnsupportedEncodingException {
searchAndSaveGoogleCustomSearch();
System.out.println("Google Crawl done.");
}
}
And here's how i have been trying to retrieve the java object from json results
package google.custom.api.results.google.custom.api;
import java.util.List;
public class GoogleCustomApiResult
{
private String link;
private String htmlFormattedUrl;
private List<GoogleCustomApiResult> items;
public String getLink() {
return link;
}
public String getUrl() {
return htmlFormattedUrl;
}
public void setUrl(String htmlFormattedUrl) {
this.htmlFormattedUrl = htmlFormattedUrl;
}
public List<GoogleCustomApiResult> getItems() {
return items;
}
public void setLink(String link) {
this.link = link;
}
public void setGroups(List<GoogleCustomApiResult> items) {
this.items = items;
}
public void getThing (int i) {
System.out.println(items.get(i));
}
public String getLink(int i) {
return items.get(i).toString();
}
public String toString() {
return String.format("%s", link);
}
}
And also using this class
package com.til.et.mynewsletter.core.parser.json.google;
import java.util.List;
public class CustomApiResult
{
private String kind;
private String title;
private String htmlTitle;
private String link;
private String displayLink;
private String snippet;
private String htmlSnippet;
private String cacheId;
private String formattedUrl;
private String htmlFormattedUrl;
//private String htmlSnippet;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getHtmlTitle() {
return htmlTitle;
}
public void setHtmlTitle(String htmlTitle) {
this.htmlTitle = htmlTitle;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDisplayLink() {
return displayLink;
}
public void setDisplayLink(String displayLink) {
this.displayLink = displayLink;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getHtmlSnippet() {
return htmlSnippet;
}
public void setHtmlSnippet(String htmlSnippet) {
this.htmlSnippet = htmlSnippet;
}
public String getCacheId() {
return cacheId;
}
public void setCacheId(String cacheId) {
this.cacheId = cacheId;
}
public String getFormattedUrl() {
return formattedUrl;
}
public void setFormattedUrl(String formattedUrl) {
this.formattedUrl = formattedUrl;
}
public String getHtmlFormattedUrl() {
return htmlFormattedUrl;
}
public void setHtmlFormattedUrl(String htmlFormattedUrl) {
this.htmlFormattedUrl = htmlFormattedUrl;
}
#Override
public String toString() {
return "GoogleCustomApiResult [title=" + title + ", link=" + link + ", snippet=" + snippet + ", cacheId="
+ cacheId + ", formattedUrl=" + formattedUrl + ", htmlFormattedUrl=" + htmlFormattedUrl + "]";
}
But the java object returned is null every time. I am new to Json and do not know how to parse the result to get the java object populated with values.
The Url is returning the result but the values are not going into java object. please help me out.
Looking at your response you're not mapping exactly the same json structure with you model GoogleCustomApiResult cause a lot of fields are missing.
You have two options:
Map the exactly json structure (Don't try to do this cause you have a giant json!)
Parse your response to get the list of objects you want (recommended).
Take a look at JsonParser in Gson API.
Also correct the error in your model class pointed by #Maraboc.

Simple-XML - how to serialize derived classes in a collection?

I want to serialize a object hierarchy including a list of objects which derive from the base class 'Thing'. This works fine, including deserialization - but XML-Simple insists in writing an attribute which specifies the actual used Java-class
when I create a xml file with the java code below, the content is like this:
<example1>
<things>
<fruit class="com.mumpitz.simplexmltest.Apple" id="17">
<sugar>212</sugar>
</fruit>
<fruit class="com.mumpitz.simplexmltest.Orange" id="25" weight="11.2"/>
</things>
</example1>
but this is not what I want.
I'd like to have
<example1>
<things>
<apple id="17">
<sugar>212</sugar>
</apple>
<orange id="25" weight="11.2"/>
</things>
</example1>
'apple' and 'orange' elements without a class attribute, not 'fruit' with such an attribute. Is this possible?
(The second xml complies to a existing schema; adding extra attributes is not an option)
Here's the code:
package com.mumpitz.simplexmltest;
import java.io.File;
import java.util.ArrayList;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
class Fruit {
#Attribute(name = "id")
protected final int id;
Fruit(
#Attribute(name = "id")
int id) {
this.id = id;
}
int getObjectId() {
return id;
}
}
#Root
class Apple extends Fruit {
private final int sugar;
#Element(type = Fruit.class)
public Apple(
#Attribute(name = "id")
int id,
#Element(name = "sugar")
int sugar) {
super(id);
this.sugar = sugar;
}
#Element(name = "sugar")
public int getSugar() {
return this.sugar;
}
#Override
public String toString() {
return "id: " + id + ", sugar: " + sugar;
}
}
#Root
class Orange extends Fruit {
#Attribute
public double weight;
public Orange(
#Attribute(name = "id")
int id) {
super(id);
}
#Override
public String toString() {
return "id: " + id + ", weight: " + weight;
}
}
#Root
public class Example1 {
#ElementList
public ArrayList<Fruit> things = new ArrayList<Fruit>();
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("things:\n");
for (int i=0; i<things.size(); i++) {
sb.append(" " + things.get(i).toString() + "\n");
}
return sb.toString();
}
//////////////////////////////////
static Example1 createDummy() {
Example1 d = new Example1();
d.things.add(new Apple(17, 212));
Orange or = new Orange(25);
or.weight = 11.2;
d.things.add(or);
return d;
}
static String msg;
static Example1 res;
static public String getMessage() {
String m = msg;
msg = null;
return m;
}
static public boolean write(String path) {
Serializer serializer = new Persister();
Example1 example = Example1.createDummy();
File result = new File(path);
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
static public boolean read(String path) {
Serializer serializer = new Persister();
File source = new File(path);
try {
res = serializer.read(Example1.class, source);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
public static Object getResult() {
return res;
}
}
some hours later I found the solution. You simply have to
Read the manual
Use the #ElementListUnion annotation
package com.mumpitz.simplexmltest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
// the base class
#Element
class Thing {
static int count=0;
Thing() {
this.id = ++count;
}
#Attribute
protected int id;
public int getId() {
return id;
}
}
// first derived class
#Element
class Car extends Thing {
#Attribute
private String name;
Car(#Attribute(name="name") String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "ID: " + id + " Car: " + name;
}
}
// second derived class
#Element
class House extends Thing {
#Attribute
private int price;
House(#Attribute(name="price") int price) {
this.price = price;
}
public int getPrice() {
return this.price;
}
#Override
public String toString() {
return "ID: " + id + " House: " + price;
}
}
// a class with a list of base class instances
#Root(name="ListOfThings")
public class Example4 {
// specify the derived classes used in the list
#ElementListUnion({
#ElementList(entry="house", inline=true, type=House.class),
#ElementList(entry="car", inline=true, type=Car.class)
})
private ArrayList<Thing> list = new ArrayList<Thing>();
public void add(Thing t) {
list.add(t);
}
public List<Thing> getProperties() {
return list;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Example4 contains " + list.size() + " elements:\n");
for (Thing t : list) {
sb.append(" " + t.toString() + "\n");
}
return sb.toString();
}
//////////////////////////////////
// test code
//////////////////////////////////
static String msg;
static Example4 res;
static public String getMessage() {
String m = msg;
msg = null;
return m;
}
static private Example4 createDummy() {
Example4 d = new Example4();
d.add(new Car("Mercedes"));
d.add(new House(34000000));
d.add(new Car("VW"));
d.add(new House(230000));
return d;
}
//////////////////////////////////
// serialize / deserialize
//////////////////////////////////
static public boolean write(String path) {
Serializer serializer = new Persister();
File result = new File(path);
Example4 example = Example4.createDummy();
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
static public boolean read(String path) {
Serializer serializer = new Persister();
File source = new File(path);
try {
res = serializer.read(Example4.class, source);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
public static Object getResult() {
return res;
}
}

Categories

Resources