How does sparkjava(java webframe) auto refresh page - java

I`m new developper of spark, And now I was block by a issue.
I was implements freemarker as web template.
Not like other framework when you modify a .ftl file, You no need to restart the server.
But now in my local it must restart the server if I wanto see the change.
Below is code.
public class SparkServer {
public static void main(String[] args){
get("/hello",(request,response) ->{
Map root = new HashMap();
root.put("user", "xiekakaban");
Map product = new HashMap();
product.put("name","Pringles");
product.put("price",13.2);
root.put("product",product);
return new ModelAndView(root,"test.ftl");
},FreeMarkerEngine.getInstance());
}
}
public class FreeMarkerEngine extends TemplateEngine{
private static FreeMarkerEngine freeMarkerEngine;
private Configuration freeConfig;
private FreeMarkerEngine() throws IOException{
freeConfig = new Configuration();
freeConfig.setDirectoryForTemplateLoading(StringUtil.getResourceFile("templates"));
freeConfig.setTemplateUpdateDelay(1);
}
public static FreeMarkerEngine getInstance(){
if(freeMarkerEngine == null){
try {
freeMarkerEngine = new FreeMarkerEngine();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
return freeMarkerEngine;
}
#Override
public String render(ModelAndView modelAndView) {
StringWriter stringWriter = new StringWriter();
try {
freeConfig.clearTemplateCache();
freeConfig.clearSharedVariables();
freeConfig.clearEncodingMap();
Template template = freeConfig.getTemplate(modelAndView.getViewName());
template.process(modelAndView.getModel(), stringWriter);
System.out.println(stringWriter.toString());
return stringWriter.toString();
} catch (IOException | TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Can not find the template:"+modelAndView.getViewName();
}
}
I don`t sure whether it is cache by spark or freemarker.But I have clear freemarker cache.
Anyone can help me.....

ok, I have figure out it.
Reloading the static files in Spark/Jetty-server
first I think you should make sure which page the freemarker load.
if you not setup, it will load ftl under "target" fold.
I think I put out a stupid question....

Related

Accessing getProperty() outside of class

public static Properties defaultProps = new Properties();
static {
try {
FileInputStream in = new FileInputStream("config.properties");
defaultProps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getProperty(String database) {
return defaultProps.getProperty(database);
}
public static void main(String[] args) {
System.out.println(...key database?);
// this is the part where I try to test if I can print the property 'database'
// I also try to make it available to other classes, tried using public statics,
}
This is my code in which I retrieve the properties from properties file config.properties. However, I want to be able to print property N (here: database) and be able to use property N in other classes.
Thanks for the help in advance.
so just call
System.out.println(getProperty("database"));

java - reading .properties file and storing it in properties object

As mentioned in the title I have to read a .properties file in java and store it in a Properties object. I use a jFileChooser from java swing to get the file, which actually works, then I pass the file to a new window as calling arguments and then I use the load() method to store it in a Properties object but I get the java.lang.NullPointerException error. I hope I was clear as trying to explain it.
This is the code:
public void actionPerformed(ActionEvent e3) { //when button is pressed
JFileChooser fc2 = new JFileChooser (new File("C:\\Users\\Ciurga\\workspace\\PropertiesManager"));
fc2.setDialogTitle("Load Default Values File");
fc2.setFileFilter(new FileTypeFilter(".properties", "Properties File"));
int result = fc2.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
df = fc2.getSelectedFile(); //getting selected file and storing it in "df" which will be passed as calling argument
defaultNameTextField.setText(df.getName());
}
}
This is how I pass the file to the other window:
public void actionPerformed(ActionEvent e1) {
FormWindow w1 = new FormWindow (df, lf); //when button is pressed, create new window passing the files i got with jFileChooser
}
And this is how I tried to store it in a Properties object:
private static Properties propDef;
private static Properties propLim;
private void run(File def, File lim) {
try {
propDef.load(new FileInputStream(def));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
propLim.load(new FileInputStream(lim));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(propDef.getProperty("name"));
}
Thank you guys, as you said I only had to initialize it and now it seems to work correctly, it was a simple error but I'm actually a beginner in java.
This is what I changed:
private static Properties propDef = new Properties();
private static Properties propLim = new Properties();
You never initialised propDef, thats why you get the NullPointerException.
If you did initialise it, please provide the code!
Probably, your propDef and propLim are null and when you call propDef.load(new FileInputStream(def)); you get a NPE because load method is instance method.

Using variables from another method - problems understanding the object orientation

the following code is incomplete but the main focus of my question is on the method processConfig() anyway. It reads the properties out of a file and I want to handover these properties to the method replaceID(). It worked already when the content of processConfig was in the main()-method. But now I wanted to put this code into it´s own method. What is the best way of handing over the properties (which I saved in Strings like difFilePath). I´m not that familiar with OO-programming and want to understand the concept. Thanks for your help.
public class IDUpdater {
....
public static void main(String[] args) throws Exception {
//Here I want to call the variables from processConfig() to make them available for replaceID(...)
replaceID(difFilePath, outputDifPath, encoding);
}
public static void replaceID(String difFilePath, String outputDifPath, String encoding) throws Exception{
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
String difFilePath = prop.getProperty("dif_file_path");
String outputDifPath = prop.getProperty("output_dif_path");
String encoding = prop.getProperty("encoding");
}
}
You've to declare your variables globally. This way they can be accessed in each method. After you've declared them globally you first call your processConfig in your main method, which will set your variables to what they should be.
public class IDUpdater {
private String difFilePath;
private String outputDifPath;
private String encoding;
public void main(String[] args) throws Exception {
processConfig();
replaceID();
}
public void replaceID() throws Exception{
// You can use your variables here.
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
difFilePath = prop.getProperty("dif_file_path");
outputDifPath = prop.getProperty("output_dif_path");
encoding = prop.getProperty("encoding");
}
}
Note that I declared the variables privately. For more information about protecting your variables see https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx.
You may want to read an article (or even better yet - a book) on topic of encapsulation and objects. This or this may be a good starting point for you. There is no point in anyone fixing your code, if you don't understand the concepts behind it.

Delete all index data/files in disk using Apache Lucene?

How can I flush/delete/erase all the index files/data in the disk using Apache Lucene.This is my code so far and still I can't remove index files.Please help me out...
Test:
public class Test {
private static final String INDEX_DIR = "/home/amila/Lucene/REST/indexing";
public static void main(String[] args) {
try {
ContentIndexer contentIndexer = new ContentIndexer(INDEX_DIR);
contentIndexer.flushDisk();
System.out.println("Flushed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
ContentIndexer:
public class ContentIndexer {
private IndexWriter writer;
public ContentIndexer(String indexDir) throws IOException {
// create the index
if (writer == null) {
writer = new IndexWriter(FSDirectory.open(new File(indexDir)),
new IndexWriterConfig(Version.LUCENE_36,
new StandardAnalyzer(Version.LUCENE_36)));
}
}
public void flushDisk() {
try {
writer.deleteAll();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Edited -- Updated Answer
public class Test {
private static final String INDEX_DIR = "/home/amila/Lucene/REST/indexing";
public static void main(String[] args) {
try {
IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36,
new StandardAnalyzer(Version.LUCENE_36));
conf.setOpenMode(OpenMode.CREATE);
Directory directory = FSDirectory.open(new File(INDEX_DIR));
IndexWriter indexWriter = new IndexWriter(directory, conf);
indexWriter.deleteAll();
indexWriter.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The simplest way is to open IndexWriter with a CREATE mode (via indexWriterConfig.setOpenMode(...)). This removes all existing index files in the given directory.
For older versions IndexWriter constructor also has a special boolean create flag which does the same thing.
You can use two options :
You can call the delete all method of the writer
indexWriter.DeleteAll();
You can create a new indexWriter with the create flag set to true ( open mode= created)
new IndexWriter(_luceneDirectory, _analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);

Unable to add strings into arrayList

may i know why? i have passed in three strings to the addTab method and it is there in the variable when i debug but it says it is null why is that so? i have also instantiated the arrayList
public class STFile implements Serializable{
private ArrayList<String> qnsTitle;
private ArrayList<String> qnsImagePath;
private ArrayList<String> qnsSoundPath;
private Boolean fileExist;
//Constructor for STFile,gets existing data files if exists and load values from it to data files arraylists, if dont exist
//arraylists for data file will be instantiated.
public STFile()
{
setFileExists(checkIfAllFileExist());
if(getFileExist())
{
try {
setQnsTitle(STFile.readFile(STMain.TITLES_PATH));
setQnsImagePath(STFile.readFile(STMain.IMAGES_PATH));
setQnsSoundPath(STFile.readFile(STMain.SOUNDS_PATH));
}catch(IOException e)
{
System.out.println("in class STFile, IOEXception");
}catch(ClassNotFoundException e)
{
System.out.println("in class STFile, ClassNotFoundException");
}
}else
{
File titleFile = new File(STMain.TITLES_PATH);
File imageFile = new File(STMain.IMAGES_PATH);
File soundFile = new File(STMain.SOUNDS_PATH);
qnsTitle = new ArrayList<String>();
qnsImagePath = new ArrayList<String>();
qnsSoundPath= new ArrayList<String>();
}
}
public void addTab(String title,String imagePath,String soundPath)
{
getQnsTitle().add(title);
getQnsImagePath().add(imagePath);
getQnsSoundPath().add(soundPath);
try {
writeFiles();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("in STFile addtab Exception");
e.printStackTrace();
}
}
public static ArrayList<String> readFile(String filePath) throws ClassNotFoundException, IOException
{
ArrayList<String> arraylist = new ArrayList<String>();
ObjectInputStream obj_in = null;
FileInputStream f_in = null;
try {
f_in = new FileInputStream(filePath);
obj_in = new ObjectInputStream (f_in);
arraylist = (ArrayList<String>)obj_in.readObject();
return arraylist;
}catch(Exception e){
return null;
}finally{
f_in.close();
obj_in.close();
return null;
}
}
main method.
STFile file = new STFile();
file.addTab("Title", "image", "sound");
it keeps throwing
Exception in thread "main" java.lang.NullPointerException
at STFile.addTab(STFile.java:53)
at STMain.main(STMain.java:18)
Your readFile method will always return null, because you've got return null; in your finally block.
So if the file exists, qnsTitle (etc) will be null, causing the NullPointerException later.
I would strongly advise you not to catch Exception in the way you're doing in readFile, either. Only catch specific exceptions if you must do so at all - but in this case I wouldn't in the first place, or possibly only to wrap it in a different exception. Simply returning null from the catch block is hiding the fact that something's gone wrong, and introducing another problem further down the line. I suggest you just expand the throws clause of your method (e.g. to include IOException) and remove the catch block.
having return null; in your finally block in readFile could be the problem, try removing that.

Categories

Resources