Cannot load properties file in java - java

I try to load properties file as below,
public class A_Main {
private static FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties");
private static Properties properties = new Properties();
private static properties.load(reader);
public static String UserName = properties.getProperty("lists.user");
public static String Passwd = properties.getProperty("lists.password");
......
......
......
public static void main(String[] args) throws IOException {
Configuration_Report conf = new Configuration_Report();
try {
conf.conf_report(UserName, Passwd);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......
However, in eclipse it marked an error under below code,
private static properties.load(reader);
I try to change everything to public static also, however it seem the properties file cannot be load as reader seem not recognize.

As shared by Elliott above, you need to call the load function either from the static block. If you call it from the static block then you will have to take care that you initialize username and password (and any other dependencies) as well in the static block. Or the other option would be to initialize them at the starting of the main function:
Static Block:
public class A_Main {
private static Properties properties = new Properties();
public static String UserName = null;
public static String Passwd = null;
static{
try (FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties"))
{
properties.load(reader);
UserName = properties.getProperty("lists.user");
Passwd = properties.getProperty("lists.password");
} catch (IOException e) {
e.printStackTrace();
}
}
......
......
......
public static void main(String[] args) throws IOException {
Configuration_Report conf = new Configuration_Report();
try {
conf.conf_report(UserName, Passwd);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......
Inside Main Function:
public class A_Main {
private static Properties properties = new Properties();
public static String UserName = null;
public static String Passwd = null;
......
......
......
public static void main(String[] args) throws IOException {
try (FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties"))
{
properties.load(reader);
UserName = properties.getProperty("lists.user");
Passwd = properties.getProperty("lists.password");
Configuration_Report conf = new Configuration_Report();
conf.conf_report(UserName, Passwd);
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......

That is not valid syntax for invoking a function on a class member. You could use a static initialization block. And that FileReader constructor can also throw an Exception. You could move that initialization into the same block. Like,
private static FileReader reader;
private static Properties properties = new Properties();
static {
try {
reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties");
properties.load(reader);
} catch (IOException e) {
e.printStackTrace();
}
}

Related

File not found exception when accessing a method from servlet

I have a java class with a file path.When i try to run that as java application it is working fine but when i try to access that method in the class from a servlet I am getting error java.io.FileNotFoundException
Java Class
public class PropertiesManager {
static Properties prop =new Properties();
static String PROPERTY_FILENAME = "Dashboard1.0/src/server_url.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.getProperty("DemoApps_DataBase"));
updateProperty();
}
public static void loadProperty(){
InputStream input = null;
try {
FileInputStream file= new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(file);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty("DemoApps_DataBase", "Oracle");
System.out.println(prop.getProperty("DemoApps_DataBase"));
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Servlet Class
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=request.getParameter("appName");
String link=request.getParameter("appLink");
String database=request.getParameter("appDB");
String webServices=request.getParameter("appWebService");
PropertiesManager.loadProperty();
PropertiesManager.updateProperty();
RequestDispatcher rd=request.getRequestDispatcher("updateappstatus.jsp");
rd.forward(request,response);
}

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);

Catching an exception when instantiating a class field

I want to instantiate a URL as a private field in a class, but I can't catch the MalformedURLException. I've tried using a static initialization block, but that doesn't work either. How do I solve this?
public class MyClass{
private final static URL DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")
...
}
You will need to throw something in the case of an exception. An Error should do the job.
public class MyClass{
private static final URL DEFAULT_URL;
static {
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")
} catch (java.net.MalformedURLException exc) {
throw new Error(exc);
}
}
...
}
In case an exception is thrown (it shouldn't be) the class will fail to initialse.
A simple workaround is to create a static method:
private final static URL DEFAULT_URL = getDefaultUrl();
private static URL getDefaultUrl() {
try {
return new URL("http://www.yadayada.com?wsdl");
} catch (Exception e) {
//what do you want to do here?
return null; //that is an option
throw new AssertionError("Invalid URL"); //that is another one
}
}
You can do it in the static block
public class MyClass {
private final static URL DEFAULT_URL;
static {
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
} catch (MalformedURLException e) {
}
}
Using static block initializer - you may catch exception inside the block.
However, I would not recommend to store it as final class field as URI. Place it as String constant and initialize in constructor or special init() intance method
Try below. you cannot use final keyword for below:
private static URL DEFAULT_URL = null;
static{
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

"Could not find the main class, program will exit" while initializing class containing main()?

The class partially shown below contains a main method. When I run the code, I see a NullPointerException (NPE) and then an error message - "Could not find the main class, program will exit". My understanding is that if I get NPE, it means that the code is running, ie the JRE found a main method to begin execution, so why do I get the error message?
This is the console output
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at com.MyWorldDemo.getValue(MyWorldDemo.java:57)
at com.MyWorldDemo.<clinit>(MyWorldDemo.java:23)
Exception in thread "main"
In a nutshell:
username is stored in a properties file.
properties file is like this username=superman....etc
here is some code example
class MyClass {
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
// this method will assign a value to my final variable username.
public static String getData(String props) {
String property = prop.getProperty(props);// ERROR HERE !!!
return property;
}
}
Initializing of static variables depends on its position in code (variables are initialized from top to bottom). In your code
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
prop object will be initialized after username in static block, but since to initialize username prop is necessary and its not initialized yet you get NPE. Maybe change your code to something like:
private static Properties prop = new Properties();
private final static String username = getData("username");
static {
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
You have a static initialization at line 23 of MyWorldDemo that is calling the method getValue, which is then causing a NPE at line 57, therefore the class cannot be instantiated, therefore the main method cannot be called. It probably looks something like:
class MyWorldDemo {
private static String foo = getValue("username");
private static Properties prop;
// This happens too late, as getValue is called first
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch(IOException ex) {
ex.printStackTrace();
}
}
// This will happen before static initialization of prop
private static String getValue(String propertyValue) {
// prop is null
return prop.getProperty(propertyValue);
}
public static void main(String args[]) {
System.out.println("Hello!"); // Never gets here
}
}

Problem when using code from a jar file

I run the following code:
public class Sign {
private static final PrivateKey priv = Util.loadPrivate();
private static final PublicKey pub = Util.loadPublic();
private static final HexBinaryAdapter adp = new HexBinaryAdapter();
public static String sign(String in) {
try {
Signature sign = Signature.getInstance(Util.ALG);
sign.initSign(priv);
sign.update(in.getBytes());
return adp.marshal(sign.sign());
} catch (Exception e) {e.printStackTrace();}
return null;
}
public static boolean verify(String data, String sign) {
try {
Signature verify = Signature.getInstance(Util.ALG);
verify.initVerify(pub);
verify.update(data.getBytes());
return verify.verify(adp.unmarshal(sign));
} catch (Exception e) {e.printStackTrace();}
return false;
}
}
and the main function looks like this:
public static void main(String[] args) {
String in = "lala";
String sign = Sign.sign(in);
System.out.println(sign);
System.out.println(Sign.verify(in, sign));
}
Everything goes well when I run it from within Eclipse (the output is "true"), but when I pack it into a jar (without the main function) and run it then the output is false.
This is how I load the keys:
public static PrivateKey loadPrivate() {
try {
URLConnection con = Util.class.getResource("private.key").openConnection();
byte[] bs = new byte[con.getContentLength()];
con.getInputStream().read(bs);
return KeyFactory.getInstance(ALG).generatePrivate(new PKCS8EncodedKeySpec(bs));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static PublicKey loadPublic() {
try {
URLConnection con = Util.class.getResource("public.key").openConnection();
byte[] bs = new byte[con.getContentLength()];
con.getInputStream().read(bs);
return KeyFactory.getInstance(ALG).generatePublic(new X509EncodedKeySpec(bs));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I checked and loading the keys works fine.
Any idea ?
Just run like this:
java Main -classpath=/path/to/libraryk.jar

Categories

Resources