I am trying to create a report using itextpdf. Everything is fine when I run the program. But I have a problem if I execute this command java -jar myproject.jar and I have the error below. I already added the itextpdf to the library, I don't understand why I got this error. Could someone explain it to me and show me how to fix this?
Thanks.
Exception in thread "main" java.lang.NoClassDefFoundError: com/itextpdf/text/DocumentException
at xxx.yyy.main(yyy.java:24)
Caused by: java.lang.ClassNotFoundException: com.itextpdf.text.DocumentException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
The below is my code for creating a pdf file
public void savePDF(String path) throws FileNotFoundException, BadElementException, IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
Document doc = new Document();
doc.setPageSize(PageSize.A4.rotate());
doc.setMargins(50f, 50f, 10f, 10f);
PdfWriter writer = PdfWriter.getInstance(doc, fos);
doc.open();
try {
doc.add(headerTable());
} catch (BadElementException | IOException ex) {
Logger.getLogger(createBeamCalculationsPDF.class.getName()).log(Level.SEVERE, null, ex);
}
addSeparatorLine(doc);
doc.add(generalProperties());
doc.newPage();
doc.close();
writer.close();
fos.close();
} catch (DocumentException ex) {
Logger.getLogger(createBeamCalculationsPDF.class.getName()).log(Level.SEVERE, null, ex);
}
}
Related
I have a Spring Batch process
I want to use a relative path to writre spring batch exception usong a csv file, but it refuse, it missing an absolute path, why?
the file is : fo
My code :
public class MyJob {
File fo=new File("C:\\Users\\m.youneb\\Documents\\icdc\\cecWorkplace\\saveLines\\src\\main\\resources\\csv\\skip.csv");
#Bean
public Step step() throws IOException {
return steps.get("step")
.<Person, Person>chunk(5)
.reader(itemReader())
.processor(itemProcessor())
.writer(itemWriter())
.faultTolerant()
.skip(IllegalArgumentException.class)
.skip(FlatFileParseException.class)
.skipLimit(100)
.listener(new MySkipListener(fo))
.skip(Exception.class)
.build();
}
public static class MySkipListener implements SkipListener<Person, Person> {
//private FileWriter fileWriter;
private BufferedWriter bw = null;
public MySkipListener(File file) throws IOException {
//this.fileWriter = new FileWriter(file);
bw= new BufferedWriter(new FileWriter(file, true));
System.out.println("MySkipListener =========> :"+file);
}
#Override
public void onSkipInRead(Throwable throwable) {
if (throwable instanceof FlatFileParseException) {
FlatFileParseException flatFileParseException = (FlatFileParseException) throwable;
System.out.println("onSkipInRead =========> :");
try {
bw.write(flatFileParseException.getInput()+"Vérifiez les colonnes!!");
bw.newLine();
bw.flush();
// fileWriter.close();
} catch (IOException e) {
System.err.println("Unable to write skipped line to error file");
}
}
}
}
I need to work with relative path, Thanks.
To work with a relative path to your file, you can use:
File fo = new File("src/main/resources/csv/skip.csv"); // should work on windows
This assumes you are running your JVM in the directory containing src/main/resources, which is usually the root directory of a typical maven project.
Hope this helps.
is there some way on how to open powershell with process builder in javafx and keep it opened to execute any command anytime?
Example code(executing only one command at a time):
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "powershell -Command \"Add-Type -AssemblyName System.DirectoryServices.AccountManagement; [System.DirectoryServices.AccountManagement.UserPrincipal]::Current.DisplayName\"&&exit");
Process p = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
displayname = line;
}
}
reader.close();
p.waitFor();
p.destroy();
} catch (IOException | InterruptedException ex) {
Logger.getLogger(AccountStatus.class.getName()).log(Level.SEVERE, null, ex);
}
Reason to keep it opened: loading powershell takes maybe 3 seconds and loading for example active directory plugin takes another maybe 2 seconds everytime i want to execute some command. If there is some way on how to preload powershell and send command to processbuilder anytime it would be very helpfull, thanks for advices.
EDIT:
I have found solution here: Apache Commons exec PumpStreamHandler continuous input
Thanks to MichalVales!
With this quick sample i am able to open powershell, keep it opened, preload some module and execute any new command anytime without loading all again.
public class FXMLDocumentController implements Initializable {
private BufferedWriter writer;
#FXML
private void handleButtonAction(ActionEvent event) {
try {
writer.write("Import-Module ActiveDirectory -Cmdlet Get-ADUser\n");
writer.flush();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#FXML
private void handleButtonAction2(ActionEvent event) {
try {
writer.write("Get-ADUser somenamehere -Properties * | Select-Object LockedOut\n");
writer.flush();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
ProcessBuilder builder = new ProcessBuilder("powershell.exe");
Process process;
try {
process = builder.start();
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
StreamReader outputReader = new StreamReader(process.getInputStream(), System.out);
outputReader.start();
StreamReader err = new StreamReader(process.getErrorStream(), System.err);
err.start();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
StreamReader code can be found on link from MichalVales
EDIT2:
I was trying to pass czech characters with any writer, but without success. I think that its impossible to pass czech characters like "ěščřžýáíé" to powershell without changing system locale, but i dont want to do it. I have tried processbuilder, apache exec, all failed, but i have found super library which works and is really easy to use:
jPowerShell
So if you have problems with keeping powershell alive or problem with characters, this is the best solution.
I've been struggling with my code:
private void longStart() {
Task task = new Task<Void>() {
#Override
protected Void call() throws Exception {
System.out.println("Iniciando");
IOManager io = new IOManager();
System.out.println("Buscando archivo Jugadores");
boolean b = io.BuscarData("Jugadores");
System.out.println("Armando Grupos");
if (!b) {
ServiceManager.CargarGrupos(b);
} else {
if (!io.BuscarData("Grupos")) {
ServiceManager.CargarGrupos(b);
}else{
Grupo.setaGrupos(io.LeerGrupos());
}
}
System.out.println("Cargando Partidos");
ServiceManager.CargarPartidos();
System.out.println("Calculando puntos de Grupos");
ServiceManager.ActualizarPuntos();
//ServiceManager.CargarGoleador();
ready.setValue(Boolean.TRUE);
notifyPreloader(new StateChangeNotification(StateChangeNotification.Type.BEFORE_START));
return null;
}
};
new Thread(task).start();
}
To put it simply, what it does is to ask if a file exists and if it doesn't, then it connects with a web service, does some meaningless object creations and finally creates the File. After all that hustle I can start my UI like this:
try {
root = FXMLLoader.load(getClass().getResource("/fxml/Main.fxml"));
} catch (IOException ex) {
Logger.getLogger(Brasuca.class.getName()).log(Level.SEVERE, null, ex);
}
stage.setTitle("Brasil 2014");
stage.setScene(new Scene(root, 1140, 705));
stage.getIcons().add(new Image("/img/trophy.png"));
stage.setResizable(false);
stage.show();
Which works perfectly when the File its looking for doesn't exist. But when it does Exists it tries to read it:
public ArrayList<Grupo> LeerGrupos() throws FileNotFoundException, IOException, ClassNotFoundException {
ArrayList<Grupo> ag;
try (ObjectInputStream obj = new ObjectInputStream(new FileInputStream("data/Grupos.jug"))) {
ag = (ArrayList<Grupo>) obj.readObject();
}
return ag;
}
Which also works fine, but when the FXMLLoader tries to load, it fails and throws this exception:
GRAVE: null
javafx.fxml.LoadException:
file:/C:/Users/Francisco/Documents/NetBeansProjects/Brasuca/dist/run613176200/Brasuca.jar!/fxml/Main.fxm
Also, if I excecute the loader like this:
root = FXMLLoader.load(getClass().getResource("fxml/Main.fxml"));
The exception changes into:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Location is required.
Any help would be apretiated
root = FXMLLoader.load(getClass().getResource("/fxml/Main.fxml"));
Don't forget the "/" when you try to load fxml class because of it is another package.
I'm working with one problematic report and it always throws the same exception when client JRE is not the same as server's. This is an RMI app and the exception only occours with this report.
Report
It's a simple report, however it has an barcode component, and I've used 2 implementations offered by iReport 5.0.1 (Barbecue and Barcode4j) and both thrown the same exception:
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.io.InvalidClassException: javax.swing.JComponent;
local class incompatible:
stream classdesc serialVersionUID = -2790168081368361182,
local class serialVersionUID = 5670834184508236790
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:191)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at $Proxy17.geraRelatorio(Unknown Source)
at base.gui.reports.ReportsPrinter.showReport(ReportsPrinter.java:151)
at base.gui.reports.ReportsPrinter.showReport(ReportsPrinter.java:139)
at jacad.gui.cadastros.curso.FrameCadastroPeriodoLetivo$30.executaAtividade(FrameCadastroPeriodoLetivo.java:1499)
at jdaap.gui.components.loader.Loader$1.doInBackground(Loader.java:70)
at jdaap.gui.components.loader.Loader$1.doInBackground(Loader.java:1)
at javax.swing.SwingWorker$1.call(SwingWorker.java:296)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at javax.swing.SwingWorker.run(SwingWorker.java:335)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.io.InvalidClassException: javax.swing.JComponent;
local class incompatible:
stream classdesc serialVersionUID = -2790168081368361182,
ocal class serialVersionUID = 5670834184508236790
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:604)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1601)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
I don't know what do now, I've tried everything I could to fix this, I don't believe that error was caused by Java code because this app have +- 300 reports, and only this one has a barcode. Here's a sample of Java code to call this report by RMI:
public JasperPrint executeReport(String reportFile, Map parameters) throws GenericException {
FileInputStream is = (FileInputStream) getReportFile(reportFile);
Connection conn = getConnection();
JasperPrint print = null;
try {
parameters.put("P_REPORTS_PATH", Application.getInstance().getReportsPath());
parameters.put(JRParameter.REPORT_LOCALE, new Locale("pt", "BR"));
print = JasperFillManager.fillReport(Application.getInstance().getReportsPath() + reportFile, parameters, conn);
} catch (JRException e1) {
e1.printStackTrace();
throw new GenericException(e1);
}
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return print;
}
Client side:
public static void view(final JasperPrint print) throws GenericException {
if (print == null) {
throw new GenericException("Nenhuma visualização do relatório foi informada.");
}
new SwingWorker() {
#Override
protected Void doInBackground() throws Exception {
JFrame viewer = new JFrame("Visualização do Relatório"); //$NON-NLS-1$
viewer.setPreferredSize(new Dimension(800, 600));
viewer.setLocationRelativeTo(null);
JasperViewer jrViewer = new JasperViewer(print, true);
viewer.getContentPane().add(jrViewer.getContentPane());
new FrameConfig(viewer);
return null;
}
}.execute();
}
public void showReport(String reportFile, Map parameters) throws GenericException {
if (reportFile == null)
throw new GenericException("Report file não pode ser nulo.");
ReportsManager rm;
try {
rm = (ReportsManager) FacadeFactoryLocal.newInstance(ReportsManager.class);
JasperPrint jasperPrint = rm.geraRelatorio(reportFile, parameters);
view(jasperPrint);
} catch (RemoteException e1) {
e1.printStackTrace();
throw new GenericException("Erro ao acessar o servidor para gerar o relatório.", e1.getStackTrace());
}
}
Does anyone have a solution for this?
Thanks in advance.
Don't serialize Swing components. There is a warning about that at the head of the Javadoc of every one of them. Serialized the underlying model.
I use a servlet to access a folder outside the web container to load some graphics to web application by using GWT. I use the following snippet in servlet to test the idea:
String s = null;
File inputFile = new File("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");
FileInputStream fin = null;
try {
fin = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte c[] = new byte[(int) inputFile.length()];
try {
fin.read(c);
} catch (IOException e) {
e.printStackTrace();
}
try {
fin.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String imgFolderPath = getServletContext().getRealPath("/")+"img";
File imgFolder = new File(imgFolderPath);
imgFolder.mkdir();
File newImage = new File("megan-fox.jpg");
FileOutputStream fout = null;
try {
fout = new FileOutputStream(newImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fout.write(c);
} catch (IOException e) {
e.printStackTrace();
}
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
boolean success = newImage.renameTo(new File(imgFolderPath, newImage.getName()));
The code in servlet reads the image file from the specified folder in hard disk, creates a new folder called 'img' in war folder and copies to it the jpg file. Then it returns to the client the path to the image (for now hardcoded as) '/img/megan-fox.jpg'.
The client then uses the Image class in GWT with the returned path-string to display the image, like in the following snippet:
public void onSuccess(String result) {
String myImage = result;
image = new Image(myImage);
RootPanel.get().add(image);
closeButton.setFocus(true);
}
I need to know if there is a way to achieve the same result without using the 'intermediate' step of creating a folder in the web container root (optional) and copying the file there in order to access it with Image GWT class and display it?
updated: The original servlet class.
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Get the absolute path of the image
ServletContext sc = getServletContext();
// i want to load the image in the specified folder (outside the web container)
String filename = sc.getRealPath("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
sc.log("Could not get MIME type of "+filename);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
resp.setContentType(mimeType);
// Set content size
File file = new File(filename);
resp.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
// This is the method that is called from the client using GWT-RPC
public String greetServer(String input) throws IllegalArgumentException {
HttpServletRequest req = this.getThreadLocalRequest();
HttpServletResponse res = this.getThreadLocalResponse();
try {
doGet(req, res);
} catch (IOException e) {
e.printStackTrace();
}
// actually i dont know what that means but i thought i would have to returned something like the image's url?
return res.encodeURL("/img/image0.png");
}
}
I logically misused the method that was proposed to solve my problem. What is the correct way?
Sure, just have your servlet serve the image directly:
Set the Content-Type header to image/jpeg.
Write out image file contents to servlet response writer.
Here is an example.