Generate BIRT PDFs from a Netbeans application - java

I have created a report with the Eclipse BIRT plugin for Eclipse and want to create a PDF from a console application (I use Netbeans to create this)
I have looked around the documentation but I can't really get anything to work. How can I call BIRT to generate the PDF from the .rptdesign?

I got most of this code from the eclipse site but I can't seem to find it now. I commented out my implementation specific code below but the rest should be usable/editable for you. All of the imports came in the normal birt runtime. The printReport method below generates a PDF from a report url:
import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.Iterator;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IParameterDefnBase;
import org.eclipse.birt.report.engine.api.IParameterGroupDefn;
import org.eclipse.birt.report.engine.api.IParameterSelectionChoice;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IScalarParameterDefn;
import org.eclipse.birt.report.engine.api.PDFRenderOption;
public class BirtEngine {
IReportEngine engine = null;
EngineConfig config = null;
public BirtEngine()
{
try {
config = new EngineConfig( );
config.setBIRTHome("C:\\birtruntime\\ReportEngine");
Platform.startup( config );
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
engine = factory.createReportEngine( config );
}catch(Exception e){
e.printStackTrace();
}
}
public void openReport(String report)
{
try {
IReportRunnable design = null;
design = engine.openReportDesign(report);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void renderReport(String report)
{
try {
IReportRunnable design = null;
design = engine.openReportDesign(report);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
HTMLRenderOption options = new HTMLRenderOption();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
options.setOutputStream(bos);
options.setOutputFormat("html");
options.setEmbeddable(true);
task.setRenderOption(options);
task.run();
task.close();
//TreeBirtFrameView.jEditorPane1.setContentType("text/html");
//TreeBirtFrameView.jEditorPane1.setText(bos.toString());
}catch(Exception ex){
ex.printStackTrace();
}
}
public void printReport(String report)
{
try {
IReportRunnable design = null;
design = engine.openReportDesign(report);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
PDFRenderOption options = new PDFRenderOption();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
options.setOutputStream(bos);
options.setOutputFormat("pdf");
task.setRenderOption(options);
task.run();
task.close();
//Runtime.getRuntime().exec("\\\\myServer\\pgms$\\Adobe\\Reader 9.0\\Reader\\acrord32.exe report.pdf");
}catch(Exception ex){
ex.printStackTrace();
}
}
public void stopPlatform()
{
engine.destroy();
Platform.shutdown();
}
}

Related

Box Java sdk - The API returned an error code 404 - Not Found

I need to create a utility, which downloads the files from the box folder. But I am unable to get it working though:
package com.box.sdk.example;
import com.box.sdk.BoxConfig;
import com.box.sdk.BoxDeveloperEditionAPIConnection;
import com.box.sdk.BoxFile;
import com.box.sdk.BoxFolder;
import com.box.sdk.BoxItem;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PlayGround {
public static void main(String[] args) {
Path configPath = Paths.get("config.json");
Path currentDir = Paths.get("").toAbsolutePath();
try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) {
BoxConfig boxConfig = BoxConfig.readFrom(reader);
BoxDeveloperEditionAPIConnection client = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig);
String folderId = "125601757844";
BoxFolder folder = new BoxFolder(client, folderId);
String folderName = folder.getInfo().getName();
Path localFolderPath = currentDir.resolve(Paths.get(folderName));
if (!Files.exists(localFolderPath)) {
localFolderPath = Files.createDirectory(localFolderPath);
} else {
localFolderPath = resetLocalFolder(localFolderPath);
}
for (BoxItem.Info itemInfo : folder) {
if (itemInfo instanceof BoxFile.Info) {
BoxFile.Info fileInfo = (BoxFile.Info) itemInfo;
BoxFile file = new BoxFile(client, fileInfo.getID());
String localFilePath = localFolderPath.resolve(Paths.get(fileInfo.getName())).toAbsolutePath()
.toString();
FileOutputStream stream = new FileOutputStream(localFilePath);
file.download(stream);
stream.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static Path resetLocalFolder(Path localFolderPath) throws IOException {
Files.list(localFolderPath).forEach(file -> {
System.out.println(file.getFileName());
try {
Files.delete(file.toAbsolutePath());
} catch (IOException e) {
}
});
Files.delete(localFolderPath);
localFolderPath = Files.createDirectory(localFolderPath);
return localFolderPath;
}
}
When I run this code, I get the following exception:
Exception in thread "main" com.box.sdk.BoxAPIResponseException: The API returned an error code [404 | lsgp4zgkfg6qipxg.0d094ed7daa5f78921603840e0fa470e1] not_found - Not Found
at com.box.sdk.BoxAPIResponse.<init>(BoxAPIResponse.java:92)
at com.box.sdk.BoxJSONResponse.<init>(BoxJSONResponse.java:32)
at com.box.sdk.BoxAPIRequest.trySend(BoxAPIRequest.java:680)
at com.box.sdk.BoxAPIRequest.send(BoxAPIRequest.java:382)
at com.box.sdk.BoxAPIRequest.send(BoxAPIRequest.java:349)
at com.box.sdk.BoxFolder.getInfo(BoxFolder.java:289)
at com.box.sdk.example.PlayGround.main(PlayGround.java:26)
Note: I am able to run the above code, by using developer token, which lasts for 1 hour, but I can't build my production application on such volatile code.
BoxAPIConnection client = new BoxAPIConnection("3i8b5sPnxUotd5etDuUkzGjXXzBphty9");

Tess4j jar file issue

import java.awt.image.RenderedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.Tesseract;
public class Tess4JSample {
public static void main(String[] args) throws Exception{
URL imageURL = new URL("http://s4.postimg.org/e75hcme9p/IMG_20130507_190237.jpg");
RenderedImage img = ImageIO.read(imageURL);
File outputfile = new File("saved.png");
ImageIO.write(img, "png", outputfile);
try {
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
String result = instance.doOCR(outputfile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
for this program I have put the jar files tess4j-1.5.0 and jai_imageio-1.1. But still it shows error
The import net.sourceforge cannot be resolved
Can anyone tell me what is the necessary action needs to be taken care for error resolution? I taken this program from stack overflow itself. Thanks! in advance.

Couldn't append the text onto a Google Drive File

I am trying to append text to a text file on the Google Drive. But when I write, it whole file is overwritten. Why can't I just add the text in the end of the file?
DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, id);
file.open(mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
msg.Log("ContentsOpenedCallBack");
if (!driveContentsResult.getStatus().isSuccess()) {
Log.i("Tag", "On Connected Error");
return;
}
final DriveContents driveContents = driveContentsResult.getDriveContents();
try {
msg.Log("onWrite");
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
writer.append(et.getText().toString());
writer.close();
driveContents.commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Finally I've found the answer to append the text on the drive document.
DriveContents contents = driveContentsResult.getDriveContents();
try {
String input = et.getText().toString();
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("\n"+input);
writer.close();
driveContentsResult.getDriveContents().commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
SO
The reason is that commit's default resolution strategy is to overwrite existing files. Check the API docs and see if there is a way to append changes.
For anyone facing this problem in 2017 :
Google has some methods to append data Here's a link!
Though copying the method from google didn't worked entirely for me , so here is the class which would append data : ( Please note this is a modified version of this code link )
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.DriveIdResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
/**
* An activity to illustrate how to edit contents of a Drive file.
*/
public class EditContentsActivity extends BaseDemoActivity {
private static final String TAG = "EditContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveId driveId = result.getDriveId();
DriveFile file = driveId.asDriveFile();
new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
}
};
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
System.out.println("0"+sp.getString("drive_id","1"));
DriveContentsResult driveContentsResult=file.open(getGoogleApiClient(), DriveFile.MODE_READ_WRITE, null).await();
System.out.println("1");
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
try {
System.out.println("2");
ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
System.out.println("3");
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
writer.close();
System.out.println("4");
driveContents.commit(getGoogleApiClient(), null).await();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
};
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
Existing_File_id is the resource id. Here is one link if you need resource id a link

ArrayList to XML

I am trying to take the contents of an ArrayList and put them into an XML file. Does anyone have a quick,clean and easy solution to this rather that having to use streams and handle exceptions?
For more information, Here is the code I have currently I am getting problem with it, one of which its not creating the file.
package ie.wit.io;
import ie.wit.abs.Device;
import ie.wit.abs.Device;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class FileHandler
{
private FileOutputStream outByteStream;
private ObjectOutputStream OOStream;
private FileInputStream inByteStream;
private ObjectInputStream OIStream;
private File aFile;
public void setUpFile()
{
aFile = new File("data.xml");
}
public boolean isFileEmpty()
{
return (aFile.length() <= 0);
}
public void writeToFile(ArrayList<Device> team)
{
try
{
outByteStream = new FileOutputStream(aFile);
OOStream = new ObjectOutputStream(outByteStream);
OOStream.writeObject(team);
outByteStream.close();
OOStream.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"I/O Error" + e + "\nPlease Contact your Administrator :-)");
}
}
currentClass)
public ArrayList<Device> readFromFile()
{
ArrayList<Device> temp = null;
try
{
inByteStream = new FileInputStream(aFile);
OIStream = new ObjectInputStream(inByteStream);
if(!this.isFileEmpty())
temp = (ArrayList<Device>)OIStream.readObject();
inByteStream.close();
OIStream.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"I/O Error" + e + "\nPlease Contact your Administrator :-)");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"General Error" + e + "\nPlease Contact your Administrator :-)");
}
return temp;
}
}
There are many libraries to do that task.
Here is what I'm doing so far. Edit as per your requirement.
protected String getDocmentsAsString(List<News> documentsListByIndex) {
if(documentsListByIndex.size()>0){
try {
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("news", News.class);
return xstream.toXML(documentsListByIndex);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
Im using http://x-stream.github.io/json-tutorial.html
You can use a StringBuilder and generate the XML yourself.. It depends on how many items you want to convert. The fastest way is just pushing out the XML data using a StringBuilder.
I recommend to:
create a XSD
generate JAXB Java classes (e.g. using a Maven Plugin)
create instances of the JAXB Java classes and fill up the data
marshal the JAXB Java classes to XML

How to add attachment to CouchDB using Couchdb4j library

How can I use Java application to add system files as an attachment to Couchdb database using Couchdb4J library?
I tried modifying the sample code below but there's an unresolved error. Does anybody know where's my mistake and how to fix it? Thanks in advance.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import com.fourspaces.couchdb.CouchResponse;
import com.fourspaces.couchdb.Database;
import com.fourspaces.couchdb.Document;
import com.fourspaces.couchdb.Session;
public class FileScanner {
Session priceListDocsSession = new Session("localhost",5984);
Database db = priceListDocsSession.getDatabase("filesdb");
public static void main(String[] args) {
FileScanner fs = new FileScanner();
fs.processDir(new File("C:\\CouchDB"));
}
void processDir(File f) {
if (f.isFile()) {
Map<String, Object> doc = new HashMap<String, Object>();
doc.put("name", f.getName());
doc.put("path", f.getAbsolutePath());
doc.put("size", f.length());
db.saveDocument(doc);
InputStream is = new FileInputStream(f);
String att=db.putAttachment(doc.getId(),doc.getRev(),f,is);
}
else {
File[] fileList = f.listFiles();
if (fileList == null) return;
for (int i = 0; i < fileList.length; i++) {
try {
processDir(fileList[i]);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
}
The errors appears on the db.saveDocument(doc);
and
String att=db.putAttachment(doc.getId(),doc.getRev(),f,is); saying that .getId() and getRev() is undefined for the type Map
I managed to fixed the problem by adding some of the jcouchdb dependencies on the classpath.

Categories

Resources