Reading a csv file with Spring Boot application - java

I am trying to convert a Java program I had written to read a csv file into a Spring Boot Application but keep getting a NullPointerException. I just want to print out the contents of the csv file.
Here is the code:
Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="Assembler" class="sample.spring.chapter01.Assembler">
<property name="infopieces" value="classpath:1erelistearticle2.csv"></property>
</bean>
<bean id="PieceDAO" class="sample.spring.chapter01.PieceDAO">
<property name="listp" ref="Piece"></property>
</bean>
<bean id = "Piece" class = "sample.spring.chapter01.Piece"/>
</beans>
Minapp.java
package sample.spring.chapter01;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class MinApp {
private static ApplicationContext context;
private static Logger logger = Logger.getLogger(MinApp.class);
public static void main(String[] args) throws FileNotFoundException, IOException{
context=new ClassPathXmlApplicationContext("Beans.xml");
Resource resource =context.getResource("classpath:1erelistearticle2.csv");
Assembler obj=(Assembler) context.getBean("Assembler");
obj.display();
try {
ArrayList<Piece> listp=obj2.getList();
for (Piece p:listp) {
System.out.println(p);
}
} catch (IOException ef) {
}
}
Assembler.java
package sample.spring.chapter01;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.opencsv.CSVReader;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
public class Assembler {
private PieceDAO listp;
//private CSVParser parser;
private Resource infopieces;
public void setlistp(PieceDAO lp) throws FileNotFoundException, IOException {
fill();
}
public void setinfopieces(Resource csvFile){
this.infopieces = csvFile;
}
public PieceDAO getlistp() {
return listp;
}
public CSVParser getinfocsv() throws FileNotFoundException, IOException{
// BufferedReader br = new BufferedReader(new FileReader("classpath:1erelistearticle.csv"));
//BufferedReader br = new BufferedReader(new FileReader("classpath:1erelistearticle.csv"));
InputStream is=infopieces.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//ClassLoader classloader=Thread.currentThread().getContextClassLoader();
//InputStream is=classloader.getResourceAsStream("classpath:1erelistearticle.csv");
//CSVReader cr=new CSVReader(is);
CSVParser parser = CSVFormat.DEFAULT.withHeader().parse(br);
//CSVParser parser = CSVFormat.DEFAULT.withHeader().parse(is);
//for (CSVRecord record: parser) {
// System.out.println(record.get("référence ascensoriste"));
//}
return parser;
}
public void fill() throws FileNotFoundException, IOException{
CSVParser parser=getinfocsv();
for (CSVRecord record:parser) {
String ref=record.get("référence ascensoriste").trim();
String asc=record.get("ascensoriste").trim();
String desc=record.get("Description article").trim();
String prix=record.get("Pv");
String category=record.get("Familie").trim();
//System.out.println(category);
Piece lift_comp=new Piece();
lift_comp.setasc(asc);
lift_comp.setdesc(desc);
lift_comp.setref(ref);
lift_comp.setprice(prix);
lift_comp.settype(category);
lift_comp.setinfo();
listp.addPiece(lift_comp);
}
}
public void display() {
listp.output();
}
}

There are plenty of problems with the code. I guess the first one is
The call
obj.display();
which calls listp.output(); but the listp is never assigned. neither from config nor from code.

The problem has been solved. The classes and beans.xml are as below and read the csv file using the Spring framework.
Beans.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="PieceDAO" class="sample.spring.chapter01.PieceDAO">
<property name="listp" ref="Piece"></property>
</bean>
<bean id = "Piece" class = "sample.spring.chapter01.Piece"/>
</beans>
Minapp.java
package sample.spring.chapter01;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class MinApp {
private static ApplicationContext context;
private static Logger logger = Logger.getLogger(MinApp.class);
public static void main(String[] args) throws FileNotFoundException, IOException{
context=new ClassPathXmlApplicationContext("Beans.xml");
Resource resource =context.getResource("classpath:1erelistearticle2.csv");
PieceDAO obj=(PieceDAO) context.getBean("PieceDAO");
obj.fill(resource);
obj.display();
}
}
PieceDAO.java
package sample.spring.chapter01;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class PieceDAO {
private List<Piece> listp;
//private Resource resource;
public PieceDAO() {
}
public void setlistp(Piece p) throws FileNotFoundException, IOException{
listp=new ArrayList<Piece>();
//this.fill(resource);
}
public Piece getlistp(Piece p) {
for (Piece currp:listp) {
if (currp.equals(p)) {
return currp;
}
}
return null;
}
public void fill(Resource resource) throws FileNotFoundException, IOException{
InputStream is=resource.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
CSVParser parser = CSVFormat.DEFAULT.withHeader().parse(br);
for (CSVRecord record:parser) {
String ref=record.get("référence ascensoriste").trim();
String asc=record.get("ascensoriste").trim();
String desc=record.get("Description article").trim();
String prix=record.get("Pv");
String category=record.get("Familie").trim();
//System.out.println(category);
Piece lift_comp=new Piece();
lift_comp.setasc(asc);
lift_comp.setdesc(desc);
lift_comp.setref(ref);
lift_comp.setprice(prix);
lift_comp.settype(category);
lift_comp.setinfo();
listp.add(lift_comp);
}
}
public void display() {
for (Piece p:listp) {
System.out.println(p);
}
}
}

Related

Junit Dynamic Test Cases data reading from file?

I have a scenario where to test the api using the payload coming from text file.Each line in file represents one payload.How can I dynamically generate test cases based on the above scenario.
I tried as below calling one test from other ,but i can only see paraent test passed.
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.jayway.restassured.RestAssured.given;
public class ExampleTest
{
private TestUtil testUtil;
String payload;
#Before
public void init()
{
testUtil = new TestUtil();
}
#Test
public void runAllTests() throws IOException
{
List<String> request = getFileDataLineByLine();
for(String fileRequest:request)
{
payload=fileRequest;
if(null!=payload) {
testExampleTest();
}
}
}
#Test
public void testExampleTest()
{
String uri = "http://localhost:8080/url";
Response response = given()
.contentType(ContentType.JSON)
.body(payload)
.post(uri)
.then()
.statusCode(200)
.extract()
.response();
}
private List<String> getFileDataLineByLine() throws IOException {
File file = testUtil.getFileFromResources();
if (file == null)
return null;
String line;
List<String> stringList = new ArrayList<>();
try (FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader))
{
while ((line = br.readLine()) != null)
{
stringList.add(line);
System.out.println(line);
}
}
return stringList;
}
File Reading Class:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class TestUtil
{
public File getFileFromResources()throws IOException
{
TestUtil testUtil = new TestUtil();
File file = testUtil.getFileFromResources("testdata.txt");
return file;
}
// get file from classpath, resources folder
private File getFileFromResources(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file is not found!");
} else {
return new File(resource.getFile());
}
}
}
How can i generate test cases dynamically by taking input from file?
If you can convert your file JUnitParams supports loading data from a CSV.
Using an example from the above link's repository:
public class PersonTest {
#Test
#FileParameters("src/test/resources/test.csv")
public void loadParamsFromCsv(int age, String name) {
assertFalse(age > 120);
}
}

ISSUES with Monitor folder, consume WebService and send files via FTP Outbound channel

I'm having bad time dealing with a simple application that must monitor a folder for new files, take each file and consume RESTful service ( one of my other apps) and send the response files using spring integration FTP Outbound channel adapter
It has following structure:
Initializer:
package com.ftpoutbound;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import com.ftpoutbound.client.FtpoutboundApp;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FtpoutboundApp.class);
}
}
I define beans in FtpoutboundApp:
package com.ftpoutbound.client;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.ftp.outbound.FtpMessageHandler;
import org.springframework.integration.ftp.session.DefaultFtpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import com.ftpoutbound.monitor.MonitorDirectory;
#Configuration
#SpringBootApplication
#ComponentScan({ "com.ftpoutbound" })
#IntegrationComponentScan
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableScheduling
public class FtpoutboundApp implements ApplicationContextAware {
final static Logger logger = Logger.getLogger(FtpoutboundApp.class);
#Autowired
private MonitorDirectory monitor;
#Autowired
MyGateway gateway;
#Value("${remotedirectory}")
private String remotedirectory;
#Value("${remotehost}")
private String remotehost;
#Value("${remoteport}")
private int remoteport;
#Value("${remoteuser}")
private String remoteuser;
#Value("${remotepassword}")
private String remotepassword;
#Value("${outbound214sname}")
private String outbound214sname;
public static void main(String[] args) {
SpringApplication.run(FtpoutboundApp.class, args);
}
public void createGateway(File file214) {
try {
gateway.sendToFtp(file214);
file214.delete();
} catch (Exception e) {
logger.error("ERROR APP OUTBOUND\n");
logger.error(e);
}
}
#Bean
public SessionFactory<FTPFile> ftpSessionFactory() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost(remotehost);
sf.setPort(remoteport);
sf.setUsername(remoteuser);
sf.setPassword(remotepassword);
return new CachingSessionFactory<FTPFile>(sf);
}
#Bean
#ServiceActivator(inputChannel = "ftpChannel")
public MessageHandler handler() {
FtpMessageHandler handler = new FtpMessageHandler(ftpSessionFactory());
handler.setRemoteDirectoryExpression(new LiteralExpression(remotedirectory));
handler.setFileNameGenerator(new FileNameGenerator() {
#Override
public String generateFileName(Message<?> message) {
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
String time = new SimpleDateFormat("HHmmssssssss").format(new Date());
return outbound214sname + "." + date + time;
}
});
return handler;
}
#MessagingGateway
public interface MyGateway {
#Gateway(requestChannel = "ftpChannel")
void sendToFtp(File file);
}
#EventListener
public void afterApplicationReady(ApplicationReadyEvent event) {
try {
logger.info("INICIO DE MONITOREO DE ARCHIVOS HG");
monitor.startMonitoring();
} catch (IOException e) {
logger.error("ERROR EN MONITOREO DE FOLDER ENTRADA ARCHIVOS HG:\n" + e);
} catch (InterruptedException e) {
logger.error("INTERRUPCIÓN EN MONITOREO DE FOLDER ENTRADA ARCHIVOS HG:\n" + e);
}
}
#Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
}
The monitor started from the FtpoutboundApp:
I'm using SCHEDULED annotation since Watchservice was not working either
package com.ftpoutbound.monitor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.ftpoutbound.client.FtpoutboundApp;
import com.ftpoutbound.restfulclient.httpPost;
#Component
public class MonitorDirectory {
final static Logger logger = Logger.getLogger(MonitorDirectory.class);
#Autowired
private httpPost httppost;
#Value("${inboundhgfilesfolder}")
private String inboundhgfilesfolder;
#Value("${inboundhgfilesfolderbak}")
private String inboundhgfilesfolderbak;
#Value("${hglin}")
private String hglin;
#Scheduled(fixedRate = 10000)
public void startMonitoring() throws IOException, InterruptedException {
try {
listFiles();
} catch (Exception e) {
logger.error("ERROR MONITOREANDO FOLDER");
logger.error(e);
}
}
public void listFiles() throws Exception {
File directory = new File(inboundhgfilesfolder);
File[] fList = directory.listFiles();
for (File file : fList) {
String fileName = file.getName();
if (file.isFile()) {
readFile(fileName);
Thread.sleep(1000);
}
}
}
public void readFile(String fileName) throws IOException {
String hgFile = fileName.substring(0, 7);
if (hgFile.equals(hglin)) {
InputStream input = new FileInputStream(inboundhgfilesfolder + fileName);
StringBuilder builder = new StringBuilder();
int ch;
while ((ch = input.read()) != -1) {
builder.append((char) ch);
}
try {
httppost.get214fromRestful(builder.toString());
} catch (Exception e) {
logger.error("ERROR EN POST REQUEST DESDE APP OUTBOUND:\n" + e);
}
}
moveFile(fileName);
}
public void moveFile(String fileName) {
Path source = Paths.get(inboundhgfilesfolder + fileName);
Path newdir = Paths.get(inboundhgfilesfolderbak + fileName);
try {
Files.move(source, newdir);
} catch (IOException e) {
logger.error("ERROR MOVIENDO ARCHIVO:\n" + e);
}
}
}
And the HTTPclient that consumes the RESTful app
package com.ftpoutbound.restfulclient;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.ftpoutbound.client.FtpoutboundApp;
#Component
public class httpPost {
final static Logger logger = Logger.getLogger(httpPost.class);
#Value("${restful214url}")
private String restful214url;
#Value("${outbound214sfolder}")
private String outbound214sfolder;
#Autowired
private FtpoutboundApp ftpoutbound;
public void get214fromRestful(String hgfile) throws Exception {
logger.info("OBTENIENDO 214");
logger.info("DIRECCION" + restful214url);
logger.info("ARCHIVO" + hgfile);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(restful214url, hgfile, String.class);
File file = createFile214local(result.toString());
logger.info("RESULTADO DE POST:");
logger.info(result.toString());
ftpoutbound.createGateway(file);
}
private File createFile214local(String hgfile) {
logger.info("ESCRIBIENDO 214");
File file = new File(outbound214sfolder + "214.tmp");
try {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(hgfile);
bw.close();
} catch (IOException e) {
logger.error("ERROR ESCRIBIENDO FILE:\n->" + e);
}
return file;
}
}
but the app seems not working, it freezes before consuming the RESTful in:
logger.info("OBTENIENDO 214");
logger.info("DIRECCION" + restful214url);
logger.info("ARCHIVO" + hgfile);
I noticed these lines are printed twice in the log, still not sure if this is a threads issue or what causes the APP to not even finish the deployment in the server, I have another similar App (except that one doesn't consume RESTful) and it works OK, another FTPInbound channel Adapter and it works OK, but I have some days figuring what I'm missing or What's the best way to do this.
Believe me, Help will be extremely appreciated.
The issue was that
my outbound channel configuration class was implementing ApplicationContextAware and it was causing the RestTemplate to freezes the App when consuming my Microservices App, so I changed to extend SpringBootServletInitializer and implement WebApplicationInitializerand it worked.

Printing results from PDF box output to a text file

I am working on a class which Parses a PDF document with PDF Box, its purpose is to create a text file (its name is PdfTestFile.txt) with the results. We have gotten it to print the parsed text to the console, but I don't know how to make it write the results to the .txt file that the class creates (name is PdfTestFile.txt).
I tried to use out.print(Text); but it gives me an error saying that:
out cannot be resolved
The class PdfEasyManager calls the class EasySearch in which we see the error mentioned above.
Below is the code that I have where the String Text is what I would like to print to the file PdfTestFile.txt:
Class " PdfEasyManager":
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class PdfEasyManager {
static BufferedWriter writer;
public static void main(String[] args) throws IOException {
//writer = new BufferedWriter(new FileWriter("Evergreen.txt"));
EasySearch easysearch = new EasySearch();
// pdfManager.setFilePath("PDFextTEST.pdf");
System.out.println(easysearch.ToText());
//out.println(easysearch.ToText());
}
}
Class "EasySearch" :
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class EasySearch {
private PDFParser parser;
private PDFTextStripper pdfStripper;
private PDDocument pdDoc ;
private COSDocument cosDoc ;
private String Text ;
private String filePath;
private File file;
static BufferedWriter writer;
//writer = new BufferedWriter(new FileWriter(BLnumber + (date.toString().substring(4, 10))+ ".org"));
public EasySearch() {
}
//public static void main(String args[]) throws Exception{
public String ToText() throws IOException
{
this.pdfStripper = null;
this.pdDoc = null;
this.cosDoc = null;
writer = new BufferedWriter(new FileWriter("PdfTestFile.txt"));
file = new File("C:/Users/Jon Smith/Desktop/Sample.pdf");
parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
pdDoc.getNumberOfPages();
pdfStripper.setStartPage(1);// reading text from page 1
// pdfStripper.setEndPage(10);// to 10
pdfStripper.setEndPage(pdDoc.getNumberOfPages());// if you want to get text from full pdf file use this code
Text = pdfStripper.getText(pdDoc);
out.print(Text); //this is the line that gives me the error
return Text;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
You are using out which is not present in your class. Use System.out.print(Text).
Thanks for the help but
writer.write(Text);
solves the issue I was having

Exception java.lang.NullPointerException with list

I can't find the mistake java.lang.NullPointerException in the line 'e = servidor.listarTrinos();' listaTrinosSistema is empty. Skip ServicioDatosInterface and Trino.
package Basededatos;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import Common.Gui;
import Common.ServicioDatosInterface;
import Common.Trino;
import Common.Utils;
public class Basededatos {
private static ServicioDatosImpl servidor;
public static void main(String[] args) throws Exception {
Utils.setCodeBase(ServicioDatosInterface.class);
ServicioDatosImpl servidor = new ServicioDatosImpl();
ServicioDatosInterface remote = (ServicioDatosInterface)UnicastRemoteObject.exportObject(servidor, 8888);
Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
registry.rebind("Pepito", remote);
menu();
}
public static void menu() throws RemoteException{
int opt = 0;
do {
opt = Gui.menu("Menu Base de Datos", new String[]{ "listarTrinos" });
switch (opt) {
case 0: listarTrinos(); break;
}
}
while (opt != 1);
}
public static void listarTrinos() throws RemoteException{
List<Trino> e;
e = servidor.listarTrinos();
System.out.print("Trinos enviados");
Iterator<Trino> nombreIterator = e.iterator();
while(nombreIterator.hasNext()){
String elemento = nombreIterator.next().toString();
System.out.print(elemento+" / ");
}
}
}
package Basededatos;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import Common.ServicioDatosInterface;
import Common.Trino;
public class ServicioDatosImpl implements ServicioDatosInterface{
private List<Trino> listaTrinosSistema = new ArrayList<Trino>();
public List<Trino> listarTrinos() throws RemoteException{
//if (listaTrinosSistema.isEmpty() == true || listaTrinosSistema.size()==0) return null;
//else return listaTrinosSistema;
return listaTrinosSistema;
}
private static ServicioDatosImpl servidor;
This declares a static variable
public static void main(String[] args) throws Exception {
Utils.setCodeBase(ServicioDatosInterface.class);
ServicioDatosImpl servidor = new ServicioDatosImpl();
and this declares and initializes a local variable which has the same name as the static variable. The static variable stays null. It should be
servidor = new ServicioDatosImpl()
If you have a NPE on e = servidor.listarTrinos() then servidor is null.
This is because you have a static attribute servidor and you create a variable servidor in the main method.

Marshaling exception when using jaxb

I have java code and i'm trying to parse it and store it as XML file on my PC using JAXB but i have a marshaling exception:
Exception in thread "main" javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an #XmlRootElement annotation]
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:311)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:236)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:103)
at xml.ConfList.addToList(ConfList.java:29)
at xml.Tester.work(Tester.java:34)
at xml.Tester.main(Tester.java:16)
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an #XmlRootElement annotation
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:237)
at com.sun.xml.internal.bind.v2.runtime.LeafBeanInfoImpl.serializeRoot(LeafBeanInfoImpl.java:126)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:483)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308)
... 5 more
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)
The JAXB code i'm using :
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class ConfList {
private static final String fileName = "Source.xml";
List<String> xmlConfList;
private Object object;
public ConfList(Object object){
this.object = object;
}
public void addToList() throws IOException, JAXBException {
File file = new File(fileName);
JAXBContext jaxbContext = JAXBContext.newInstance(XmlConf.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(object, file); // i got the exception here
jaxbMarshaller.marshal(object, System.out);
}
}
The main class i use:
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import org.xml.sax.SAXException;
public class Tester{
public static void main (String [] args) throws XPathExpressionException, IOException, ParserConfigurationException, SAXException, TransformerException, JAXBException{
work();
}
public static void work () throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException, JAXBException{
String surl = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=Cairo&format=xml&num_of_days=1&key=wd63kxr294rcgvbynhaf2z4r";
XmlSource xml = new XmlSource(surl);
xml.validate();
xml.load();
ArrayList<String> paths = xml.getAllPaths();
for(String path : paths){
System.out.println(path);
}
ConfList v = new ConfList(xml.getXml());
v.addToList();
}
}
The XmlConf Class :
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "XmlSource")
public class XmlConf {
private URL url;
private List<String> path = new ArrayList<String>();
private String urlp;
private Map<String, String> parameters;
private String host;
public URL getUrl() {
return url;
}
#XmlAttribute(name = "URL")
public void setUrl(URL url) {
this.url = url;
}
#XmlElement
public List<String> getPath() {
return path;
}
public void setPath(String path) {
this.path.add(path);
}
#XmlElement
public void setUrlPath(String urlp){
this.urlp = urlp;
}
public String getUrlPath(){
return urlp;
}
public void setParameters(Map<String, String> parameters){
this.parameters = parameters;
}
public Map<String, String> getParameters(){
return parameters;
}
public void setHostName(String host){
this.host = host;
}
public String getHostName(){
return host;
}
}
Note that all (XmlSource class) methods are run correctly.
Below is some sample code that unmarshals some XML into an instance of XmlConf and then marshals it back to XML.
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(XmlConf.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum16762200/input.xml");
XmlConf xmlConf = (XmlConf) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(xmlConf, System.out);
}
}
input.xml/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<XmlSource URL="http://www.example.com">
<parameters>
<entry>
<key>A</key>
<value>a</value>
</entry>
<entry>
<key>B</key>
<value>b</value>
</entry>
</parameters>
<path>foo</path>
<urlPath>bar</urlPath>
</XmlSource>

Categories

Resources