jasper report does not show up when executing the jar file - java

it works fine in when I run it in Netbeans but it's won't show in executable jar file here's my codes
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
rep.siapkan_report_dengan_parameter("report4.jrxml", "Report", "periode",tCari.getText());
this.setCursor(Cursor.getDefaultCursor());
}
public void siapkan_report_dengan_parameter(
String nama_report,
String direktori,
String namaparameter,
String isiparameter){
konek.openConnection();
Properties systemProp = System.getProperties();
// Ambil current dir
String currentDir = systemProp.getProperty("user.dir");
File dir = new File(currentDir);
String reportName = nama_report;
String reportDirName = direktori;
File fileRpt;
String fullPath = "";
if (dir.isDirectory()) {
String[] isiDir = dir.list();
for (int i = 0; i < isiDir.length; i++) {
fileRpt = new File(currentDir + File.separatorChar + isiDir[i] + File.separatorChar +
reportDirName + File.separatorChar + reportName);
if (fileRpt.isFile()) { // Cek apakah file ada
fullPath = fileRpt.toString();
}
}
}
String[] subRptDir = fullPath.split(reportName);
try {
// Persiapkan parameter untuk Report
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(namaparameter, isiparameter);
try {
JasperReport JRpt = JasperCompileManager.compileReport(fullPath);
JasperPrint JPrint = JasperFillManager.fillReport(JRpt, parameters,konek.conn);
if(JPrint.getPages().isEmpty()){
JOptionPane.showMessageDialog(null,
"Data Untuk Kriteria :\n" + isiparameter +"\nTidak Ada",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}else{
JasperViewer.viewReport(JPrint, false);
}
} catch (Exception rptexcpt) {
JOptionPane.showMessageDialog(null,
"a",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"b",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
}
thanks in advance!
my libraries are:
common-beanutils-1.7
commons-collections-2.1
commons-digester-1.7
commons-javaflow-20060411
commons-logging-1.1
jasperreports-3.0.1
jdt-compiler-3.1.1
jfreechart-1.0.3
poi-3.0.1-FINAL-20070705

The problem is that you are not loading jasper report as a stream. So, try adding this:
InputStream st = getClass().getResourceAsStream(fullPath);
try {
JasperDesign jd = JRXmlLoader.load(st);
JasperReport JRpt = JasperCompileManager.compileReport(jd);
JasperPrint JPrint = JasperFillManager.fillReport(JRpt, parameters,konek.conn);
if(JPrint.getPages().isEmpty()){
JOptionPane.showMessageDialog(null,
"Data Untuk Kriteria :\n" + isiparameter +"\nTidak Ada",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}else{
JasperViewer.viewReport(JPrint, false);
}
} catch (Exception rptexcpt) {
JOptionPane.showMessageDialog(null,
"a",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
Also, add your .jrxml files in some package in your project before you export it to .jar.
Path (fullPath) you will pass will be something like: /com/report/nameofreport.jrxml.

Problem is not with your code... Just add following libraries. Don't use latest jasper libraries. that is the reason to not load your reports through jar executable. (use ireport 5.5.0 libraries). Code i use is below
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
org.apache.log4j.BasicConfigurator.configure(new NullAppender());
//InputStream st = getClass().getResourceAsStream("/Reports/SalesInvoiceCustomerCopy.jrxml");
try
{
Connection connect = conn.open();
String report2 = "H:\\Higher Diploma Project\\FinalHD\\src\\Reports\\SalesInvoiceCustomerCopy.jrxml";
JasperReport rep2 = JasperCompileManager.compileReport(report2);
JasperPrint rep_print2 = JasperFillManager.fillReport(rep2,null,connect);
JasperPrintManager.printReport(rep_print2,false);
String report = "H:\\Higher Diploma Project\\FinalHD\\src\\Reports\\SalesInvoice.jrxml";
JasperReport rep = JasperCompileManager.compileReport(report);
JasperPrint rep_print = JasperFillManager.fillReport(rep,null,connect);
JasperPrintManager.printReport(rep_print,false);
try
{
pst =conn.open().prepareStatement("INSERT INTO invoice_balanace VALUES (?,?,?,?)") ;
pst.setString(1, txtInvoiceNo.getText());
pst.setString(2, txtValue.getText());
pst.setString(3, totDisc.getText());
pst.setString(4, txtNetVal.getText());
pst.executeUpdate();
}catch(Exception e){JOptionPane.showMessageDialog(null, e);}
idUpdater();
}catch(Exception e){JOptionPane.showMessageDialog(null,""+ e);}
}

It is not quite efficient to use a compiled jasper report into your jar file. I'll suggest you reference the report from a location on your pc e.g., C: drive.
It'll also be Best if you have a permanent folder that can be easily accessed. It could be C:/<project name>/report/<your-report>.
This approach enables you to distribute it with ease.

Related

delete image from the folder

I want to delete one image from the folder when I delete a user from the table with this image. Here is my code:
//first I can the function that finds a path of the image in the folder
public void deleteStudent(String name) {
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call delete_student(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
statement.executeQuery();
} catch (Exception c) {
c.printStackTrace();
}
//After I call the function to delete image from directory
deleteImageDerictory(name);
}
This method allows choosing the image from the directory when I get the image I add the path in jTextField1.getText().
//use this method to get the path of my image.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpeg", "jpg", "png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result ==JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
//GET ABSOLUTE PATH OF PICTURES
jTextField1.setText(selectedFile.getAbsolutePath());
//addPicture.setText(selectedFile.getName());
//GET NAME OF PICTURES
//getPicName = selectedFile.getName();
} else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("File not found!");
}
}
//I use this method to call another method deleteImageDerictory(jTextField1.getText());
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
deleteImageDerictory(jTextField1.getText());
}catch(Exception e) {
e.printStackTrace();
}
}
public void deleteImageDerictory(String name) {
String pictureName = null;
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call get_picture(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
myResults = statement.executeQuery();
while (myResults.next()) {
//COPY PATH IN pictureName
pictureName = myResults.getString(1);
}
myResults.close();
} catch (Exception c) {
c.printStackTrace();
}
//DELETE ELEMENT FROM FOLDER
File sourceFile = new File(pictureName);
File file = new File("/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/");
images = file.listFiles();
File file2 = new File(file.getAbsolutePath(), sourceFile.getName() );
boolean deleted = file2.delete();
System.out.println(deleted);
}
I just don't know how to delete image from folder when I find it. Any ideas?
You can use the modern and more powerful java.nio.* instead of the old fashioned java.io.File. You just have to create a Path object containing the path to the folder where the images are stored and resolve the file name:
//DELETE ELEMENT FROM FOLDER
Path imagesPath = Paths.get(
"/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/" +
pictureName);
try {
Files.delete(imagesPath);
System.out.println("File "
+ imagesPath.toAbsolutePath().toString()
+ " successfully removed");
} catch (IOException e) {
System.err.println("Unable to delete "
+ imagesPath.toAbsolutePath().toString()
+ " due to...");
e.printStackTrace();
}
EDIT due to discussion in comments below:
This is a very simple approach that deletes a file chosen via JFileChooser:
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path pathToBeDeleted = Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(pathToBeDeleted);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have just tried it myself and it successfully removes the chosen file.
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView()./0());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path data= Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to get jasper report to load from jar file?

How do you get a compiled jasper report to load from within the jar file, instead of via a specific path on your hard drive?
My report was working fine on my machine as I had set the path to the reports with:
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
But the reports were not loading when working from the finished jar on a different computer. So I am trying to use Input stream and passing it to JasperFillManager but nothing is working - the InputStream is not finding the files. Have I the path wrong?
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
My original working code:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasperReport1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasperReport2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
And now the changed code that is not working:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasper1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasper2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
Any help greatly appreciated!
Ok update: I got the InputStreams to work by creating a new package called "reports" and using
InputStream jasper1 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg2.jasper");
And this works fine in Netbeans BUT it still won't load the files when I compile to jar!!?
Any ideas what I'm doing wrong?
you should put jasper reports in
yourapp/src/main/resources/reports
then you invoke that reports from class java
JasperReport jp = JasperCompileManager.compileReport(getClass().getResourceAsStream("/reports/yourReport.jrxml"));
See you!
Old topic, but could be useful.
I thing where is no src folder inside your jar.
InputStream jasper2 = getClass().getResourceAsStream("/ie/test/OMACYTDReportFinalpg2.jasper");
Where is more advanced way:
Put your jasper reports, images and other resources into jar.
Put YourClass inside jar file and load resources using class.getResourceAsStream() and you need to add loader extention before load resource
(JasperReport) JRLoader.loadObject("stream or path");
// DefaultJasperReportsContext user ExtensionsEnvironment
ExtensionsEnvironment.setThreadExtensionsRegistry(LoaderExtention.INSTANCE);
The following example of loading resources
public class LoaderService
implements RepositoryService
{
public static final RepositoryService INSTANCE = new LoaderService();
#Override
public void setContext(RepositoryContext repositoryContext)
{
}
#Override
public void revertContext()
{
}
#Override
public InputStream getInputStream(String file)
{
LOGGER.fine(String.format("getInputStream('%s')", file));
return <YourClass>.class.getResourceAsStream(file);
}
#Override
public Resource getResource(String file)
{
LOGGER.fine(String.format("getResource('%s') not implemented", file));
return null;
}
#Override
public <K extends Resource> K getResource(String file, Class<K> cls)
{
LOGGER.fine(String.format("getResource('%s', %s)", file, cls != null? cls.getName(): null));
try
{
if (cls == ReportResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
JasperReport report = (JasperReport) JRLoader.loadObject(resource);
if (report != null)
{
ReportResource res = new ReportResource();
res.setName(file);
res.setReport(report);
return (K) res;
}
}
}
else if (cls == InputStreamResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
InputStreamResource res = new InputStreamResource();
res.setInputStream(resource);
return (K) res;
}
}
}
catch (JRException e)
{
}
return null;
}
#Override
public void saveResource(String string, Resource resource)
{
// TODO Implement this method
}
}
public class LoaderExtention
implements ExtensionsRegistry
{
public static final LoaderExtention INSTANCE = new LoaderExtention();
#Override
public <T extends Object> List<T> getExtensions(Class<T> cls)
{
ExtensionsRegistry system = ExtensionsEnvironment.getSystemExtensionsRegistry();
List<T> services = null;
if (system != null)
services = system.getExtensions(cls);
if (cls == RepositoryService.class)
{
List<T> servicesAll = new ArrayList<T>();
if (services != null)
servicesAll.addAll(services);
servicesAll.add((T) LoaderService.INSTANCE); // Try to use system resource loaders then my
services = servicesAll;
}
LOGGER.fine(String.format("getExtensions(%s) = %s", cls.getName(), services));
return services;
}
}
I use JasperReport 5.5
Have fun.
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");

How to fix FileNotFoundException

This is my source cord to print my invoice page. My report is in Java package. I kept it inside a folder called "report".
try {
String date1 = new SimpleDateFormat("yyyy-MM-dd").format(isdate.getDate());
String time1 = istime.getValue().toString().split(" ")[3];
date1 = date1 + " " + time1;
String date2 = new SimpleDateFormat("yyyy-MM-dd").format(redate.getDate());
String time2 = retime.getValue().toString().split(" ")[3];
date2 = date2 + " " + time2;
JRTableModelDataSource dataSource = new JRTableModelDataSource(jTable1.getModel());
String reportsource = " D:/Catering/report/report1.jrxml";
Map<String, Object> params = new HashMap<String, Object>();
params.put("inid", txtInvoiceID.getText());
params.put("cuname", txtCuName.getText());
params.put("cuadd", txtCuid.getText());
params.put("cutp", txtTPNo.getText());
params.put("isdate", date1);
params.put("redate", date2);
params.put("advance", txtAdvance.getText());
params.put("due", txtDue.getText());
params.put("total", txtGtotal.getText());
JasperReport jasperReport = JasperCompileManager.compileReport(reportsource);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
JasperViewer.viewReport(jasperPrint, true);
JOptionPane.showMessageDialog(null, "Done");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "jasper error"+e);
}
It would be better make the report an embedded resource, but where possible you should not rely on absolute paths, as these may change between installs...
Try changing
String reportsource = " D:/Catering/report/report1.jrxml";
^---- Did you notice the white space here?
To
String reportsource = "report/report1.jrxml";
It is, also, generally better to pre-compile the report so you don't need to do it at run time...
You could write a simple program that compiled it for you using something like...
String templateFile = "report/report1.jrxml"
String compiledReport = "report/report1.jasper"
JasperCompileManager.compileReportToFile(templateFile, compiledReport);
The method takes two Strings, basically one is the jrxml file and other is the expected jasper file.
You could use JasperReports' Ant task and make apart of your build process.
Or you could use iReports...
Once compiled, you can simply load the jasper file at run time...
String compiledReport = "report/report1.jasper";
JasperReport report = (JasperReport)JRLoader.loadObjectFromFile(compiledReport );
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
Updated with Quick Compile example
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
public class QuickCompile {
public static void main(String[] args) {
try {
String template = "...";
String compiled = "...";
JasperCompileManager.compileReportToFile(template, compiled);
// Just as a test...
JasperReport jr = (JasperReport) JRLoader.loadObjectFromFile(compiled);
} catch (JRException exp) {
exp.printStackTrace();
}
}
}

How to specify the subdataset query when executing report from a Java application

I have a main report with a main query and a Table (with subdataset) inside of it, which has its own Query.
I know how to specify the Query for the main report, but I don't know how the to specify Query for the subdatset in my Java code of creation reports.
Can anyone help, please ?
My code:
public static java.sql.Connection cx = Connexion.SetConOn();
public static void Create report(String Query, String model, String title, String art) {
try {
JRDesignQuery jrd = new JRDesignQuery();
JasperDesign design = JRXmlLoader.load(model);
jrd.setText(Query);
design.setQuery(jrd);
Map map = new HashMap();
JasperReport etat = JasperCompileManager.compileReport(design);
JasperPrint print = JasperFillManager.fillReport(etat, map, cx);
File f = new File("C:\\" + fdg);
f.mkdir();
JasperExportManager.exportReportToPdfFile(print, f.getPath() + "\\" + title + ".pdf");
JasperViewer jv = new JasperViewer(print, false, Locale.FRENCH);
try {
java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read(jv.getClass().getResource("/cycloplan/Images/Burn-icon1.png"));
javax.swing.ImageIcon myImg = new javax.swing.ImageIcon(bi);
jv.setIconImage(myImg.getImage());
} catch (java.io.IOException ex) {
ex.printStackTrace();
}
jv.setTitle(title);
jv.setAlwaysOnTop(true);
jv.setVisible(true);
} catch (JRException ex) {
ex.printStackTrace();
}
}
The JasperDesign class has a few different ways to access subdatasets; take a look at the javadoc [link]. I think the following code should work to set the subdataset query, where subQueryString is the query you want to use and datasetName is the name given to the subdataset element in the JRXML.
JRDesignQuery subQuery = new JRDesignQuery();
subQuery.setText(subQueryString);
Map<String, JRDataset> datasetMap = design.getDatasetMap();
JRDesignDataset subDataset = (JRDesignDataset) datasetMap.get(datasetName);
subDataset.setQuery(subQuery);
(* I haven't actually tested this code. YMMV)

Running OpenOffice Macro from Java API

I'm trying to write a Java program that will run an OpenOffice Macro. I'm getting this error:
java.lang.RuntimeException:
com.sun.star.script.provider.ScriptFrameworkErrorException: Incorrect
format for Script URI: vnd.sun.star.script:Name of macro
I believe it has something to do with the way that I'm calling the macro (String cmd)
I've searched high and low but can't seem to find any information on this. There are a few posts on the OO forums but none of them seemed to help. Here is some of the code:
public static void main(String[] args) throws BootstrapException {
if(args.length == 0)
{
System.out.println("Must enter a filename");
System.exit(1);
}
try
{
String param = args[0];
//String cmd = "Standard.Conversion.ConvertHTMLToWord?langauge=Basic&location=application";
String cmd = "Name.Of.Macro?langauge=Basic&location=Document";
System.out.println("Running macro on " + param);
Macro macObj = new Macro();
macObj.executeMacro(cmd, new Object[]{param}]);
System.out.println("Completed");
}
catch(Exception e)
{
System.out.println(e.toString());
//e.printStackTrace();
}
Macro Class:
class Macro {
private static final String ooExecPath = "C:/Program Files/OpenOffice.org 3/program";
public Object executeMacro(String strMacroName, Object[] aParams) throws BootstrapException
{
try
{
com.sun.star.uno.XComponentContext xContext;
System.out.println("Connecting to OpenOffice");
xContext = BootstrapSocketConnector.bootstrap(ooExecPath);
System.out.println("Connected to a running instance of OpenOffice");
System.out.println("Trying to execute macro...");
com.sun.star.text.XTextDocument mxDoc = openWriter(xContext);
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, mxDoc);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
return xScript.invoke(aParams, aOutParamIndex, aOutParam);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static com.sun.star.text.XTextDocument openWriter(com.sun.star.uno.XComponentContext xContext)
{
com.sun.star.frame.XComponentLoader xCLoader;
com.sun.star.text.XTextDocument xDoc = null;
com.sun.star.lang.XComponent xComp = null;
try {
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF =
xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
xCLoader = (com.sun.star.frame.XComponentLoader)
UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
com.sun.star.beans.PropertyValue [] szEmptyArgs =
new com.sun.star.beans.PropertyValue [0];
/*
ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
PropertyValue p = new PropertyValue();
p.Name = "Hidden";
p.Value = new Boolean(true);
props.add(p);
PropertyValue[] properties = new PropertyValue[props.size()];
props.toArray(properties);
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, properties);
*/
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = (com.sun.star.text.XTextDocument)
UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
xComp);
} catch(Exception e){
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xDoc;
}
}
I suppose your problem is in the "Name.Of.Macro": it must be: Library.Module.NameOfMacro.
"langauge=Basic" of course sets the language name, and "location=application" means the macro library should be searched in the opened document, and not in global OO libraries.
As far as parameters are involved, I use:
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+macroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
Object[] aParams = new String[2];
aParams[0] = myFirstParameterName;
aParams[1] = mySecondParameterName;
#SuppressWarnings("unused")
Object result = xScript.invoke(aParams, aOutParamIndex, aOutParam);
System.out.println("xScript invoke macro " + macroName);
Hope it can be useful, after such long time... :-(
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
What is xComponent in the above code?
Compare: ?langauge=Basic&location=Document"
to: ?language=Basic&location=Document"
wring is: "langauge" :D, swap "au" to "ua". :)

Categories