Access public assets with Java in Play Framework - java

Is it possible to access Assets inside the Java code in Play Framework? How?
We access assets from the scala HTML templates this way:
<img src="#routes.Assets.versioned("images/myimage.png")" width="800" />
But I could not find any documentation nor code example to do it from inside the Java code. I just found a controllers.Assets class but it is unclear how to use it. If this is the class that has to be used, should it maybe be injected?

I finally found a way to access the public folder even from a production mode application.
In order to be accessible/copied in the distributed version, public folder need to be mapped that way in build.sbt:
import NativePackagerHelper._
mappings in Universal ++= directory("public")
The files are then accessible in the public folder in the distributed app in production form the Java code:
private static final String PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH = "public/images/";
static File getImageAsset(String relativePath) throws ResourceNotFoundException {
final String path = PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH + relativePath;
final File file = new File(path);
if (!file.exists()) {
throw new ResourceNotFoundException(String.format("Asset %s not found", path));
}
return file;
}
This post put me on the right way to find the solution: https://groups.google.com/forum/#!topic/play-framework/sVDoEtAzP-U

The assets normally are in the "public" folder, and I don't know how you want to use your image so I have used ImageIO .
File file = new File("./public/images/nice.png");
boolean exists = file.exists();
String absolutePath = file.getAbsolutePath();
try {
ImageInputStream input = ImageIO.read(file); //Use it
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("EX = "+exists+" - "+absolutePath);

Related

Properties file not loading and updating for relative path but working fine for absolute path

I am trying to access a properties file from the src/main/resources folder but when I try to load the file using a relative path it is not getting updated. But it is working fine for an absolute path.
I need the dynamic web project to work across all platforms.
public static void loadUsers() {
try(
FileInputStream in = new FileInputStream("C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties")) {
// write code to load all the users from the property file
// FileInputStream in = new FileInputStream("classpath:users.properties");
users.load(in);
System.out.println(users);
in.close();
}
catch(Exception e){
e.printStackTrace();
}
First of all you are using Spring, at least that is what the tags at the bottom say. Secondly C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties is the root of your classpath. Instead of loading a File use the Spring resource abstraction.
As this is part of the classpath you can simply use the ClassPathResource to obtain a proper InputStream. This will work regardless of which environment you are in.
try( InputStream in = new ClassPathResource("users.properties").getInputStream()) {
//write code to load all the users from the property file
//FileInputStream in = new FileInputStream("classpath:users.properties");
users.load(in);
System.out.println(users);
} catch(Exception e){
e.printStackTrace();
}
NOTE: you are already using a try with resources so you don't need to close the InputStream that is already handled for you.
Changing things inside your application simply won't work, as this would mean you could change resources (read classes) in your jar which would be quite a security risk! If you want something to be changable you will have to make it a file outside of the classpath and directly on the file-system.
Try the following code
import java.io.FileInputStream;
import java.io.IOException;
public class LoadUsers {
public static void main(String[] args) throws IOException {
try(FileInputStream fis=new FileInputStream("src/main/resources/users.properties")){
Properties users=new Properties();
users.load(fis);
System.out.println(users);
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

File not reading in selenium - maven framewaork

I tried to create a quick framework. in that I created below-mentioned classes:
Config file(All browsers path)
configDataProvider java class(reads the above file)
BrowserFactory class(has firefox browser object)
configDataProviderTest class(access data from dconfigDataProvider class)
now its not reading the paths mentioned in config.properties file.
I have provided all correct path and attached screenshots:
Looks like a problem is at your ConfigDataProvider class.
Firstly, you using Maven for building your project. Maven has defined project structure for code sources and for resources:
/src/main/java
/src/main/resorces
Thus, much better to put your .properties file there.
Second, you don't need to set the full path to your config file.
Relative path will be just enough. Something like below:
public class PropertiesFileHandler {
private static Logger log = Logger.getLogger(PropertiesFileHandler.class);
public static final String CONFIG_PROPERTIES = "src/main/resources/config.properties";
public static final String KEY = "browser.type";
public static BrowserType readBrowserType() {
BrowserType browserType = null;
Properties properties = new Properties();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(CONFIG_PROPERTIES))) {
properties.load(inputStream);
browserType = Enum.valueOf(BrowserType.class, properties.getProperty(KEY));
} catch (FileNotFoundException e) {
log.error("Properties file wasn't found - " + e);
} catch (IOException e) {
log.error("Problem with reading properties file - " + e);
}
return browserType;
}
}
Lastly, if you are building framework you don't need to put everything under src/main/test. This path specifies tests with future possibilities to be executed with maven default lifecycle - mvn test.
The core of your framework can look like:
Two things which I noticed:
Don't give path in your properties path within ""
all the path seperators should be replaced with double backward slash \\ or single forward slash /

TrueZip unable to extract file from archive

I am creating a java app that will extract the embedded thumbnail inside of a Powerpoint (PPTX) document. Since pptx files are zip archives, I am trying to use TrueZip to get the thumbnail found inside of the archive. Unfortunately whenever I try running my application it throws an IOException stating that the file is missing C:\Users\test-user\Desktop\DocumentsTest\Hello.pptx\docProps\thumbnail.jpeg (missing file)
Below is the code I use to get the thumbnail:
public Boolean GetThumbPPTX(String inFile, String outFile)
{
try
{
TFile srcFile = new TFile(inFile, "docProps\\thumbnail.jpeg");
TFile dstFile = new TFile(outFile);
if(dstFile.exists())
dstFile.delete();
srcFile.toNonArchiveFile().cp_rp(dstFile);
return dstFile.exists();
} catch (IOException ex) {
Logger.getLogger(DocumentThumbGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
Where inFile is the absolute path of the pptx file and outFile is the path that the thumbnail will be copied to. I can verify that the archive does have a thumbnail inside of it at the same exact path.
Can someone help please?
I just found the answer. It seems I did not have the Zip driver configured correctly. I added this to my class constructor and it all works now:
TConfig.get().setArchiveDetector(new TArchiveDetector(
TArchiveDetector.NULL,
new Object[][] {
{ "zip|pptx", new ZipDriver(IOPoolLocator.SINGLETON)},
}));

Open a properties file from a class in a Dynamic Web Project

I'm using Eclipse for EE Developer.
I need to access to a properties file (db.properties) from a class's method (DBQuery.java).
The class is located inside a package inside the src folder.
For the properties file i tried almost everything that i could find over the net to make it work, but looks like i can't.
The properties file is located inside the WebContent folder, and i'll add the code with which i'm trying to load this file:
public class DBQuery {
public static String create_DB_string(){
//the db connection string
String connString = "";
try{
Properties props = new Properties();
FileInputStream fis = new FileInputStream("db.properties");
props.load(fis);
fis.close();
/* creating connString using props.getProperty("String"); */
}
catch (Exception e) {
System.out.println(e.getClass());
}
return connString;
}
}
So my question is, where to put the properties file, and which is the correct way to load it?
You can put this propertie file within your java package for example com/test and use following:
getClass().getResourceAsStream( "com/test/myfile.propertie");
Hope it helps.

Create a public folder in internal storage

Sorry for my English, but I want to write in this file because in my opinion is the best.
Now my problem:
I want to create a folder in Internal storage to share with 2 application.
In my app, I downloaded an Apk from my server and I run it.
Before I used external storage and everything worked.
Now I want to use the internal storage for users that don't have an external storage.
I use this:
String folderPath = getFilesDir() + "Dir"
but when i try to run the Apk, it doesn't work, and I can't find this folder on my phone.
Thank you..
From this post :
Correct way:
Create a File for your desired directory (e.g., File path=new
File(getFilesDir(),"myfolder");)
Call mkdirs() on that File to create the directory if it does not exist
Create a File for the output file (e.g., File mypath=new File(path,"myfile.txt");)
Use standard Java I/O to write to that File (e.g., using new BufferedWriter(new FileWriter(mypath)))
Enjoy.
Also to create public file I use :
/**
* Context.MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application.
* Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
*/
public static void createInternalFile(Context theContext, String theFileName, byte[] theData, int theMode)
{
FileOutputStream fos = null;
try {
fos = theContext.openFileOutput(theFileName, theMode);
fos.write(theData);
fos.close();
} catch (FileNotFoundException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
}
}
Just set theMode to MODE_WORLD_WRITEABLE or MODE_WORLD_READABLE (note they are deprecated from api lvl 17).
You can also use theContext.getDir(); but note what doc says :
Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
Best wishes.
You can create a public into a existing system public folder, there is some public folder accessible from internal storage :
public static String DIRECTORY_MUSIC = "Music";
public static String DIRECTORY_PODCASTS = "Podcasts";
public static String DIRECTORY_RINGTONES = "Ringtones";
public static String DIRECTORY_ALARMS = "Alarms";
public static String DIRECTORY_NOTIFICATIONS = "Notifications";
public static String DIRECTORY_PICTURES = "Pictures";
public static String DIRECTORY_MOVIES = "Movies";
public static String DIRECTORY_DOWNLOADS = "Download";
public static String DIRECTORY_DCIM = "DCIM";
public static String DIRECTORY_DOCUMENTS = "Documents";
To create your folder, use this code :
File myDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyPublicFolder");
myDirectory.mkdir();
With this example, a public will be created in Documents and can be visible in any file's explorer app for Android.
try the below
File mydir = context.getDir("Newfolder", Context.MODE_PRIVATE); //Creating an internal dir;
if(!mydir.exists)
{
mydir.mkdirs();
}
This is what i have used and is working fine for me:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, fileName);
File parent=file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
This will create a new directory if not already present or use the existing if already present.

Categories