how to upload a file - upload

i try to upload a file from client to server
on the client side, i have a file input
on server side i have
private void uploadFile(final FileTransfer fileTransfer) {
String destinationFile = "/home/nat/test.xls";
InputStream fis = null;
FileOutputStream out = null;
byte buf[] = new byte[1024];
int len;
try {
fis = fileTransfer.getInputStream();
out = new FileOutputStream(new File(destinationFile));
while ((len = fis.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
a file is created on the server, but it's empty
when i debug, i can see then fis is not null
any idea?

Here is a code extract of mine:
try {
File fileData = new File(fileTransfer.getFilename());
// Write the content (data) in the file
// Apache Commons IO: (FileUtils)
FileOutputStream fos = FileUtils.openOutputStream(fileData);
// Spring Utils: FileCopyUtils
FileCopyUtils.copy(fileTransfer.getInputStream(), fos);
// Alternative with Apache Commons IO
// FileUtils.copyInputStreamToFile(fileTransfer.getInputStream(), fileData);
// Send the file to a back-end service
myService.persistFile( fileData );
} catch (IOException ioex) {
log.error("Error with io")
}
return fileTransfer.getFilename(); // this is for my javascript callback fn
Apache Commons IO is a good library to use for such manipulations (I use Spring Utils as well). If you do not have a Spring context, use the commented alternative with Apache (check the syntax, it is not verified).

Related

How to extract content from. Pst file using apache tika?

How to parse.Pst file using apache tika
1.2?
How can I get entire body, attachment, and all Metadata of email while searching with ljcene?
for (File file : docs.listFiles()) {
Metadata metadata = new Metadata();
ContentHandler handler = new BodyContentHandler();
ParseContext context = new ParseContext();
Parser parser = new AutoDetectParser();
InputStream stream = new FileInputStream(file);
try {
parser.parse(stream, handler, metadata, context);
}
catch (TikaException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
If you're stuck with 1.2, you might try the recommendation here
If you're able to upgrade, we added that as the RecursiveParserWrapper in 1.7 ...just upgrade to 1.12 if you can, or wait a week or two and 1.13 should be out.
Via commandline:
java -jar tika-app.jar -J -t -i input_directory -o output_directory
Or in code:
Parser p = new AutoDetectParser();
RecursiveParserWrapper wrapper = new RecursiveParserWrapper(p,
new BasicContentHandlerFactory(
BasicContentHandlerFactory.HANDLER_TYPE.XML, -1));
try (InputStream is = Files.newInputStream(file)) {
wrapper.parse(is, new DefaultHandler(), new Metadata(), context);
}
int i = 0;
for (Metadata metadata : wrapper.getMetadata()) {
for (String name : metadata.names()) {
for (String value : metadata.getValues(name)) {
System.out.println(i + " " + name +": " + value);
}
}
i++;
}

Downloading Docusign PDF in Grails, file corrupted

Using Groovy 1.8.6 and Grails 2.1.0
Using embedded API, after user signs document, browser is redirected back to my app. Using "Get Envelope Documents and Certificate" API to download document to server. URL format:
"${baseUrl}/envelopes/${envelopeId}/documents/combined"
Code snippet (with minor details removed):
private void getDocument(requestUrl) {
def connection = urlConnect(requestUrl, null, "GET")
if (connection.responseCode == 200) {
savePDF(envelopeId, connection.inputStream)
}
}
private void savePDF(envelopeId, inputStream) {
String filePath = getSavedPDFPath(envelopeId)
def pdfWriter = new File(filePath).newWriter()
pdfWriter << inputStream
pdfWriter.close()
}
What happens is that the resulting file is not 100% correct, Adobe Reader complains that "at least one signature is invalid". Reader at least knows that the file was signed by DocuSign, Inc., and can show details about the certificate.
Per the Question's comment thread, the issue was being caused by the way the file was being saved. Using this code instead, the file saves / opens correctly:
private void savePDF(envelopeId, connection)
{
FileOutputStream fop = null;
File file;
String filePath = getSavedPDFPath(envelopeId);
try {
file = new File(filePath);
fop = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int numRead;
while((numRead = connection.getInputStream().read(buffer)) > 0)
{
fop.write(buffer, 0, numRead);
}
fop.flush();
fop.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}

sending json data to server in blackberry

In my application i have to integrate API. I am not getting code for how to check whether internet is available or not. How to send JSON Data to server. Please help me out. As in android we call API in AsyncTask class. In blackberry i did not found like this.
Suggest me some link or ideas so that i can integrate code. I am googling. But did not getting result .
What I have tried is here:
JSONObject postData = new JSONObject();
postData.put("userId", "24");
postData.put("messageTime","06:00:00");
postData.put("language", language[lang_Ocf.getSelectedIndex()]);
System.out.println("********json********"+postData);
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
conDesc = conFactory.getConnection(url+";deviceside=true");
}
catch(Exception e)
{
System.out.println(e.toString()+":"+e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if(null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection)conDesc.getConnection();
//set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length", Integer.toString(postData.length()));
connection.setRequestProperty("Content-Type","application/json");
OutputStream out = connection.openOutputStream();
out.write(postData.get);
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK){
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while((read = in.read())!= -1)
buf.append((char)read);
response = buf.toString();
}
Dialog.inform(response);
connection.close();
} catch(Exception e) {
}
}
return response;
Thanks
I solved this problem
Error:
Error: Cannot run program "jar": CreateProcess error=2, The system cannot find the file specified Packaging project HelaBibleWhereUR failed (took 10.715 seconds)
I simply put jar.exe that is under java bin folder in the jre bin folder.

How to compress the files in Blackberry?

In my application I used html template and images for browser field and saved in the sdcard . Now I want to compress that html,image files and send to the PHP server. How can I compress that files and send to server? Provide me some samples that may help lot.
i tried this way... my code is
EDIT:
private void zipthefile() {
String out_path = "file:///SDCard/" + "newtemplate.zip";
String in_path = "file:///SDCard/" + "newtemplate.html";
InputStream inputStream = null;
GZIPOutputStream os = null;
try {
FileConnection fileConnection = (FileConnection) Connector
.open(in_path);//read the file from path
if (fileConnection.exists()) {
inputStream = fileConnection.openInputStream();
}
byte[] buffer = new byte[1024];
FileConnection path = (FileConnection) Connector
.open(out_path,
Connector.READ_WRITE);//create the out put file path
if (!path.exists()) {
path.create();
}
os = new GZIPOutputStream(path.openOutputStream());// for create the gzip file
int c;
while ((c = inputStream.read()) != -1) {
os.write(c);
}
} catch (Exception e) {
Dialog.alert("" + e.toString());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
}
}
this code working fine for single file but i want to compress all the file(more the one file)in the folder .
In case you are not familiar with them, I can tell you that in Java the stream classes follow the Decorator Pattern. These are meant to be piped to other streams to perform additional tasks. For instance, a FileOutputStream allows you to write bytes to a file, if you decorate it with a BufferedOutputStream then you get also buffering (big chunks of data are stored in RAM before being finally written to disc). Or if you decorate it with a GZIPOutputStream then you get also compression.
Example:
//To read compressed file:
InputStream is = new GZIPInputStream(new FileInputStream("full_compressed_file_path_here"));
//To write to a compressed file:
OutputStream os = new GZIPOutputStream(new FileOutputStream("full_compressed_file_path_here"));
This is a good tutorial covering basic I/O . Despite being written for JavaSE, you'll find it useful since most things work the same in BlackBerry.
In the API you have these classes available:
GZIPInputStream
GZIPOutputStream
ZLibInputStream
ZLibOutputStream
If you need to convert between streams and byte array use IOUtilities class or ByteArrayOutputStream and ByteArrayInputStream.

convert the bytes in to readable string format in blackberry?

I am working on an BB app in which I need to maintain a HTTP connection and with a name of image which is stored on server to get the text written in that image document.
I am getting the response in RTF format.
When I directly hit the server on open browser Chrome, I RTF file get downloaded.
Now I needs to perform that programetically,
1) Either convert the bytes which are coming in response in a simple string format so that I can read that.
or
2) Download the file as its happening on the browser manually so that by reading that file I read the information written in the document.
please suggest me how can I read the data from server by hitting any URL?
Currently I am working with this code:
try {
byte []b = send("new_image.JPG");
String s = new String(b, "UTF-8");
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
public byte[] send(String Imagename) throws Exception
{
HttpConnection hc = null;
String imageName = "BasicExp_1345619462234.jpg";
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open("http://webservice.tvdevphp.com/basisexpdemo/webservices/ocr.php?imgname="+imageName);
hc.setRequestProperty("Content-Type", "multipart/form-data;");
hc.setRequestMethod(HttpConnection.GET);
int ch;
StringBuffer sb= new StringBuffer();
is = hc.openInputStream();
while ((ch = is.read()) != -1)
{
bos.write(ch);
sb.append(ch);
}
System.out.println(sb.toString());
res = bos.toByteArray();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
return res;
}
The response is like:
{\rtf1\ansi\ansicpg1252\uc1\deflang1033\adeflang1033...................
I can read the data but its not formatted, so that i can read that programetically too.
I have done with this task....
Actually the mistake was on server side.
When they were performing OCR, the format parameter was not corrected that was reason.

Resources