I am writing in java, but want to create a dynamic HTML-page for the users. I am using Lowagie to create the document with HTML. I do manage to present the html, but my picture is empty. It just contain the picture-border.
Can anyone help me with this? Or tell me another way of creating HTML-pages (preferable by using ByteArrauOutputstream or other outpustreams to display the content).
The code is as follows:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String orderId = request.getParameter("id1");
String telephone = request.getParameter("id2");
response.setHeader("Expires", EXPIRES);
response.setContentType(CONTENT_TYPE);
ServletOutputStream out = null;
ByteArrayOutputStream baos = null;
try {
baos = getHtmlTicket(orderId, telephone);
response.setContentLength(baos.size());
out = response.getOutputStream();
baos.writeTo(out);
}
catch (Exception e) {
log.error(e.getMessage(), e);
}
finally {
if (out != null) {
try {
out.flush();
}
catch (Exception e) {
log.debug(e.getMessage(), e);
}
}
if (baos != null) {
try {
baos.flush();
}
catch (Exception e) {
log.debug(e.getMessage(), e);
}
}
if (out != null) {
try {
out.close();
}
catch (Exception e) {
log.warn(e.getMessage(), e);
}
}
if (baos != null) {
try {
baos.close();
}
catch (Exception e) {
log.warn(e.getMessage(), e);
}
}
}
public ByteArrayOutputStream getHtmlTicket(String orderId, String telephoneTest) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
Order order = orderService.getOrder(Integer.parseInt(orderId));
String fileType = "png";
String filePath = "html/picture.png";
File myFile = new File(filePath);
try {
HtmlWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("Hello World"));
Image fileImage = Image.getInstance(filePath);
document.add(fileImage);
document.add(new Paragraph("osv"));
}
catch (DocumentException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
document.close();
return baos;
}
Related
This code is used to copy an instance through java serialization. It uses the traditional try-catch-finally writing method. Can it be changed to try-with-resources form?(The DeepConcretePrototype in the code is an ordinary java object)
/**
* Clone an instance through java serialization
* #return
*/
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
//Output an instance to memory
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.flush();
//Read instance from memory
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(byteArrayInputStream);
clone = (DeepConcretePrototype)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return clone;
}
Yes you can use try-with-resources, but it's a little tricky because the success of read depends on the success of write. One way you can write it is with a nested try:
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
//Output an instance to memory
objectOutputStream.writeObject(this);
objectOutputStream.flush();
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
//Read instance from memory
clone = (DeepConcretePrototype) objectInputStream.readObject();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return clone;
}
i have a problem with download a textfile. I have no file contents after the dowload, the downloaded file is empty. Android and Core Api
#Override
protected Boolean doInBackground(Void... params) {
FileOutputStream outputStream = null;
try {
File fileDown = new File(LOCAL_PATH_DOWNLOAD);
outputStream = new FileOutputStream(fileDown);//
DropboxAPI.DropboxFileInfo info = mApi.getFile(DROPBOX_FILE_DIR_DOWNLOAD, null, outputStream, null);
return false;
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
}
return false;
}
What do i wrong? Thanks for help
i use above code to do this
File file= new File("/sdcard/New_csv_file.csv");
OutputStream out= null;
boolean result=false;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
DropboxFileInfo info = mApi.getFile("/photos/New_csv_file.csv", null, out, null);
Log.i("DbExampleLog", "The file's rev is: " + info.getMetadata().rev);
Intent JumpToParseCSV=new Intent(context,ParseCSV.class);
JumpToParseCSV.putExtra("FileName", file.getAbsolutePath());
Log.i("path", "FileName"+ file.getAbsolutePath());
((Activity) context).finish();
context.startActivity(JumpToParseCSV);
result=true;
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while downloading.");
file.delete();
result=false;
}
return result;
I am using Hibernate. I have mapped my column nIcon VARBINARY(MAX) in my object as the following
#Column(columnDefinition="binary")
public byte[] getNicon() {
return this.nicon;
}
The method getByteArrayFromFile() is used to get the bytes from an image file, which I successfully write to the database.
public static byte[] getByteArrayFromFile(String absoluteFilePath) {
byte [] byteArray = null;
File file = new File(absoluteFilePath);
byteArray = new byte[(int) file.length()];
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(byteArray);
} catch (FileNotFoundException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
}finally {
if(fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
}
}
}
return byteArray;
}
The method getFileFromByteArray() is used to write the image file from the byte array that I retrieve from the database.
public static boolean getFileFromByteArray(String fileName, byte [] byteArray) {
boolean isSuccessful = false;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(byteArray);
isSuccessful = true;
} catch (FileNotFoundException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
} finally {
if (fileOutputStream !=null) {
try {
fileOutputStream.close();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
}
}
}
return isSuccessful;
}
My problem is that I am using binary to store the file. I would like to use the IMAGE type in MS SQL Server.
I know that the Hibernate mapping #LOB can be used to store the image as IMAGE type.
BUT I am having problems while writing the bytes back to file.
I'm trying to detect a file content type passed to a web service into the SOAP envelop.
This file can be indicated in two ways :
from its url,
from its contain (base64 compressed data).
At this point, I'm able to translate this file into a stream buffer.
But, all my tries to get its content type failed.
The content type is detected if the file extension is indicated otherwise the content is always detected as "plain/text".
Bellow is my class code :
class MetadataAnalyser {
private InputStream _is;
private File _file;
private void initializeAttributes() {
_is = null;
_file= null;
}
private void createTemporaryFile(byte[] pData) {
FileOutputStream fos = null;
try {
_file = File.createTempFile(
UUID.randomUUID().toString().replace("-", ""),
null,
new File("C:\\Users\\Florent\\Documents\\NetBeansProjects\\ServiceEdition\\tmp"));
} catch (IOException e) {
e.printStackTrace();
}
try {
fos = new FileOutputStream(_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(pData);
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
_file.deleteOnExit();
}
public MetadataAnalyser(byte[] pData) {
initializeAttributes();
_is = new ByteArrayInputStream(pData);
createTemporaryFile(pData);
}
public MetadataAnalyser(InputStream pIs) {
initializeAttributes();
_is = pIs;
_file = null;
}
public MetadataAnalyser(File pFile) {
initializeAttributes();
try {
_file = pFile;
_is = new FileInputStream(_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public MetadataAnalyser(String pFile) {
initializeAttributes();
try {
_file = new File(pFile);
if (_file.exists()) {
_is = new FileInputStream(_file);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getContentType() {
AutoDetectParser parser = null;
Metadata metadata = null;
InputStream is = null;
String mimeType = null;
parser = new AutoDetectParser();
parser.setParsers(new HashMap<MediaType, Parser>());
metadata = new Metadata();
if(_file != null) {
metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, _file.getName());
}
try {
is = new FileInputStream(_file);
parser.parse(is, new DefaultHandler(), metadata, new ParseContext());
mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
} finally {
return mimeType;
}
}
}
So, how to detect the MIME type even if the file extension is unknown ?
I don't think you can detect the mime type without extension , you would need to know which system is writing the file and what kind of file is expected to be there and based on that you need to set the MIME type(I guess you are using it in your response).
You need to make sure the content is decoded before being sent to Tika and no, the extension is absolutely not needed, the detection happens via a well understood mime magic process described here: https://tika.apache.org/1.1/detection.html
i want to know how to read and write text to a .txt file in j2me help me thanks...
public String readFile(String path)
{
InputStream is = null;
FileConnection fc = null;
String str = "";
try
{
fc = (FileConnection)Connector.open(path, Connector.READ_WRITE);
if(fc.exists())
{
int size = (int)fc.fileSize();
is= fc.openInputStream();
byte bytes[] = new byte[size];
is.read(bytes, 0, size);
str = new String(bytes, 0, size);
}
}
catch (IOException ioe)
{
Alert error = new Alert("Error", ioe.getMessage(), null, AlertType.INFO);
error.setTimeout(1212313123);
Display.getDisplay(main).setCurrent(error);}
finally
{
try
{
if (null != is)
is.close();
if (null != fc)
fc.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
return str;
}
void writeTextFile(String fName, String text)
{
OutputStream os = null;
FileConnection fconn = null;
try
{
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
fconn.setHidden(false);
// fconn.setReadable(true);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (null != os)
os.close();
if (null != fconn)
fconn.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}