I write a code to connect to database from servlet.I want to use properties.but it does not work.i think i my code or properties file has problem.please help me to correct it.
try
{
Properties prop=new Properties();
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
prop.load(in);
in.close();
String drivers = prop.getProperty("jdbc.drivers");
String connectionURL = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
Class.forName(drivers);
con=DriverManager.getConnection(connectionURL,username,password);
System.out.println("Connection Successful");
..
and this is my properties file
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#192.168.101.84:1521:orcl
jdbc.username=user1
jdbc.password=123
Instead of
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
use
InputStream in = getClass().getResourceAsStream("dbConnection.properties");
try {
FileReader reader = new FileReader("Full Path");
Properties prop = new Properties();
prop.load(reader);
String drivers = prop.getProperty("jdbc.driverClassName");
String connectionURL = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
Class.forName(drivers);
Connection con = DriverManager.getConnection(connectionURL, username, password);
System.out.println("Connection Successful");
} catch (SQLException sqle) {
// TODO: Add catch code
sqle.printStackTrace();
} catch (FileNotFoundException fnfe) {
// TODO: Add catch code
fnfe.printStackTrace();
} catch (IOException ioe) {
// TODO: Add catch code
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
// TODO: Add catch code
cnfe.printStackTrace();
}catch (Exception e) {
// TODO: Add catch code
e.printStackTrace();
}
This part:
(System.getProperty("WEB-INF/dbConnection.properties"));
is actually referring to your classpath, try removing WEB-INF/ or just leave /, for checking root folder.
Or you can specify the fully qualified name, i.e : "C:\\foo\\test\\...\\dbConnection.properties" or "/app/blah/.../dbConnectionProperties"
For Class name, in the properties file you have defined the driver as 'jdbc.driverClassName'
but when passing variable you just pass as 'jdbc.drivers'
Related
So I've been working on taking the logic from an older webapp and making a new Spring Boot application out of it. I've come to a stuck spot regarding an ftp connection and call. Since I don't have a bunch of experience with this, I'm curious if there is a better/more modern way to handle most of this ftp stuff using Spring Boot/Thymeleaf and ways to go ahead and set that up. Any advice/guidance would be fantastic.
This is the older code that I'd like to modernize a bit.
String serverName = getFtpServer();
// Connect to the server
try {
ftp.connect(serverName);
ftp.enterLocalPassiveMode();
String replyText = ftp.getReplyString();
System.out.println(replyText);
} catch (Exception e) {
e.printStackTrace();
return false;
}
// Login to the server
try {
ftp.login(userName, password);
String replyText = ftp.getReplyString();
System.out.println(replyText);
} catch (Exception e) {
e.printStackTrace();
return false;
}
// Tell server that the file will have JCL records
try {
ftp.site("filetype=jes");
String replyText = ftp.getReplyString();
System.out.println(replyText);
} catch (Exception e) {
e.printStackTrace();
return false;
}
// Submit and run the JCL
try {
System.out.println("TRYING TO START MAINFRAME JCL");
submitJcl(filename, serverName);
String replyText = ftp.getReplyString();
System.out.println(replyText);
} catch (Exception e) {
String replyText = ftp.getReplyString();
System.out.println(replyText);
e.printStackTrace();
return false;
}
// Quit the server
try {
ftp.quit();
} catch (Exception e) {
e.printStackTrace();
}
Storing the file
private String submitJcl(String remoteFile, String serverName) throws IOException {
String filePath = getFilePath();
String result = "";
String fileName = filePath + remoteFile;
System.out.println("filePath = " + fileName);
FileInputStream inputStream = new FileInputStream(fileName);
ftp.storeFile(serverName, inputStream);
return result;
}
For this I figured out that there may be better ways to change it into the newer ftp format for Spring Boot, but this still completely works.
Changes I made to it regardless:
Consolidated the try/catch blocks into one.
Pushed the ftp stuff into its own function and then just called it inside the try/catch block
Changed all of the sys.out's to info.debugs.
Changed the way it gets the filePath to more of a relative path with the file stored within the system instead of user files.
I'm facing this error:
`Unable to load properties file for MultiWordNet
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:417)
at java.lang.Integer.<init>(Integer.java:660)
at org.itc.mwn.MysqlDictionary.<init>(MysqlDictionary.java:85)`
This is the property file that MysqlDictionary.java is trying to read:
#------------------------------------------------------------
#Properties file properties MultiWordNet API
#Hostname of the MySQL server
MWN_HOSTNAME=localhost
#User
MWN_USER=root
#Password
MWN_PASSWD=
#Database name
MWN_DB=wordnet
#Cache of entity
CACHE_CAPACITY=1000
And,finally, this is the part where the code fails:
public MysqlDictionary() {
try {
connectionParameters = new Properties();
connectionParameters.load(new FileInputStream(new File("./conf/multiwordnet.properties")));
} catch (java.io.IOException ioee) {
System.err.println("Unable to load properties file for MultiWordNet");
}
/// connection drivers instance
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Class.forName("org.gjt.mm.mysql.Driver").newInstance();
} catch(ClassNotFoundException E){
System.err.println("Unable to load driver");
} catch(IllegalAccessException E){
System.err.println("Unable to load driver");
} catch(InstantiationException E){
System.err.println("Unable to load driver");
}
// MultiWordnet db connection
String host = connectionParameters.getProperty("MWN_HOSTNAME");
String user = connectionParameters.getProperty("MWN_USER");
String passwd = connectionParameters.getProperty("MWN_PASSWD");
String dbname = connectionParameters.getProperty("MWN_DB");
Integer cache = new Integer(connectionParameters.getProperty("CACHE_CAPACITY"));
//here is where the parsing fails, but the file is properly written!
try {
DEFAULT_CACHE_CAPACITY = cache.intValue();
String conn = "jdbc:mysql://" + host + "/" + dbname;
this.db = DriverManager.getConnection(conn,user,passwd);
this.stmt = db.createStatement();
System.err.println("Welcome to the MultiWordNet API\nConnection database ...OK\n");
} catch (SQLException E) {
System.out.println("Unable to establish multiwordnet Mysql DB connection on " + host + "(" + user + " - " + passwd + ")");
E.printStackTrace(System.out);
}
The strange thing is that the program started suddenly failing, after it was running correctly
When dealing with File in java don't struggle with relative paths. They are quite unpredictable since they depend on the current working directory on which you don't have total control. Use classpath instead, loading the resource using the class loader:
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("multiwordnet.properties"));
Your problem isn't not being able to parse an integer, but not being able to load your file.
Check out for irregular invisible chars, like <SHIFT>+<SPACE> or <CTRL>+<SPACE> or else, next to CACHE_CAPACITY=1000.
Sounds a bit profanatory, but I've often enough stumbled upon such things.
Check for spaces in your properties file or try as below
String cacheProp = connectionParameters.getProperty("CACHE_CAPACITY")
//For debug
System.out.println("cacheProp="+cacheProp);
Integer cache = new Integer(cacheProp.trim());
This code worked fine for me i kept the properties file in resources folder(src/main/resources)
public static void MysqlDictionary() {
try {
Properties p = new Properties();
p.load(MyTest.class.getResourceAsStream("/test.properties"));
String host = p.getProperty("MWN_HOSTNAME");
String user = p.getProperty("MWN_USER");
String passwd = p.getProperty("MWN_PASSWD");
String dbname = p.getProperty("MWN_DB");
String cache = p.getProperty("CACHE_CAPACITY");
int i = Integer.parseInt(cache);
System.out.println(host+"\t"+user+"\t"+passwd+"\t"+dbname+"\t"+i);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
In my spring project, I have a service class to create my database and tables. After create the database (which is being done successfully), this method is called:
public void create_tables(String maquina, String usuario, String senha) {
System.out.println("create_tables");
create_properties(maquina, usuario, senha);
Configuration config = new Configuration();
Properties props = new Properties();
FileInputStream fos;
try {
fos = new FileInputStream( "database.properties" );
props.load(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
config.setProperties(props);
try {
String url = props.getProperty("jdbc.url");
Connection conn = DriverManager.getConnection(url,usuario,senha);
SchemaExport schema = new SchemaExport(config, conn);
schema.create(true, true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
insert_default_values();
}
But, despite in the Eclipse console display that the schema was exported successfully, no table is created in my database.
Anyone can see what's wrong here?
UPDATE
database.properties
#propriedades
#Sat May 10 12:52:57 BRT 2014
jdbc.url=jdbc\:postgresql\://localhost\:5432/horario
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=false
jdbc.user=<<my database user>>
jdbc.Classname=org.postgresql.Driver
hibernate.hbm2ddl.auto=update
jdbc.pass=<<my password>>
HibernateConfig.java -> https://github.com/klebermo/webapp_horario_livre/blob/master/src/com/horariolivre/resources/HibernateConfig.java
Entity classes -> https://github.com/klebermo/webapp_horario_livre/tree/master/src/com/horariolivre/entity
Dao classes -> https://github.com/klebermo/webapp_horario_livre/tree/master/src/com/horariolivre/dao
Try adding following code snippet:
config.addAnnotatedClass(com.horariolivre.entity.Atributo.class);
config.addAnnotatedClass(com.horariolivre.entity.Autorizacao.class);
...
Is this what you are looking for?
hey i want to upload a file to a directory called 'screenshots' on my webserver via FTP using java. I have been using this code and it says that it stores the file successfully and connected successfully but when i check my screenshots directory via the cpanel i dont see the file that was uploaded any help?
public static void uploadFilee() {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("****************");
client.login("********", "********");
System.out.println("Connected Successfully");
String filename = "C:/Users/Christian/Desktop/screenshots/img_" + queueInfo.get("SessionID");
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
System.out.println("Stored File Successfully");
client.logout();
} catch (IOException e) {
System.out.println("Error_1");
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
System.out.println("Error_2");
e.printStackTrace();
}
}
}
`
You may want to review this page
http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#_storeFile(java.lang.String,java.lang.String,java.io.InputStream)
you have your statements such as storefile in a try statement, but if they fail, they return false, not an exception.
changing your code to inspect the return values of each function should help you find where your problem lies.
how can I place my mysql database url, username and password in a file and how can I access them to use in my java code instead of hard coding them. I've tried google but am not getting clear direction
Create a properties file. You can load it by the Properties API.
E.g. config.properties:
url = jdbc:mysql://localhost:3306/dbname
username = foo
password = bar
Then you can load and read it as follows (after you've placed it in the classpath):
Properties config = new Properties();
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
String url = config.getProperty("url");
String username = config.getProperty("username");
String password = config.getProperty("password");
// ...
/**
* Function that connects to a DB and data fro connection is loaded from a properties file
* #param fileName
* #return the connection to DB or null if any problem
*/
public java.sql.Connection connect_to_database_from_properties(String fileName)
{
Properties prop = new Properties();
InputStream is;
try {
is = new FileInputStream(fileName);
prop.load(is);
String url=prop.getProperty("url");
String un=prop.getProperty("username");
String pass=prop.getProperty("password");
System.out.println("URL: "+url+" UN: "+un+" PASS: "+pass);
is.close();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conection =DriverManager.getConnection(url, un, pass);
return conection;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}