How to upload all document files Like PDF, DOCX,XLS to mysql Database using java and JPA and Spring
Thanks in advance
I did come across a similar situation but with Minor Modifications of your requirement.., like
DB - Oracle 11g (Instead of mySql)
IDE - jDeveloper 11 (To take care of Java, Swings - MVC)
If you'r cool with this modification plz have a look how I developed this,
Flow: UI(Pass the file)--->(Processing by IDE)--->DB(Data Saved)
Create a DB Schema:(2 Coloumns)
Info - Varchar 2 (Data Type)
Media - Blob
Now that done with DB, Come to IDE & create a .jspx Page (Without Backing Bean!), Drag & Drop InputFile Component from Component Palette. Create a Managed bean and write the following code to recieve the file as Parameter from UI & process further.
Code:-
public class Upload()
{
private UploadedFile _file;
public void setFile(UploadedFile _file) {
this._file = _file;
}
public UploadedFile getFile() {
return _file;
}
public String UploadMedia(){
UploadedFile myFile = (UploadedFile)this.getFile();
System.out.println("****************************************************");
BindingContext bc = BindingContext.getCurrent();
BindingContainer bindings = bc.getCurrentBindingsEntry();
DCBindingContainer dbc = (DCBindingContainer)bindings;
DCIteratorBinding iter = dbc.findIteratorBinding("MediadbVO1Iterator");
Row row = iter.getCurrentRow();
row.setAttribute("Media", createBlobDomain(myFile));
return null;
}
private BlobDomain createBlobDomain(UploadedFile file) {
InputStream in = null;
BlobDomain blobDomain = null;
OutputStream out = null;
try {
in = file.getInputStream();
blobDomain = new BlobDomain();
out = blobDomain.getBinaryOutputStream();
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.fillInStackTrace();
}
return blobDomain;
}
}
Set the "Value" field of InputFile Component as "#{backing_Upload.file}"
where backing_Upload is my bean name with file as Paramater.
Now Drag & Drop a Command Button & set its Action Field as "#{backing_Upload.UploadMedia}"
where backing_Upload is my bean name and UploadMedia is my method.
Hope you achieve what you desired on selecting file & clicking Button the file gets stored to DB.
You cannot store files in a DATABASE, but can store their location in the table.
Related
I'm trying to create a facturX using Mustang Library in a webservice. This web service accept a xml string and a base64 PDF.
My issue is that i have no "knowledge" about PDF format that is sent to me. In my service layer class, I build my facturx using ZUGFeRDExporterFromA1.
#Override
public FacturxDto createFacturX(FacturxDto facturxDto) {
context.setContext(facturxDto);
if (facturxDto.getVersion() == null) {
facturxDto.setVersion(2);
}
if(facturxDto.getPdfDocument() == null) {
throw new AppServiceException("Pdf is required in the payload");
}
if(facturxDto.getXml() == null) {
throw new AppServiceException("Xml is required in the payload");
}
if ((facturxDto.getVersion() < 1) || (facturxDto.getVersion() > 2)) {
throw new AppServiceException("invalid version");
}
try {
Utils.facturxValidator(facturxDto);
} catch (SAXException | IOException e) {
throw new AppServiceException(e.getMessage());
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
log.debug("Converting to PDF/A-3u");
PDFAConformanceLevel pdfaConformanceLevel = Utils.setPdfaConformanceLevel(facturxDto);
// System.out.println(Arrays.toString(facturxDto.getPdfDocument().getBytes(StandardCharsets.UTF_8)));
byte[] xmlData = facturxDto.getXml().getBytes(StandardCharsets.UTF_8);
byte[] pdfData = Base64.getDecoder().decode(facturxDto.getPdfDocument().getBytes(StandardCharsets.UTF_8));
try {
ZUGFeRDExporterFromA1 ze = new ZUGFeRDExporterFromA1()
.setProducer("Mustang LIB")
.setCreator("ME")
.setProfile(facturxDto.getFxLevel())
.setZUGFeRDVersion(facturxDto.getVersion())
.setConformanceLevel(pdfaConformanceLevel)
.ignorePDFAErrors()
.load(pdfData);
ze.attachFile("factur-x.xml", xmlData, "text/xml", "Data");
ze.setXML(xmlData);
log.debug("Attaching ZUGFeRD-Data");
ze.disableAutoClose(true);
ze.export(output);
byte[] bytes = output.toByteArray();
InputStream inputStream = new ByteArrayInputStream(bytes);
byte[] pdfBytes = IOUtils.toByteArray(inputStream);
String encoded = Base64.getEncoder().encodeToString(pdfBytes);
// persist data in db and generate id
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
FacturxEntity facturxEntity = modelMapper.map(facturxDto, FacturxEntity.class);
facturxEntity.setStatus(RequestOperationStatus.SUCCESS.name());
facturxEntity.setCreatedAt(new Date());
facturxEntity.setFacturxId(Utils.generateId());
FacturxEntity storedFacturx = facturxRepository.save(facturxEntity);
FacturxDto returnValue = modelMapper.map(storedFacturx, FacturxDto.class);
returnValue.setPdfDocument(encoded);
return returnValue;
} catch (IOException e) {
e.printStackTrace();
throw new AppServiceException(e.getMessage());
}
}
My issue is here :
ZUGFeRDExporterFromA1 ze = new ZUGFeRDExporterFromA1()
.setProducer("Mustang LIB")
.setCreator("ME")
.setProfile(facturxDto.getFxLevel())
.setZUGFeRDVersion(facturxDto.getVersion())
.setConformanceLevel(pdfaConformanceLevel)
.ignorePDFAErrors()
.load(pdfData);
If i don't use ignorePDFAErrors() I do have an exception thrown.
If i use it, my pdf is not PDFA compliant. And it's an issue.
Is there a way to convert on the fly an invalid PDFA to a valid one. Thanks
You can e.g. use Mustang's REST API, Mustang Server https://www.mustangproject.org/server/ to correct and export any input PDF file as PDF/A, which also includes files which are already PDF/A-1.
kind regards
Jochen
I need to fetch a user uploaded XML file from the DAM, parse this file and store the contents in the JCR. Here's what I have so far
public class foo implements Runnable {
private static final Logger log = LoggerFactory
.getLogger(foo.class);
#Reference
ResourceResolverFactory resourceResolverFactory;
#Reference
ResourceProvider resourceProvider;
ResourceResolver resourceResolver = null;
#Reference
SlingRepository repository;
Session session;
// private static ReadXMLFileUsingDomparserTest readxml;
File tempFile;
public void run(){
log.info("\n *** Seems okay ***\n");
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
Resource resource = resourceResolver.getResource("/content/dam/foo/file.xml");
Node node = resource.adaptTo(Node.class);
boolean isAssest = DamUtil.isAsset(resource);
if (isAssest) {
Asset asset = resource.adaptTo(Asset.class);
List<Rendition> rendition = asset.getRenditions();
for (Rendition re : rendition) {
InputStream in = re.getStream();
File xmlFile = copy(in,tempFile);
if(filetest.exists()){
ReadXMLFileUsingDomparserTest.parseXML(filetest,null);
}else {
log.info("File not found at all");
}
}
}
File xmlFile = copy(in,tempFile);*/
}catch (Exception e) {
log.error("Exception while running foo" , e);
}
}
private File copy(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
}
Although I'm able to pick up the Node object correctly (doing Node.getPath() returns the correct path), I am not able to translate this node into a File object. (cannot be Adapted). I want to access this in terms of a File object for parsing. This is why I went through the renditions of the asset and used the stream to copy it into a file.
However, this always shows null for the above code; the output is always File not found at all.
What is the correct way to get a File object with the requisite data from the DAM so that I can successfully parse it?
Uploaded xml file should have an nt:file node, which has a jcr:content node with jcr:data property. You can read the xml from jcr:data i.e: jcrContent.getProperty("jcr:data").getBinary().getStream();
Here are the build in adapters: http://dev.day.com/docs/en/cq/current/developing/sling-adapters.html
I think you can use InputStream here...
At the very begining - sorry for my english.
I'm developing a play-application in java and deploy it to heroku.
I like to create a picture (a QRCode to be precisely), store it temporary and display it on the next page.
I do know about herokus ephemeral filesystem, but if I understand right, on the cedar stack, I am able to create files wherever I like, as long as it's ok, that they won't be stored for a long time. The app just needs to generate a QR, I scan it and the file may be deleted.
It seems as if the file is not created. Any ideas of how I can manage to temporary save and show my QRs?
Controller
public class Application extends Controller {
private static String workingDirectory = "public/images/";
public static Result qrCode() {
String msg = "I am a QR-String";
BufferedImage image = (BufferedImage) QR.stringToImage(msg);
String imgPath = workingDirectory+"posQR.png";
try{
File outputfile = new File(imgPath);
ImageIO.write(image,"png",outputfile);
}catch(IOException e){
e.printStackTrace();
}
return ok(views.html.qrCode.render());
}
}
View qrCode
<img src="#routes.Assets.at("images/posQR.png")">
Edit 1
Stored the image as tempFile an pass it to the view.
On heroku an local the view contains the exact absolute path, but the image won't load.
Any ideas left?
Controller
public class Application extends Controller {
private static String workingDirectory = "public/images/";
public static Result qrCode() {
String msg = "I am a QR-String";
BufferedImage image = (BufferedImage) QR.stringToImage(msg);
File outputfile = null;
String imgPath = workingDirectory+"posQR.png";
try{
outputfile = File.createTempFile("posQR",".png");
ImageIO.write(image,"png",outputfile);
}catch(IOException e){
e.printStackTrace();
}
return ok(views.html.qrCode.render(outputfile.getAbsolutePath()));
}
View qrCode
#(qrPath: String)
...
<img id="qr" src=#qrPath>
Does workingDirectory end with file separator?
String imgPath = workingDirectory+"posQR.png";
This helped me: Play! framework 2.0: How to display multiple image?
Finaly I did it. The trick was not to do src=path but src=getImage(path). Still strange, but now it works.
routes
GET /tmp/*filepath controllers.Application.getImage(filepath: String)
Application
public class Application extends Controller {
public static Result qrCode() {
String msg = "I am a QR-String";
BufferedImage image = (BufferedImage) QR.stringToImage(msg);
File outputfile = null;
try{
outputfile = File.createTempFile("posQR",".png");
ImageIO.write(image,"png",outputfile);
}catch(IOException e){
e.printStackTrace();
}
return ok(views.html.qrCode.render(outputfile.getAbsolutePath()));
}
...
public static Result getImage(String imgPath){
return ok(new File(imgPath));
}
}
view qrCode
#(qrPath: String)
...
<img src="#routes.Application.getImage(qrPath)"/>
Thanks for your help :D
I found here: what I was searching for but still I have some issues.
This is my action code:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile());
jEditorPane1.setText(image);
}
}
Here is a screenshot of what happens, as you can see the image is not loaded.
http://postimg.org/image/agc665ih1/
But if I save the file (with save button) and reopen the same file (with open button), the image is there and is perfectly loaded.
I already tried the .repaint() and .revalidate() methods, but is not working..
Any idea?
This may be problem in setting up path in JEditorPane page. use this:
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile().getPath());
I am assuming that you have already selected appropriate editorKit for JEditorPane.
So now I can answer with my code. I am using this class for the file chooser:
import java.io.File;
import javax.swing.filechooser.FileFilter;
class jpgfilter extends FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".jpg");
}
public String getDescription() {
return "JPG image (*.jpg)";
}
}
And in my main class I have this:
FileChooser1 = new javax.swing.JFileChooser();
FileChooser1.setDialogTitle("Choose your image:");
FileChooser1.setFileFilter(new jpgfilter());
And that's it.
So I actually found some kind of a solution but I think there is really too much code and that I should do it easily..I actually insert the image and simultaneously save and open the content of the EditorPane as .html file.
The code:
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1
.getSelectedFile().getPath());
jEditorPane1.setText(image);
String type = jEditorPane1.getContentType();
OutputStream os = new BufferedOutputStream(new FileOutputStream(
"/Library/java_test/temp" + ".html"));
Document doc = jEditorPane1.getDocument();
int length = doc.getLength();
if (type.endsWith("/rtf")) {
// Saving RTF - use the OutputStream
try {
jEditorPane1.getEditorKit().write(os, doc, 0, length);
os.close();
} catch (BadLocationException ex) {
}
} else {
// Not RTF - use a Writer.
Writer w = new OutputStreamWriter(os);
jEditorPane1.write(w);
w.close();
}
String url = "file:///" + "/Library/java_test/temp" + ".html";
jEditorPane1.setPage(url);
}
What I'm trying to do is this: I want my application to download an image from the Internet and save it to the phone's internal memory in a location that is private to the application. If there is no image available for the list item (i.e. it can't be found on the Internet), I want a default placeholder image to display. This is the image that I have defined in my list_item_row.xml file as the default.
In my ListActivity file, I am calling an instance of a CustomCursorAdapter class I have written. It is in CustomCursorAdapter where I am iterating through all the list items and defining what content needs to be mapped to the views, including the image file by trying to read it from internal memory.
I've seen several questions on this subject, but the examples either are specific to external phone memory (e.g. SDCard), involve saving strings instead of images, or involve using Bitmap.CompressFormat to reduce the resolution of the file (which is unnecessary in my case, as these images will be small thumbnails of already-small resolution). Trying to piece together code from each example has been difficult, hence my asking about my specific example.
At the moment, I believe I've written valid code, but no image is displaying for my list items, including the default placeholder image. I don't know if the problem is being caused by invalid download/save code, or invalid read code - it doesn't help that I don't know how to check internal memory to see if the image exists.
Anyways, here's my code. Any help would be greatly appreciated.
ProductUtils.java
public static String productLookup(String productID, Context c) throws IOException {
URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
FileOutputStream output =
c.openFileOutput(productID + "-thumbnail.jpg", Context.MODE_PRIVATE);
byte[] data = new byte[1024];
output.write(data);
output.flush();
output.close();
input.close();
}
CustomCursorAdapter.java
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
String fileName =
cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_IMAGE_FILE_PATH));
Bitmap bMap = BitmapFactory.decodeFile(fileName);
thumbnail.setImageBitmap(bMap);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list_item_row, parent, false);
bindView(v, context, cursor);
return v;
}
}
it seems that some code is left out, I re-wrote it like this:
ProductUtils.java
public static String productLookup(String productID, Context c) throws IOException {
URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
InputStream input = null;
FileOutputStream output = null;
try {
String outputName = productID + "-thumbnail.jpg";
input = url.openConnection().getInputStream();
output = c.openFileOutput(outputName, Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = input.read(data)) != -1)
output.write(data, 0, read);
return outputName;
} finally {
if (output != null)
output.close();
if (input != null)
input.close();
}
}
Looks like simply referring to the image file name when trying to read it was not enough, and I had to call getFilesDir() to get the path of the file storage. Below is the code I used:
String path = context.getFilesDir().toString();
String fileName = cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_PRODUCT_ID));
if (fileName != null && !fileName.equals("")) {
Bitmap bMap = BitmapFactory.decodeFile(path + "/" + fileName);
if (bMap != null) {
thumbnail.setImageBitmap(bMap);
}
}
void writeToFile(Bitmap _bitmapScaled)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
try{
File f;
//you can create a new file name "test.jpg" in sdcard folder.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
f =new File(android.os.Environment.getExternalStorageDirectory(),"FamilyLocator/userimages/"+imageName);
else
f = new File(Environment.getDataDirectory(),"FamilyLocator/userimages/"+imageName);
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
}catch(Exception e){e.printStackTrace();}
}