Apache POI Excelsheet to pdf file - apache-poi

How can I save a defined excel spreedsheet (e.g. Tabelle1) with printlayout on one page (.setFitToPage) as pdf-file
HSSFWorkbook workBook = null;
try {
workBook = new HSSFWorkbook(new FileInputStream("/total-ae-chem.xls"));
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HSSFSheet spreadsheet = workBook.getSheet("Tabelle1");

Related

Nifi:transfer relationship not specified

I want to update xml data and write it in flowfile1 but for some reason my ExecuteScript processor can't specify transfer relationship here is my code, what should i change to make this task?:
Is it possbile that my code inside session.write can't cast xml data to ByteArray and can't write this in flowfile content? ( but it doesn't throw exception)
flowFile1 = session.putAttribute(flowFile1, "filename", "conf.xml");
session.write(flowFile1, new StreamCallback() {
#Override
public void process(InputStream inputStream1, OutputStream outputStream) throws IOException {
TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
Transformer transformer1 = null;
try {
transformer1= transformerFactory1.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source1 = new DOMSource(doc);
ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos1);
try {
transformer1.transform(source1, result);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array1 = bos1.toByteArray();
outputStream.write(array1);
}
});
if(flowFile1!=null){
session.transfer(flowFile1, REL_SUCCESS);
}
else{
session.transfer(flowFile1, REL_FAILURE);
}
}catch (OverlappingFileLockException e) {
lock.release();
}
catch (FileNotFoundException e) {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.release();
ini.close();
}
session.write() returns a reference to a newer version of the flow file, but you are not storing it or transferring it. Later on, you end up trying to transfer a version that is not the latest. Try adding "flowFile1 = " to the beginning of your session.write() statement.

send a JSON request with JSONObject as parameter?

I want to make an android-json request to a webservice with httpClient.
The method which i try to call is "authenticate"
The request should have the following structure:
{"id":"ID","method":"authenticate","params":{"user":"ANDROID",
"password":"PASSWORD", "client":"CLIENT"},"jsonrpc":"2.0"}
mandatory parameter: ?school=SCHOOLNAME
This is what i have tried:
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do";
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("?school","litec");
params1.put("user", "40146720133271");
params1.put("password", "1234567");
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}
}
After executing this, i get the request:
{"jsonrpc":"2.0","id":"error","error":{"message":"invalid schoolname","code":-8500}}
So its telling me that our schoolname is false.
So what can i do, is my way to pass parameters wrong ?
I saw your question some time ago, but I was not able to answer. I'm working with the WebUntis API as well, and I dont know if you solved the error, but it is a simple error in the url. As mentionend in the API, the mandatory paramter for the method 'authenthicate' is ?school=SCHULNAME. Your Url in the code is 'https://arche.webuntis.com/WebUntis/jsonrpc.do', but the mandatory parameter SCHULNAME is not given. Your Url should look like this: https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME. Maybe you have to add the length of your request. E.g. if you use the method authenthicate: {"id":"ID","method":"authenticate","params":{"user":"USR", "password":"PW", "client":"MyApp"},"jsonrpc":"2.0"}
In this case length would be 109. I hope this helped, even if the question is over a month old. For other Googlers: If you are not using an AsyncTask, you have to return true, not ok.
EDIT:
The code looks like this (I haven't tested this yet, I hope it works):
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME"; //Changes here
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("user", "40146720133271");
params1.put("password", "1234567");
params1.put("client", "seriouslysAndroidApp"); //You can change the name
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setHeader("Content-length",""+se.getContentLength()); //header has to be set after jsonparams are complete
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}

Liferay Document Management System Workflow

I am creating a DMS in Liferay. So far I could upload documents in Liferay in document library. And also I can see documents in document and media portlet. The problem is though status for the document is in pending state, the workflow is not started. Below is my code.
Folder folder = null;
// getting folder
try {
folder = DLAppLocalServiceUtil.getFolder(10181, 0, folderName);
System.out.println("getting folder");
} catch(NoSuchFolderException e)
{
// creating folder
System.out.println("creating folder");
try {
folder = DLAppLocalServiceUtil.addFolder(userId, 10181, 0, folderName, description, serviceContext);
} catch (PortalException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} catch (SystemException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
}
catch (PortalException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
} catch (SystemException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
// adding file
try {
System.out.println("New File");
fileEntry = DLAppLocalServiceUtil.addFileEntry(userId,
10181, folder.getFolderId(), sourceFileName,
mimeType, title, "testing description",
"changeLog", sampleChapter, serviceContext);
Map<String, Serializable> workflowContext = new HashMap<String, Serializable>();
workflowContext.put("event",DLSyncConstants.EVENT_CHECK_IN);
DLFileEntryLocalServiceUtil.updateStatus(userId, fileEntry.getFileVersion().getFileVersionId(), WorkflowConstants.ACTION_PUBLISH, workflowContext, serviceContext);
System.out.println("after entry"+ fileEntry.getFileEntryId());
} catch (DuplicateFileException e) {
} catch (PortalException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SystemException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return fileEntry.getFileEntryId();
}
I have even used WorkflowHandlerRegistryUtil.startWorkflowInstance(companyId, userId, fileEntry.getClass().getName(), fileEntry.getClassPK, fileEntry, serviceContext);
But still i have the same problem
If you are working on DMS service for upload document and media in Liferay Dxp.
By default status of the document will be draft.You can use below code,
DLFileEntry dlFileEntry = null;
String fileName = null;
long PARENT_FOLDER_ID = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
DLFolder folder = DLFolderLocalServiceUtil.getFolder(group.getGroupId(), PARENT_FOLDER_ID,
"SirswaPartnerDocuments");
long groupId = folder.getGroupId();
long repositoryId = folder.getRepositoryId();
long folderId = folder.getFolderId();
String sourceFileName = "dummy";
String mimeType = MimeTypesUtil.getContentType(file);
String title = file.getName();
String extension = "Caption";
fileName = file.getName();
String uniqueTitle = DLFileEntryLocalServiceUtil.getUniqueTitle(groupId, folderId,
folder.getDefaultFileEntryTypeId(), title, extension);
String changeLog = "SirswaChangeLog";
String description = folder.getDescription();
long defaultFileEntryTypeId = folder.getDefaultFileEntryTypeId();
try
{
dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(folder.getUserId(), groupId,
repositoryId, folder.getFolderId(), sourceFileName, MimeTypesUtil.getContentType(file),
uniqueTitle, description, changeLog, folder.getDefaultFileEntryTypeId(),
ddmFormValuesMap, file, is, size, serviceContext);
}
catch (Exception e)
{
e.printStackTrace();
}
Now if you want to change the status of document and media draft to Approved programmatically.
Use below code It will work as expected
int workFlowStatus = WorkflowConstants.STATUS_APPROVED;
dlFileEntry = DLFileEntryLocalServiceUtil.updateStatus(folder.getUserId(),dlFileEntry.getFileVersion().getFileVersionId(),workFlowStatus, serviceContext,new HashMap<String, Serializable>());
This is a piece of code that insert correctly fileentry into document library. Take care the serviceContext settings.
ServiceContext serviceContext = new ServiceContext();
serviceContext.setAddGroupPermissions(true);
serviceContext.setUserId(userDest.getUserId());
serviceContext.setScopeGroupId(userDest.getGroupId());
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);
FileEntry newfile =
DLAppLocalServiceUtil.addFileEntry(
userDest.getUserId(),
userDest.getGroupId(),
folder.getFolderId(),
item.getFileName(),
MimeTypesUtil.getContentType(item.getFileName()),
item.getFileName(), null, null, bytes,
serviceContext);

How to create a excel spread sheet on client side

I am creating a web app where I want to show a excel icon in my results. When user clicks on icon, it should open up a spread sheet on clients machine with some data sent by server (clients will have excel installed).
I wrote some code to create excel on my local machine from the webservice.
public class App
{
public static void main( String[] args )
{
try {
URL oracle = new URL("http://someService.com");
URLConnection yc =null;
yc = oracle.openConnection();
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
int rowNum =0;
while ((inputLine = in.readLine()) != null) {
Row row = sheet.createRow(rowNum++);
String[] coloumns = inputLine.split("\t");
int cellNum =0;
for(String coloumn: coloumns){
coloumn.
Cell cell = row.createCell(cellNum++);
cell.setCellValue(coloumn);
}
System.out.println(inputLine);
}
in.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\libraries\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works fine.
All it does is it reads data coming from web service and creates a spreadsheet in my machine at C:\libraries\new.xls.
Now if I am on web app I want to open a spread sheet on clients machine. I don't have to save the sheet. Just open with the data.
How can I open spread sheet on client machine with this data from web service?
EDIT
Here is my new server code:
#RequestMapping(value = "/Excel")
public void getFile(HttpServletResponse response){
OutputStream out =null;
try {
out = response.getOutputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response.setContentType("application/x-ms-excel");
try {
URL oracle = new URL("http://someService.com");
URLConnection yc =null;
yc = oracle.openConnection();
//Get the workbook instance for XLS file
IOUtils.copy(yc.getInputStream(),out);
out.flush();
System.out.println("Excel written successfully..");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So now i ran the web app and nothing happened? Should i do something on front end to invoke this stream.
You can do something like this inside a Spring MVC controller to send the file to the client's computer:
#RequestMapping(value = "/myexcelreport")
public void getFile(
HttpServletResponse response) {
OutputStream out=response.getOutputStream();
response.setContentType("application/x-ms-excel");
... Same code a before, just use out instead of a FileOutputStream , and don't close out.
out.flush();
}

how to read a text file stored in mobile using j2me midp2.0?

HI ALL,
I am working in j2me midp2.0 environment.My application wants to read a text file which is stored in mobile device.How to read the text file programatically using j2me.Please give me idea to get this.What is the root folder in mobile to place the text file for accessible from j2me Application environment.
Saravanan.P
You need javax.microedition.io.file.FileConnection
Get root folder:
try {
Enumeration roots = FileSystemRegistry.listRoots();
while(roots.hasMoreElements()) {
System.out.println("Root: file:///"+(String)roots.nextElement());
}
} catch(Exception e) {
}
write to file
public void write(String root) {
FileConnection fc = null;
String fName = "test.txt";
try {
fc = (FileConnection) Connector.open(root + fName, Connector.READ_WRITE);
if(!fc.exists()) {
fc.create();
}
DataOutputStream dos = fc.openDataOutputStream();
dos.writeUTF("test-test");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fc.close();
} catch (IOException e) { }
}
}
read from file
public void read(String root) {
FileConnection fc = null;
try {
fc= (FileConnection) Connector.open(root + "test.txt", Connector.READ);
DataInputStream dis = fc.openDataInputStream();
String data = dis.readUTF();
System.out.println(data);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fc.close();
} catch (IOException e) { }
}
}
Better u use FileConnection.
FileConnection fc=(FileConnection)Connector.ope(url);

Resources