Create file inside folder "resources" of spring project - java

In my current spring, some forms have a field where the user can upload a file, which should be saves inside the folder resources from project (src/main/resources, following the structure created by maven).
the method responsible for save the file in this folder is working ok until this line:
URL path = this.getClass().getClassLoader().getResource(file);
the variable path is staying with the value null. the variable file is defined with this value:
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
Anyone can tell me the right way to do this?
PS.: the complete code for this method is:
public boolean upload_picture(E e, MultipartFile f) {
Integer id = null;
if(f == null) {
return false;
}
Class<?> clazz = e.getClass();
Method methods[] = clazz.getDeclaredMethods();
for(int i=0; i<methods.length; i++) {
if(methods[i].getName().equals("getId")) {
try {
id = (Integer) methods[i].invoke(e);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return false;
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
return false;
} catch (InvocationTargetException e1) {
e1.printStackTrace();
return false;
}
}
}
BufferedImage src;
try {
src = ImageIO.read(new ByteArrayInputStream(f.getBytes()));
} catch (IOException e3) {
e3.printStackTrace();
return false;
}
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
URL path = this.getClass().getClassLoader().getResource(file);
File destination;
try {
destination = new File(path.toURI());
} catch (URISyntaxException e2) {
destination = new File(path.getPath());
e2.printStackTrace();
}
try {
ImageIO.write(src, "jpeg", destination);
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}

Related

Is there a way to get a generic mp3 tag using mp3agic?

I'm developing an MP3 player with java, using mp3agic to edit .mp3 files metadata. The problem is: I don't know the specific tags of the files to edit the desired data.
Here's my code to get the mp3 track for example:
public static int get_rep(Music msc)
{
try
{
Mp3File file = new Mp3File(msc.get_path());
if (file.hasId3v1Tag())
{
ID3v1 tag = file.getId3v1Tag();
return Integer.parseInt(tag.getTrack());
}
else if (file.hasId3v2Tag())
{
ID3v2 tag = file.getId3v2Tag();
return Integer.parseInt(tag.getTrack());
}
}
catch (UnsupportedTagException e)
{
e.printStackTrace();
}
catch (InvalidDataException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return -1;
}
Is there a way to get the tag value skipping file.hasId3v1Tag() and file.hasId3v2Tag() verifications?
I tried:
private static Object get_tag(Music msc)
{
try
{
Mp3File file = new Mp3File(msc.get_path());
if (file.hasId3v1Tag())
{
return file.getId3v1Tag();
}
else if (file.hasId3v2Tag())
{
return file.getId3v2Tag();
}
/*
else if(file.hasCustomTag())
{
file.removeCustomTag();
return file.getCustomTag();
}
*/
}
catch (UnsupportedTagException e)
{
e.printStackTrace();
}
catch (InvalidDataException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return Boolean.FALSE;
}
But I still have to check the tags, then cast the Object value to a tag value, which means I'd have to know it anyway. I'm accepting any suggestions, even exchanging mp3agic.
ID3v2 extends ID3v1, so you should be able to use ID3v1 tag = file.getId3v2Tag(); and be able to extract ID3v1 data from it.
You could try this:
private static ID3v1 get_tag(Music msc) {
try {
Mp3File file = new Mp3File(msc.get_path());
if (file.hasId3v1Tag()) {
return file.getId3v1Tag();
} else if (file.hasId3v2Tag()) {
return file.getId3v2Tag();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Extracting RAR with JunRAR [duplicate]

I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}

Merge pdf files and loss of information

doing the merge of 2 or + pdf I lose some information that imposed in the upload phase of the files (ALT tags on the images). This is the method:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
PDFMergerUtility ut = new PDFMergerUtility();
try {
for (int i = 0; i < filesTBM.length; i++) {
ut.addSource(filesTBM[i]);
}
ut.setDestinationFileName(mergedFileLocation);
ut.mergeDocuments();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
}
}
If the PDF with the ALT tags were in the list of files to be merged, the result is correct, otherwise not. So far I've tried max with 3 PDFs including 1 with ALT tags.
The questions:
How can I not lose the alt tag after the merge of the files?
Thanks to those who want to help me
Daniele
N.b. I have also tried iText pdf:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
Document document = new Document();
PdfCopy copy = null;
try {
copy = new PdfCopy(document, new FileOutputStream(mergedFileLocation));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
document.open();
PdfReader[] reader = new PdfReader[filesTBM.length];
for (int i = 0; i < filesTBM.length; i++) {
try {
reader[i] = new PdfReader(filesTBM[i]);
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.addDocument(reader[i]);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.freeReader(reader[i]);
} catch (IOException e) {
e.printStackTrace();
}
reader[i].close();
}
document.close();
}

Jackcess DatabaseBuilder.open fails

I am using Jackcess API in my Eclipse plugin project. I added jackcess-2.1.0.jar file under resources/lib. I included the jar under my Binary build and in build.properties. I successfully make a connection using connection string but my DatabaseBuilder.open() call is not executing. My code is
public void run() {
try {
File tempTarget = File.createTempFile("eap-mirror", "eap");
try {
this.source = DriverManager.getConnection(EaDbStringParser.eaDbStringToJdbc(sourceString));
this.source.setReadOnly(true);
try {
FileUtils.copyFile(new File(templateFileString), tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
// Changes
try {
this.target = DatabaseBuilder.open(tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
Collection<String> tables = selectTables(source);
long time = System.currentTimeMillis();
for (String tableName : tables) {
long tTime = System.currentTimeMillis();
Table table = target.getTable(tableName);
System.out.print("Mirroring table " + tableName + "...");
table.setOverrideAutonumber(true);
copyTable(table, source, target);
System.out.println(" took "+ (System.currentTimeMillis() - tTime));
}
System.out.println("Done. Overall time: "+ (System.currentTimeMillis() - time));
System.out.println("done");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// More Code here
} catch (IOException e1) {
}
}
When I run the class in debug mode and I reach DatabaseBuilder.open call it fails.
Here is my project structure:
Can anyone tell me the possible reason for it ?
The .open method of DatabaseBuilder expects to open an existing well-formed Access database file. The .createTempFile method of java.io.File creates a 0-byte file. So, the code
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", "eap");
try (Database db = DatabaseBuilder.open(dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}
will cause Jackcess to throw
java.io.IOException: Empty database file
when it tries to do DatabaseBuilder.open(dbFile).
Instead, you should DatabaseBuilder.create to convert the 0-byte file into a real Access database file like this
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", ".accdb");
dbFile.deleteOnExit();
try (Database db = DatabaseBuilder.create(Database.FileFormat.V2010, dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}

where android saves serialized objects?

I'm looking for a place where are objects after serialization ? I would like to put serialized objects(created in another app) to my android project and then only load this files in my game. The problem is that I don't know where do I have to put this objects ? and even if I save object from android app it never saves in my project folder. My load and save functions for objects
public static void save(Context context, Map obj, String nazwa)
{
FileOutputStream str = null;
ObjectOutputStream objStr = null;
try {
str = context.openFileOutput(nazwa, Context.MODE_PRIVATE);
objStr = new ObjectOutputStream(str);
objStr.writeObject(obj);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (objStr != null) objStr.close();
} catch (IOException e) {}
try
{
if (str != null) str.close();
} catch (IOException e) {}
}
}
public static Map load(Context context, String nameFile)
{
Map obj = null;
FileInputStream str_w = null;
ObjectInputStream obj_w = null;
try
{
str_w = context.openFileInput(nameFile);
obj_w = new ObjectInputStream(str_w);
obj = (Map) obj_w.readObject();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
try
{
if (obj_w != null) obj_w.close();
} catch (IOException e) {}
try
{
if (str_w != null) str_w.close();
} catch (IOException e) {}
}
return obj;
}
If I copy my object file to /levels/ and use
final Map map2 = MapManager.load(this, "/levels/map1.lvl");
or
final Map map2 = MapManager.load(this, "levels/map1.lvl");
it never works
How should I do it ?
You're storing them as app private files (Context.MODE_PRIVATE) to a folder only the app has access to, so no other application will be able to access them.
I think the easiest way to store them so they can be shared between apps is to store them to the sdcard using:
Environment.getExternalStorageDir();
Be aware to store them as globally readable.

Categories