How can i specify a different attachments path under play framework - java

I'm using play framework now, i already know we can specify the attachments path in application.conf:
# Store path for Blob content
attachments.path=data/attachments
My application have different kinds of pictures, i need to separate those pictures into different directories.
How can i implement my thought ?
Many thanks!
This is my controller code:
public static void uploadAvatar(Blob file){
if(request.isNew){
Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
User user = User.findById(userId);
// Delete old picture
if (user.avatar.getFile() != null) {
user.avatar.getFile().delete();
}
user.avatar = file;
user.avatarFileName = file.getFile().getName();
user.save();
}
Users.settings();
}

I would make a class which extends the current blob.class (http://www.playframework.org/documentation/api/1.2.4/play/db/jpa/Blob.html), and reimplement the getStore() method to read a different property than attachments.path (ie avatar.path).
Good luck!

Related

Deleting photo saved in folder using room database in android

I am taking photo using default camera in mobile. After that saving the photo in specific path in folder which path have been created using File class. In Room database I have storing only the path of image. Now, I added delete method to delete specific photo. I am using following query to delete,
#Query("DELETE FROM record_table WHERE photo_path = photoPath")
int deletePhotoPath(String photoPath);
below methods are used for deleting photo(DataRepository.class)
public void deletePhotoPath(String photoPath){
new deletePhotoPathAsyncTask(RecordDao).execute(photoPath);
}
private class deletePhotoPathAsyncTask extends AsyncTask<String,Void,Void>{
public deletePhotoPathAsyncTask(RecordDao dao) {
RecordDao=dao;
}
#Override
protected Void doInBackground(final String... strings) {
int photoPathDeleted=RecordDao.deletePhotoPath(strings[0]);
Log.d("deletePhotoPath"," Photo Path"+photoPathDeleted+strings[0]);
return null;
}
}
I am calling delete method as below(MyActivity.class),
HolderData.deletePhotoPath(photopathArrayList.get(positionOfCurrentViewPhoto));
In HolderData class I have following method to call delete method from database(HolderData.class),
public static void deletePhotoPath(String photoPath){
Log.d(LOG_TAG, "deletPhotoPath:"+photoPath);
dataRepository.deletePhotoPath(photoPath);
}
But my photo is not getting deleted. Logcats inside delete method works fine.
Doesn't know to delete photo. And How do I reflect the change in my design.
Anybody help me to solve this..Already Surfed a lot but not able to find a solution.
Don`t forget to add the colon when you refer to the argument parameter in your query:
DELETE FROM record_table WHERE photo_path = :photoPath
Before deleting the link from Room extract it, create a File instance programmatically and call "delete" method on that instance:
File file = new File("path to your file");
file.delete();

How do intelligent Agents work with data base?

I am working with JADE framework and I want to know is there any way for intelligent agents to work with some kind of data base, where they can read from it and write some information?..
I tried to make a connection between excel (using jxl) and my project but there is a problem: below is the code for writing in excel file:
public static void write(String[] args) throws Exception {
// TODO code application logic here
File f = new File("C:\\Users\\Mastisa\\Desktop\\Master.xls");
WritableWorkbook Master = Workbook.createWorkbook(f);
WritableSheet History_Table = Master.createSheet("History_Table", 0);
Label L00 = new Label (0,0,"RUN#");
History_Table.addCell(L00);
Master.write();
System.out.println("finished...");
Master.close();
}
}
but I want agents to do something like this:
Database D;
D.add(myAgent.getLocalName);
but it is not possible as jxl doesn't provide functions for working with agents. and it looks like that everything must be written in that excel file manually.... but it is not what I want.. I want agents comfortably read and write...
Is there any other way?
Yes basically when you create a JADE agent, you can add behaviors to those Agents,
There are several types of behaviors, you should be choosing them based on your requirement. You can find the list of behaviors here
For an Example,
public class MyAgent extends Agent
{
#Override
protected void setup()
{
addBehaviour( new InformBehaviour() );
}
private class InformBehaviour extends CyclicBehaviour
{
//dostuff
}
}
So basic idea is you need to do all these inside a behavior of a agent.
Make sure you choose right behaviour which suites your requirement.

Serialize JavaFX components

I'm trying to develop a little drag & drop application under Java FX. User will drop JFX components like Buttons, Menus, Labels on certain positions. When done, he will save this layout and later on he will reopen the layout and he will use it again.
Its important to store the information about all objects that are dropped on some position.
I decided to use serialization for this purpose. But I'm not able to serialize JavaFX components. I tried to serialize Buttons, Scenes, Stages, JFXPane but nothing seemed to work (I obtained NotSerializableException).
Any suggestions how to save all the components and then retrieve them ?
P.S.: I was trying to find out some method with FXML but I did not succeed.
Thank you very much for your answers :)
You are correct, JavaFX (as of 2.1) does not support serialization of components using the Java Serializable interface - so you cannot use that mechanism.
JavaFX can deserialize from an FXML document using the FXMLLoader.load() method.
The trick though, is how to write your existing components and states out to FXML?
Currently, there is nothing public from the platform which performs FXML serialization. Apparently, creating a generic scenegraph => FXML serializer is quite a complex task (and there is no public 3rd party API for this that I know of). It wouldn't be too difficult to iterate over the scenegraph and write out FXML for a limited set of components and attributes.
If the main goal of saving user components on the servers side - is to have a possibility to show the same interface to the user - why not to save all descriptive information you need about users components, and when it is needed - just rebuild user interface again, using stored descriptive information? Here is primitive example:
/* That is the class for storing information, which you need from your components*/
public class DropedComponentsCoordinates implements Serializable{
private String componentID;
private String x_coord;
private String y_coord;
//and so on, whatever you need to get from yor serializable objects;
//getters and setters are assumed but not typed here.
}
/* I assume a variant with using FXML. If you don't - the main idea does not change*/
public class YourController implements Initializable {
List<DropedComponentsCoordinates> dropedComponentsCoordinates;
#Override
public void initialize(URL url, ResourceBundle rb) {
dropedComponentsCoordinates = new ArrayList();
}
//This function will be fired, every time
//a user has dropped a component on the place he/she wants
public void OnDropFired(ActionEvent event) {
try {
//getting the info we need from components
String componentID = getComponentID(event);
String component_xCoord = getComponent_xCoord(event);
String component_yCoord = getComponent_yCoord(event);
//putting this info to the list
DropedComponentsCoordinates dcc = new DropedComponentsCoordinates();
dcc.setX_Coord(component_xCoord);
dcc.setY_Coord(component_yCoord);
dcc.setComponentID(componentID);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getComponentID(ActionEvent event){
String componentID;
/*getting cpmponentID*/
return componentID;
}
private String getComponent_xCoord(ActionEvent event){
String component_xCoord;
/*getting component_xCoord*/
return component_xCoord;
}
private String getComponent_yCoord(ActionEvent event){
String component_yCoord;
/*getting component_yCoord*/
return component_yCoord;
}
}

Wicket: make a generated csv available to a dygraphs JavaScript

I'm trying to figure out how to make a dynamically generated csv available to a dygraphs JavaScript.
I'm using a wicket behavior to add the dygraph (JavaScript graph) to my markup like shown in the codesample bellow. Right now I've hardcoded it to use a csv file named "dygraph.csv". I want to change this, and instead make dygraph use the values from String csv, how do I achieve this?
Any help help is greatly appreciated.
public class DygraphBehavior extends AbstractBehavior {
private static final long serialVersionUID = -516501274090062937L;
private static final CompressedResourceReference DYGRAPH_JS = new CompressedResourceReference(DygraphBehavior.class, "dygraph-combined.js");
#Override
public void renderHead(IHeaderResponse response) {
response.renderJavascriptReference(DYGRAPH_JS);
}
#Override
public void onRendered(Component component) {
final String id = component.getId();
Response response = component.getResponse();
response.write(JavascriptUtils.SCRIPT_OPEN_TAG);
response.write("new Dygraph(document.getElementById(\""+id+"\"), \"dygraph.csv\", {rollPeriod: 7, showRoller: true, errorBars: true});");
response.write(JavascriptUtils.SCRIPT_CLOSE_TAG);
}
}
public class Dygraph extends WebPage {
public Dygraph() {
String csv = "Date,ms\n20070101,62\n20070102,62";
add(new ResourceLink<File>("csv", new ByteArrayResource("text/csv", csv.getBytes())));
add(new Label("graphdiv").add(new DygraphBehavior()));
}
}
<div>
<h1>Dygraph:</h1>
<div wicket:id="graphdiv" id="graphdiv" style="width:500px; height:300px;"></div>
<a wicket:id="csv" href="#">dl generated csv</a>
</div>
public class Dygraph extends WebPage {
public Dygraph() {
String csv = "Date,ms\n20070101,62\n20070102,62";
ResourceLink<File> link = new ResourceLink<File>("csv", new ByteArrayResource("text/csv", csv.getBytes()));
add( link );
//this is the url that should be passed to the javascript code
CharSequence url = link.urlFor( IResourceListener.INTERFACE );
add(new Label("graphdiv").add(new DygraphBehavior()));
}
}
There are other solutions based on the scope of your resource, maybe a dynamic shared resource would work better (if your graph parameters can simply be passed as url parameters), but this will work.
The JavaScript needs to see the data in some way after the page has been rendered. So you have two options:
Embed the data in the page (say in a hidden div) and then let JavaScript read the data from there as text.
Create a servlet where the JavaScript can download the data from.
The second option means that your page rendering code has to pass the data somehow to the servlet. You can try to put it into the session but then, it will sit there, occupying RAM. Probably not a problem if it's just a little bit of data and you have only a few users. But if that's not true, option #1 is probably better.

How to check if a Java ResourceBundle is loadable, without loading it?

I would like to check the existence of a ResourceBundle without actually loading it.
Typically, I'm using Guice, and at initialization time, I want to check the existence, while at execution time, I want to load it. If the bundle doesn't exist, I want an early report of the inexistence of the RB.
If it was possible to get the ResourceBundle.Control instance used for a specific ResourceBundle, I would have no problem getting the basic information to build the actual resource name (using toBundleName() and toResourceName()), but it is not the case at that level.
Edit:
Ok, I found the way to do it. I'll create a ResourceBundle.Control that is extensible (using a custome addFormat(String, Class)) to store all the bundle formats, then use another method of my own to check all possible file names for a specific locale (using Class.getResource as indicated here below).
Coding speaking:
class MyControl extends ResourceBundle.Control {
private Map<String,Class<? extends ResourceBundle>> formats = new LinkedHashMap();
public void addFormat(String format,Class<? extends ResourceBundle> rbType) {
formats.put(format, rbType);
}
public boolean resourceBundleExists(ClassLoader loader, String baseName, Locale locale) {
for (String format: formats.keySet()) {
// for (loop on locale hierarchy) {
if (loader.getResource(toResourceName(toBundleName(baseName, locale), format)) != null) {
return true;
}
// }
}
return false;
}
}
If the default bundle must exists you can do:
Class.getResource("/my/path/to/bundle.properties")
and it will return an URL to the file or null if it doesn't exists.
Of course use the correct class or classloader if you have many.
EDIT: if you have resources as classes you have to check also
Class.getResource("/my/path/to/bundle.class")
In Java 6 you can store resource bundles in XML. I don't know how ResourceBundle class lookups this resource, but I bet it's in the same way.
You can load the bundles, thus making your checks, and then call ResourceBundle.clearCache() so that they are loaded again next time.
This happens once (at initialization time), and it isn't such a heavy operation, so it won't be a problem.
Or you can simply try to find whether a resource is present on the classpath. For example the fallback .properties file, or the properties file for your default locale.
Finally, after having a look at the code for ResourceBundle.Control, you have the option to do what they do in the newBundle() method.
Something like this, maybe
ResourceBundle bundle;
public PropertiesExist() {
String propsFile = "log4j";
String propsPath = this.getClass().getClassLoader().getResource(".").getPath();
File f = new File(propsPath, propsFile + ".properties");
if(!f.exists()){
System.out.println("File not found!!!!");
System.exit(-1);
}
bundle = ResourceBundle.getBundle(propsFile);
System.out.println(bundle.getString("log4j.rootLogger"));
}
public static void main(String[] args) {
new PropertiesExist();
}
This will look for the logging file, log4.properties, if not found program will exit

Categories