Initialize an object on the arraylist.get.set method? - java

I'm new at this.
I have something like this:
{
libri.get(i).setUtenteAssegnato(**Utente**); How do i create an Utente instance with user inputs?
}
Utente class:
package Biblioteca;
public class Utente
{
private String nome;
private String cognome;
public Utente (String unNome, String unCognome)
{
this.nome=unNome;
this.cognome=unCognome;
}
public String getNome()
{
return nome;
}
public String getCognome()
{
return cognome;
}
public String toString()
{
return (this.nome + this.cognome);
}
}
This is the Libro class, with setUtenteAssegnato method:
package Biblioteca;
public class Libro
{
private int codice;
private String titolo;
private Utente utenteAssegnato;
public Libro (int unCodice, String unTitolo)
{
this.codice = unCodice;
this.titolo = unTitolo;
this.utenteAssegnato = null;
}
public Utente getUtenteAssegnato()
{
return this.utenteAssegnato;
}
public void setUtenteAssegnato(Utente utenteAssegnato)
{
this.utenteAssegnato = utenteAssegnato;
}
public int getCodice()
{
return codice;
}
public String getTitolo()
{
return titolo;
}
public String toString()
{
return (this.codice + this.titolo + this.utenteAssegnato);
}
}
This is the class i'm having problem with:
package Biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Biblioteca
{
List<Libro> libri = new ArrayList<Libro>();
List<Utente> utenti = new ArrayList<Utente>();
public Biblioteca ()
{
}
public void aggiungiUtente (String unNome, String unCognome)
{
Utente u1 = new Utente (unNome, unCognome);
utenti.add(u1);
}
public void aggiungiLibro(int unCodice, String unTitolo)
{
Libro l1 = new Libro (unCodice, unTitolo);
libri.add(l1);
}
public void creaPrestito (int unCodice, String unCognome)
{
boolean codiceTrovato = false;
boolean cognomeTrovato = false;
int i;
int j;
for (i=0; i<libri.size(); i++)
{
if (libri.get(i).getCodice() == (unCodice))
{
System.out.println("Codice trovato. ");
codiceTrovato = true;
}
else
{
System.out.println("Codice non trovato. ");
}
}
for (j=0; j<utenti.size(); j++)
{
if (utenti.get(j).getCognome().equals(unCognome))
{
System.out.println("Utente trovato. ");
cognomeTrovato = true;
}
else
{
System.out.println("Utente non trovato. ");
}
}
if (codiceTrovato && cognomeTrovato)
{
**libri.get(i).setUtenteAssegnato(Utente);**
}
}
public String toString()
{
String stampa = ", ";
for(Libro d : libri)
{
stampa += d.toString();
}
return stampa;
}
}
Basically, i don't know how to set the object in the arraylist (i) position from input (it should be 2 strings, right?)
Do i have to create another instance of Utente?

Related

Age filter in Java with ArrayList

I want to make a method that tells me who is the oldest person in the ArrayList and who is the youngest person. The method will receive the arraylist that i want to apply the method, i have 3 in my code, each one is an contact list.
The method is suppose to return the name of the person, but i don't know how to do it. Familia, Profissional and Amigos are my arraylists and "idade" = age and "nome" = name.
package com.company;
public class Contato {
public String nome;
public int idade;
public String sexo;
public String profissao;
public String telefone;
public String email;
public Contato(String nome, int idade, String sexo, String profissao, String telefone, String email) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
this.telefone = telefone;
this.email = email;
}
#Override
public String toString() {
return "" +
nome + ',' +
idade + " anos de idade, " +
"do sexo " + sexo + ',' +
profissao + ',' +
" telefone nº " + telefone + ", " +
"e-mail:" + email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GestaoContatos extends Contato {
ArrayList<Contato> Familia = new ArrayList();
ArrayList<Contato> Amigos = new ArrayList();
ArrayList<Contato> Profissional = new ArrayList();
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
}
public void adicionaContato(String nomeAgenda, Contato contato) {
if( nomeAgenda == "Familia"){
Familia.add(contato);
} else
if(nomeAgenda == "Amigos"){
Amigos.add(contato);
} else
if(nomeAgenda == "Profissional") {
Profissional.add(contato);
} else
System.out.println("Indispnível");
}
public void eliminaContato(String nomeContato) {
for(int i = 0; i < Familia.size(); i++) {
if(getFamilia().contains(nomeContato)) {
Familia.remove(nomeContato);
}
}
}
public void printaLista(String nomeAgenda){
if(nomeAgenda.equals("Familia")) {
Familia.forEach(System.out::println);
}
if(nomeAgenda.equals("Amigos")) {
Amigos.forEach(System.out::println);
}
if(nomeAgenda.equals("Profissional")) {
Profissional.forEach(System.out::println);
}
else {
throw new RuntimeException("Opcao invalida");
}
}
public void tooString() {
var contatos = new ArrayList<Contato>();
Familia.forEach(it -> contatos.add(it));
Amigos.forEach(it -> contatos.add(it));
Profissional.forEach(it -> contatos.add(it));
System.out.println(contatos.toString());
}
public void olderPerson(String nomeAgenda){
int i = 0;
if (nomeAgenda.equals("Amigos")) {
for (i = 0; Familia.size(); i++) {
Familia.stream().filter();
}
}
}
public void geraListaBinaria() throws IOException {
var file = new File("C:\\Users\\Jorge Luiz\\Desktop\\contatos.txt");
var writer = new FileWriter(file.getName());
writer.write(this.getProfissional().toString());
writer.write(this.getFamilia().toString());
writer.write(this.getProfissional().toString());
writer.close();
}
public ArrayList<Contato> getFamilia() {
return Familia;
}
public void setFamilia(ArrayList<Contato> familia) {
Familia = familia;
}
public ArrayList<Contato> getAmigos() {
return Amigos;
}
public void setAmigos(ArrayList<Contato> amigos) {
Amigos = amigos;
}
public ArrayList<Contato> getProfissional() {
return Profissional;
}
public void setProfissional(ArrayList<Contato> profissional) {
Profissional = profissional;
}
}
If you want to return oldest person in one list:
public Contato oldestPerson(String nomeAgenda){
return Familia.stream()
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
For all lists you can do:
public Contato oldestPerson(){
return Stream.of(Familia, Amigos, Profissional)
.flatMap(Collection::stream) // flatting to one long stream
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade))
.get();
}
EDIT
Based on the comment, we should change a couple of things to achieve what you want. First, we should define a Map<String, List<Contato>> and populate it in the constructor:
private Map<String, List<Contato>> contatoGroups;
private static final String familiaKey = "Familia";
private static final String amogisKey = "Amigos";
private static final String profissionalKey = "Profissional";
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
contatoGroups.put(familiaKey, new ArrayList<>());
contatoGroups.put(amogisKey, new ArrayList<>());
contatoGroups.put(profissionalKey, new ArrayList<>());
}
(Consider using enum instead of String as key in the map)
Then wherever you want to get a group, for example: Familia, you should do:
List<Contato> contatoes = contatoGroups.get(familiaKey);
And then we should change the oldestPerson() like this:
public Contato oldestPerson(String nomeAgenda){ // nomeAgenda could be "Familia", "Amigos"...
List<Contato> selectedGroup = contatoGroups.get(nomeAgenda);
return selectedGroup.stream()
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}

Codehaus Jackson JSON data to POJO Can not deserialize instance ... out of START_ARRAY token

I am convert a json data into POJO with array of objects using Codehaus Jackson.
I am having problems with the array of objects. I am getting errors like "Can not deserialize instance ... out of START_ARRAY token".
Below are my codes
JSON Data (flightItineraryPrice.json)
{
"tripType": "OneWay",
"tripInfos":[
{
"from":"EARTH",
"to":"MOON",
"fromSchedule":"2015-12-21T04:30:00",
"toSchedule":"2015-12-21T06:50:00"
},
{
"from":"MOON",
"to":"MARS",
"fromSchedule":"2015-12-21T03:30:00",
"toSchedule":"2015-12-21T011:10:00"
},
{
"from":"VENUS",
"to":"KEPLER",
"fromSchedule":"2015-12-21T01:30:00",
"toSchedule":"2015-12-21T22:30:00"
},
{
"from":"EARTH",
"to":"SUN",
"fromSchedule":"2015-12-20T02:30:00",
"toSchedule":"2015-12-29T15:10:00"
}
],
"adultFare":{
"paxType":"ADT",
"baseFare":"1000",
"totalFeesAndTaxes":"300",
"totalAmount":"1300.00"
},
"childFare":{
"paxType":"CHD",
"baseFare":"750",
"totalFeesAndTaxes":"250",
"totalAmount":"1000.00"
},
"infantFare":{
"paxType":"INF",
"baseFare":"250",
"totalFeesAndTaxes":"25",
"totalAmount":"275.00"
},
"adultCount":"1",
"childCount":"1",
"infantCount":"2"
}
Class (JacksonFlightItineraryPrice.java)
package com.jgtt.samples;
import java.util.*;
import org.codehaus.jackson.annotate.JsonProperty;
public class JacksonFlightItineraryPrice {
private String tripType;
#JsonProperty("tripInfos")
private JacksonFlightItineraryPrice.TripInfo tripInfos;
private JacksonFlightItineraryPrice.PaxFare adultFare;
private JacksonFlightItineraryPrice.PaxFare childFare;
private JacksonFlightItineraryPrice.PaxFare infantFare;
private short adultCount;
private short childCount;
private short infantCount;
public JacksonFlightItineraryPrice() {}
public String getTripType() {
return (this.tripType);
}
public void setTripType(String tripType) {
this.tripType = tripType;
}
public JacksonFlightItineraryPrice.TripInfo getTripInfos() {
return (this.tripInfos);
}
public void setTripInfos(JacksonFlightItineraryPrice.TripInfo tripInfos) {
this.tripInfos = tripInfos;
}
public JacksonFlightItineraryPrice.PaxFare getAdultFare() {
return (this.adultFare);
}
public void setAdultFare(JacksonFlightItineraryPrice.PaxFare adultFare) {
this.adultFare = adultFare;
}
public JacksonFlightItineraryPrice.PaxFare getChildFare() {
return (this.childFare);
}
public void setChildFare(JacksonFlightItineraryPrice.PaxFare childFare) {
this.childFare = childFare;
}
public JacksonFlightItineraryPrice.PaxFare getInfantFare() {
return (this.infantFare);
}
public void setInfantFare(JacksonFlightItineraryPrice.PaxFare infantFare) {
this.infantFare = infantFare;
}
public short getAdultCount() {
return (this.adultCount);
}
public void setAdultCount(short adultCount) {
this.adultCount = adultCount;
}
public short getChildCount() {
return (this.childCount);
}
public void setChildCount(short childCount) {
this.childCount = childCount;
}
public short getInfantCount() {
return (this.infantCount);
}
public void setInfantCount(short infantCount) {
this.infantCount = infantCount;
}
public static class TripInfo {
private List<JacksonFlightItineraryPrice.FlightInfoParameter> flightInfoParameters;
public List getFlightInfoParameters() {
return (this.flightInfoParameters);
}
public void setFlightInfoParameters(List flightInfoParameters) {
this.flightInfoParameters = flightInfoParameters;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[\n");
if(null != flightInfoParameters){
sb.append(" flightInfoParameters:\n");
boolean isFirst = true;
for(FlightInfoParameter f : flightInfoParameters){
if(!isFirst){
sb.append(",\n");
}
sb.append(f);
isFirst = false;
}
sb.append("\n");
}
else {
sb.append(" flightInfoParameters=null\n");
}
sb.append("]");
return sb.toString();
}
}
public static class FlightInfoParameter {
private String from;
private String to;
private String fromSchedule;
private String toSchedule;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getFromSchedule() {
return fromSchedule;
}
public void setFromSchedule(String fromSchedule) {
this.fromSchedule = fromSchedule;
}
public String getToSchedule() {
return toSchedule;
}
public void setToSchedule(String toSchedule) {
this.toSchedule = toSchedule;
}
#Override
public String toString() {
return "User [ "+from+"(" + fromSchedule + ") -> " + to + "(" + toSchedule + ") ]";
}
}
public static class PaxFare {
private String paxType;
private Double baseFare;
private Double totalFeesAndTaxes;
private Double totalAmount;
public String getPaxType() {
return paxType;
}
public void setPaxType(String paxType) {
this.paxType = paxType;
}
public Double getBaseFare() {
return baseFare;
}
public void setBaseFare(Double baseFare) {
this.baseFare = baseFare;
}
public Double getTotalFeesAndTaxes() {
return totalFeesAndTaxes;
}
public void setTotalFeesAndTaxes(Double totalFeesAndTaxes) {
this.totalFeesAndTaxes = totalFeesAndTaxes;
}
public Double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Double totalAmount) {
this.totalAmount = totalAmount;
}
#Override
public String toString() {
return "User [paxType=" + paxType + ", baseFare=" + baseFare + ", totalFeesAndTaxes" + totalFeesAndTaxes + ", totalAmount=" + totalAmount + "]";
}
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[\n");
sb.append(" tripType=" + tripType + ",\n");
sb.append(" tripInfos=" + tripInfos + ",\n");
sb.append(" adultFare=" + adultFare + ",\n");
sb.append(" childFare=" + childFare + ",\n");
sb.append(" infantFare=" + infantFare + ",\n");
sb.append(" adultCount=" + adultCount + ",\n");
sb.append(" childCount=" + childCount + ",\n");
sb.append(" infantCount=" + infantCount + "\n]");
return sb.toString();
}
}
Main Application (JacksonExample.java)
package com.jgtt.samples;
import java.util.*;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.TypeReference;
import org.codehaus.jackson.map.type.CollectionType;
import org.codehaus.jackson.map.type.TypeFactory;
public class JacksonExample {
private static void flightJsonToPojo(){
ObjectMapper mapper = new ObjectMapper();
try {
String file_url = "d:\\Work files\\Java Test Codes\\Jackson\\flightItineraryPrice.json";
File jsonFile = new File(file_url);
JacksonFlightItineraryPrice flightInfo = mapper.readValue(jsonFile, JacksonFlightItineraryPrice.class);
System.out.println(flightInfo);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
flightJsonToPojo();
}
}
The only part in the json data that I am having problem with is the "tripInfos" because its value is an arraylist of objects. If I remove tripInfos... everything works fine... but I really needed it also.
Hope somebody can show me the way :)
The class JacksonFlightItineraryPrice has one attribute tripInfos that isn't an array:
#JsonProperty("tripInfos")
private JacksonFlightItineraryPrice.TripInfo tripInfos;
and TripInfo has flightInfoParameters as a List of List<JacksonFlightItineraryPrice.FlightInfoParameter>
But in your json tripInfos is an array of JacksonFlightItineraryPrice.FlightInfoParameter.
Instead it should be:
{
"tripType": "OneWay",
"tripInfos": {
"flightInfoParameters" : [
{
"from":"EARTH",
"to":"MOON",
"fromSchedule":"2015-12-21T04:30:00",
"toSchedule":"2015-12-21T06:50:00"
},
{
"from":"MOON",
"to":"MARS",
"fromSchedule":"2015-12-21T03:30:00",
"toSchedule":"2015-12-21T011:10:00"
},
{
"from":"VENUS",
"to":"KEPLER",
"fromSchedule":"2015-12-21T01:30:00",
"toSchedule":"2015-12-21T22:30:00"
},
{
"from":"EARTH",
"to":"SUN",
"fromSchedule":"2015-12-20T02:30:00",
"toSchedule":"2015-12-29T15:10:00"
}
]
},
"adultFare":{
"paxType":"ADT",
"baseFare":"1000",
"totalFeesAndTaxes":"300",
"totalAmount":"1300.00"
},
"childFare":{
"paxType":"CHD",
"baseFare":"750",
"totalFeesAndTaxes":"250",
"totalAmount":"1000.00"
},
"infantFare":{
"paxType":"INF",
"baseFare":"250",
"totalFeesAndTaxes":"25",
"totalAmount":"275.00"
},
"adultCount":"1",
"childCount":"1",
"infantCount":"2"
}
or if you cannot change the JSON, then in JacksonFlightItineraryPrice the property tripInfos should be a list of FlightInfoParameter :
#JsonProperty("tripInfos")
private List<JacksonFlightItineraryPrice.FlightInfoParameter> tripInfos;

how to populate jcombobox with arrays that match specific criteria

When i try my code below the list isn't be populated with the specific arrays please help i'm pretty new to coding GUI in netbeans
private void bookingListJCBActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0;i<dataSource.getBookingList().size();i++){
Bookings tempBooking = dataSource.getBookingList().get(i);
boolean tempFinish = tempBooking.getFinish();
String tempMechanic = tempBooking.getMechanic();
String tempClerk = tempBooking.getClerk();
String tempService = tempBooking.getService();
if(tempFinish == true){
bookingListJCB.addItem(tempBooking);
mechanicJTF.setText(tempMechanic);
seriveceClerkJTF.setText(tempMechanic);
serviceJTF.setText(""+tempService );
finishJTF.setText(""+tempFinish);
}
}
// TODO add your handling code here:
}
Here is the Bookings class how i don't know why the combo box isn't displaying anything
public class Bookings {
private String vehicle;
private String clerk;
private String service;
private String mechanic;
private boolean finish;
public Bookings() {
}
public Bookings(String vehicle, String clerk, String service, String mechanic, boolean finish) {
this.vehicle = vehicle;
this.clerk = clerk;
this.service = service;
this.mechanic = mechanic;
this.finish = finish;
}
public String getVehicle() {
return vehicle;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
}
public String getClerk() {
return clerk;
}
public void setClerk(String clerk) {
this.clerk = clerk;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getMechanic() {
return mechanic;
}
public void setMechanic(String mechanic) {
this.mechanic = mechanic;
}
public boolean getFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
#Override
public String toString() {
return "Bookings{" + "vehicle=" + vehicle + ", clerk=" + clerk + ", service=" + service + ", mechanic=" + mechanic + ", finish=" + finish + '}';
}
}

How to read an ArrayList from a File into another ArrayList?

I trying to read an arraylist from a file into another arraylist but I keep getting errors. The file is called eventos.dat and the arraylist is from the type Evento. I want to create a new ArrayList<Evento> with the objects from the array on the file. Here is the method i'm using:
public class ListaEventos implements Serializable{
private ArrayList<Evento> eventos = new ArrayList();
public String adicionarEvento(Evento novo){
for (Evento evento : eventos) {
if(novo.equals(evento)){
return "Evento já existe";
}
}
eventos.add(novo);
return "ADICIONEI";
}
public ArrayList<Evento> getEventos() {
return eventos;
}
public Evento procuraEvento(String tituloEvento){
for (Evento evento : eventos){
if(tituloEvento.equals(evento.getTitulo())){
return evento;
}
}
return null;
}
public String editaEvento(Evento antigo, Evento novo){
for (int i=0;i<eventos.size();i++){
if(antigo.equals(eventos.get(i))){
eventos.get(i).setTitulo(novo.getTitulo());
eventos.get(i).setData(novo.getData());
eventos.get(i).setDescricao(novo.getDescricao());
eventos.get(i).setLocal(novo.getLocal());
eventos.get(i).setPrivado(novo.getPrivado());
return "Editei evento";
}
}
return "Evento não existe";
}
public String removeEvento(String removeTitulo){
Evento aux= procuraEvento(removeTitulo);
if(aux != null){
eventos.remove(aux);
return "Evento removido!";
}
return "Evento não existe";
}
public void gravaFicheiro(){
try{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Eventos.dat"));
out.writeObject(eventos);
out.close();
}
catch(IOException ex){
System.out.println("Não conseguiu gravar");
}
}
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException{
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
}
here is the Evento class:
public class Evento implements Serializable {
private String titulo = "Nao preenchido";
private String data = "Nao preenchido";
private String local = "Nao preenchido";
private String descricao = "Nao preenchido";
private String privado = "Nao preenchido";
private ArrayList<Contacto> convidados = new ArrayList();
public Evento() {
}
public Evento(String titulo, String data, String local, String descricao, String privado) {
this.titulo = titulo;
this.data = data;
this.local = local;
this.descricao = descricao;
this.privado = privado;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setData(String data) {
this.data = data;
}
public void setLocal(String local) {
this.local = local;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setPrivado(String privado) {
this.privado = privado;
}
public String getTitulo() {
return titulo;
}
public String getData() {
return data;
}
public String getLocal() {
return local;
}
public String getDescricao() {
return descricao;
}
public String getPrivado() {
return privado;
}
public ArrayList<Contacto> getConvidados() {
return convidados;
}
public void setConvidados(ArrayList<Contacto> convidados) {
this.convidados = convidados;
}
public String adicionaConvidado(String nomeConvidado){
Contacto novo = new Contacto();
for (Contacto contacto : this.convidados) {
if(nomeConvidado.equals(contacto.getNome())){
return "Contacto já foi convidado";
}
}
novo.setNome(nomeConvidado);
novo.setEmail("");
novo.setTelefone("");
convidados.add(novo);
return "ADICIONEI CONVIDADO";
}
public Evento(String titulo, String local) {
this.titulo = titulo;
this.local = local;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Evento other = (Evento) obj;
if (!Objects.equals(this.titulo, other.titulo)) {
return false;
}
if (!Objects.equals(this.data, other.data)) {
return false;
}
if (!Objects.equals(this.local, other.local)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Evento{" + "titulo=" + titulo + ", data=" + data + ", local=" + local + ", descricao=" + descricao + ", privado=" + privado + ", convidados=" + convidados + '}';
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
Changed the method CarregaEvento to:
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException {
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
No errors but still doesn't work.
eventos=(ArrayList<Evento>) in.readObject();
This will not create a new type of an ArrayList<Evento>.
although you can create a new instance of an Evento with the String that is provided when you read the text file. you can use the split(String par1) method in the String class to create a new instance of Evento and add it to an arraylist.
refer to the JavaDocs for more info on splitting.

parse xml nested nodes that repeat with SAX

I have looked for days and I can't seem to wrap my head around my issue. I have been able to parse the xml doc but it has child nodes that repeat before moving back up to the parent node. My parser seems to be iterating through the child nodes correctly but I can only see the results of the last child node which is repeated multiple times.
If a parent node contains 5 child nodes, it prints the result of the last of the 5 nodes 5 times.
I need the xml tags after "portfolio" and "trade" to parse correctly. Ultimately get the xml tags before the tag to line up and print with the child nodes after "trade" without repeating the last node inside "trade"
Examples are appreciated
Thank you
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
//List to hold trade object
private List<Portfolio> tradeList = null;
private Portfolio trd = null;
//getter method for trade list
public List<Portfolio> getEmpList() {
return tradeList;
}
boolean bdate = false;
boolean bfirm = false;
boolean bacctId = false;
boolean bUserId = false;
boolean bseg = false;
boolean btradedate = false;
boolean btradetime = false;
boolean bec = false;
boolean bexch = false;
boolean bpfcode = false;
boolean bpftype = false;
boolean bpe = false;
boolean btradeqty = false;
boolean btradeprice = false;
boolean bmore = false;
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("portfolio")) {
trd = new Portfolio();
//initialize list
if (tradeList == null)
tradeList = new ArrayList<>();
} else if (qName.equalsIgnoreCase("firm")) {
bfirm = true;
} else if (qName.equalsIgnoreCase("acctId")) {
bacctId = true;
} else if (qName.equalsIgnoreCase("UserId")) {
bUserId = true;
} else if (qName.equalsIgnoreCase("seg")) {
bseg = true;
} else if (qName.equalsIgnoreCase("trade")) {
} else if (qName.equalsIgnoreCase("tradedate")) {
btradedate = true;
} else if (qName.equalsIgnoreCase("tradetime")) {
btradetime = true;
} else if (qName.equalsIgnoreCase("ec")) {
bec = true;
} else if (qName.equalsIgnoreCase("exch")) {
bexch = true;
} else if (qName.equalsIgnoreCase("pfcode")) {
bpfcode = true;
} else if (qName.equalsIgnoreCase("pftype")) {
bpftype = true;
} else if (qName.equalsIgnoreCase("pe")) {
bpe = true;
} else if (qName.equalsIgnoreCase("tradeqty")) {
btradeqty = true;
} else if (qName.equalsIgnoreCase("tradeprice")) {
btradeprice = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("trade")) {
tradeList.add(trd);
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bfirm) {
//age element, set Employee age
trd.setFirm(new String(ch, start, length));
bfirm = false;
} else if (bacctId) {
trd.setAcctId(new String(ch, start, length));
bacctId = false;
} else if (bUserId) {
trd.setUserId(new String(ch, start, length));
bUserId = false;
} else if (bseg) {
trd.setSeg(new String(ch, start, length));
bseg = false;
} else if (btradedate) {
trd.setTradedate(new String(ch, start, length));
btradedate = false;
} else if (btradetime) {
trd.setTradetime(new String(ch, start, length));
btradetime = false;
} else if (bec) {
trd.setEC(new String(ch, start, length));
bec = false;
} else if (bexch) {
trd.setExch(new String(ch, start, length));
bexch = false;
} else if (bpfcode) {
trd.setPFCode(new String(ch, start, length));
bpfcode = false;
} else if (bpftype) {
trd.setPFType(new String(ch, start, length));
bpftype = false;
} else if (bpe) {
trd.setPE(new String(ch, start, length));
bpe = false;
} else if (btradeqty) {
trd.setTradeQty(new String(ch, start, length));
btradeqty = false;
} else if (btradeprice) {
trd.setTradePrice(new String(ch, start, length));
btradeprice = false;
// bmore = false;
}
}
}
Here is an example of my xml file
<?xml version="1.0"?>
<XMLFiletoparse>
<created>201311290419</created>
<pointInTime>
<date>20131129</date>
<portfolio>
<firm>999</firm>
<acctId>1234G5689</acctId>
<UserId>11AA</UserId>
<seg>ABC</seg>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:30:00</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>0</tradeQty>
<tradePrice>1.11111</tradePrice>
</trade>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:30:00</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>10</tradeQty>
<tradePrice>2.22222</tradePrice>
</trade>
</portfolio>
<portfolio>
<firm>888</firm>
<acctId>454588784KI</acctId>
<UserId>LMNO3</UserId>
<seg>ABC</seg>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:31:08</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>6</tradeQty>
<tradePrice>3.58965</tradePrice>
</trade>
</portfolio>
</pointInTime>
</XMLFiletoparse>
Here is portfolio class
import java.io.Serializable;
public class Portfolio implements Serializable {
private String date = null;
private String firm = null;
private String acctId = null;
private String UserId = null;
private String seg = null;
private String tradedate = null;
private String tradetime = null;
private String ec = null;
private String exch = null;
private String pfcode = null;
private String pftype = null;
private String pe = null;
private String tradeqty = null;
private String tradeprice = null;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFirm() {
return firm;
}
public void setFirm(String firm) {
this.firm = firm;
}
public String getAcctId() {
return acctId;
}
public void setAcctId(String acctId) {
this.acctId = acctId;
}
public String getUserId() {
return UserId;
}
public void setUserId(String UserId) {
this.UserId = UserId;
}
public String getSeg() {
return seg;
}
public void setSeg(String seg) {
this.seg = seg;
}
public String getTradedate() {
return tradedate;
}
public void setTradedate(String tradedate) {
this.tradedate = tradedate;
}
public String getTradetime() {
return tradetime;
}
public void setTradetime(String tradetime) {
this.tradetime = tradetime;
}
public String getEC() {
return ec;
}
public void setEC(String ec) {
this.ec = ec;
}
public String getExch() {
return exch;
}
public void setExch(String exch) {
this.exch = exch;
}
public String getPFCode() {
return pfcode;
}
public void setPFCode(String pfcode) {
this.pfcode = pfcode;
}
public String getPFType() {
return pftype;
}
public void setPFType(String pftype) {
this.pftype = pftype;
}
public String getPE() {
return pe;
}
public void setPE(String pe) {
this.pe = pe;
}
public String getTradeQty() {
return tradeqty;
}
public void setTradeQty(String tradeqty) {
this.tradeqty = tradeqty;
}
public String getTradePrice() {
return tradeprice;
}
public void setTradePrice(String tradeprice) {
this.tradeprice = tradeprice;
}
#Override
public String toString() {
return "Date: " + this.date + " Firm: " + this.firm + " Acct ID: " + this.acctId + " User ID: " + this.UserId +
" Seg: " + this.seg + " tradedate: " + this.tradedate + " tradetime: " + this.tradetime +
" EC: " +this.ec+ " Exch: " +this.exch+ " PFCode: " +this.pfcode+ " PFType: " +this.pftype+
" PE: " + this.pe + " Trade Qty: " + tradeqty + " Trade Price: " + tradeprice;
}
You are seeing last child node result only, in case of multiple trade node in portfolio, because you are initializing trd after encountering portfolio tag, and it appears it can only store info about 1 trade. So, when there are 2 or more trade tags, same portfolio object gets modified. Now since Java works with call by reference at the background, the object you added in the list also gets updated as trd and object in list points to same memory area.
There could be two solutions to your problem:
1. Modify Portfolio class to store more than 1 trade data. (This should be the implementation based on your XML structure)
2. Move line trd = new Portfolio() inside else if (qName.equalsIgnoreCase("trade"))
I am posting an updated portfolio class. I had to essentially save the parent node values to a variable and pass them with the children node variables to be inserted into a database with all fields populated with the proper data. The variables for the parent node only update with a new value when the next parent node is reached. This kept the integrity of the data correct row to row.
package risk_mgnt_manager;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class Portfolio implements Serializable {
final private static String JDBC_CONNECTION_URL = "com.mysql.jdbc.Driver";
final private static String DB_URL = "jdbc:mysql://123.456.789.123/DB_Name";
final private static String USER = "user";
final private static String PASS = "pass";
private Connection connection;
private String firm = null;
private String acctId = null;
private String UserId = null;
private String seg = null;
private String tradedate = null;
private String tradetime = null;
private String ec = null;
private String exch = null;
private String pfcode = null;
private String pftype = null;
private String pe = null;
private String tradeqty = null;
private String tradeprice = null;
private String ffirm = null;
private String facctId = null;
private String fUserId = null;
private String fseg = null;
private String ftradedate = null;
private String ftradetime = null;
private String fec = null;
private String fexch = null;
private String fpfcode = null;
private String fpftype = null;
private String fpe = null;
private String ftradeqty = null;
private String ftradeprice = null;
private List results;
//parent nodes with if else statements check if there is new value for variable
public String getFirm() {
return firm;
}
public void setFirm(String firm) {
this.firm = firm;
if(firm == null){
ffirm = ffirm;
} else {
ffirm = firm;
}
}
public String getAcctId() {
return acctId;
}
public void setAcctId(String acctId) {
this.acctId = acctId;
if(acctId == null){
facctId = facctId;
} else {
facctId = acctId;
}
}
public String getUserId() {
return UserId;
}
public void setUserId(String UserId) {
this.UserId = UserId;
if(UserId == null){
fUserId = fUserId;
} else {
fUserId = UserId;
}
}
public String getSeg() {
return seg;
}
public void setSeg(String seg) {
this.seg = seg;
if(seg == null){
fseg = fseg;
} else {
fseg = seg;
}
}
// no if else statement from here on out. this is the child node data and
// it is always present
public String getTradedate() {
return tradedate;
}
public void setTradedate(String tradedate) {
this.tradedate = tradedate;
ftradedate = tradedate;
}
public String getTradetime() {
return tradetime;
}
public void setTradetime(String tradetime) {
this.tradetime = tradetime;
ftradetime = tradetime;
}
public String getEC() {
return ec;
}
public void setEC(String ec) {
this.ec = ec;
fec = ec;
}
public String getExch() {
return exch;
}
public void setExch(String exch) {
this.exch = exch;
fexch = exch;
}
public String getPFCode() {
return pfcode;
}
public void setPFCode(String pfcode) {
this.pfcode = pfcode;
fpfcode = pfcode;
}
public String getPFType() {
return pftype;
}
public void setPFType(String pftype) {
this.pftype = pftype;
fpftype = pftype;
}
public String getPE() {
return pe;
}
public void setPE(String pe) {
this.pe = pe;
fpe = pe;
}
public String getTradeQty() {
return tradeqty;
}
public void setTradeQty(String tradeqty) {
this.tradeqty = tradeqty;
ftradeqty = tradeqty;
}
public String getTradePrice() {
return tradeprice;
}
public void setTradePrice(String tradeprice) {
this.tradeprice = tradeprice;
ftradeprice = tradeprice;
// data from parser is sent to list
toList(ffirm,facctId,fUserId,fseg,ftradedate,tradetime,fec,fexch,
fpfcode,fpftype,fpe,ftradeqty,ftradeprice);
}
/*
This will ultimately be the setup to import the list into my database
I only printed the results to make sure I am getting the correct output
*/
public void toList(String a,String b,String c,String d,String e,String f,
String g,String h,String i,String j,String k,String l,String m){
importData(ffirm,facctId,fUserId,fseg,ftradedate,tradetime,fec,fexch,
fpfcode,fpftype,fpe,ftradeqty,ftradeprice);
}
// public void importData(final List<String> results){
public void importData(String firm,String acctid,String userid,String seg,String trdDate,String trdTime,
String ec,String exch,String pfcode,String pftype,String pe,String trdQty,String trdPrice){
connection = null;
try {
Class.forName(JDBC_CONNECTION_URL);
connection = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
String query = "INSERT INTO t_datarlt_trades_wrk (Firm, AcctId, UserID"
+ ", seg, tradedate, tradetime, ec, exch, pfcode, pftype, pe"
+ ", tradeqty, tradeprice) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
connection.setAutoCommit(false);
PreparedStatement stmt = connection.prepareStatement(query);
// for(String result : results){
stmt.setString(1, firm);
stmt.setString(2, acctid);
stmt.setString(3, userid);
stmt.setString(4, seg);
stmt.setString(5, trdDate);
stmt.setString(6, trdTime);
stmt.setString(7, ec);
stmt.setString(8, exch);
stmt.setString(9, pfcode);
stmt.setString(10, pftype);
stmt.setString(11, pe);
stmt.setString(12, trdQty);
stmt.setString(13, trdPrice);
stmt.addBatch();
// }
stmt.executeBatch();
connection.commit();
//STEP 6: Clean-up environment
stmt.close();
connection.close();
} catch(SQLException sqle) {
System.out.println("SQLException : " + sqle);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories