mysql database url, username and password in file - java

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

Related

How do i open all the links for a given URL using java?

Okay So I have the code to open up an URL using firebox. I'm just trying to find out how to open up all the links on that page, it can be done one at a time or all at once, but I just want to know. I can't seem to find this anywhere.
String url = "http://www.example.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

connect to database use properties file in java web application

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'

how can i instantiate an object from a compilationunit

I am trying to develop a plugin, which from a java file generate test and tables classes... when I select a Java source, I will be able to have an option "generate class test", the problem that I am recupering the Java file as ICompliationUnit, then I have a method that xtract methods of an object, that's why; I want to parse the IComplilationUnit to an instance of the class which represents, I tried to use Class.forName but it doesn't work , that's the code:
private void write(String dir, ICompilationUnit cu) throws JavaModelException
{
try
{
cu.getCorrespondingResource().getName();
System.out.println("0000000000000" + cu.getJavaProject().getProject().toString());
}
catch (JavaModelException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String test = cu.getCorrespondingResource().getName();
IPackageDeclaration[] test1 = cu.getPackageDeclarations();
// Need
String[] name = test.split("\\.");
String contentFile = dir + "\\" + name[0] + "content.txt";
GenerateFitnessTable inst = new GenerateFitnessTable();
try
{
String pack = test1[0].toString().substring(7, test1[0].toString().indexOf("[") - 1) + "." + name[0];
#SuppressWarnings("rawtypes")
Class classe = Class.forName(cu.getJavaProject().getProject().toString()
.substring(cu.getJavaProject().getProject().toString().indexOf("/"), cu.getJavaProject().getProject().toString().length())
+ pack);
try
{
classe.newInstance();
}
catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (ClassNotFoundException e1)
{
System.out.print("****************************la classe n'existe pas");
}
try
{
inst.generateContent(cu, contentFile);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this the right way ;)) , i found it :
// nouveau region
region = JavaCore.newRegion();
// ajout de la classe selectionné a cette region
region.add(cu);
if (JavaCore.getGeneratedResources(region, true).length == 0)
{
// bug
}
// recuperer l'url de .class
String url = "file:" + JavaCore.getGeneratedResources(region, true)[0].getLocation().makeAbsolute();
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while (data != -1)
{
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
clas = defineClass(pack.substring(1, pack.length()), classData, 0, classData.length);

Retrieving YouTube Channel insights though API

i'm using code below to get link for my channels insight data.
somehow my code is returning null as Link.
/* code***/
public static final String FEED_URL = "http://gdata.youtube.com/feeds/api/users/mychannelname/uploads"; //i put my channel's name in 'mychannelname'
String username = "mygmailid"; //here i entered my gmail id eg. mikeme#gmail.com
String password = "mypassword";
String developerKey = "AI39si7ffVeKWbG1k37***********************************************" //developer key
YouTubeService service = new YouTubeService( username ,developerKey); //just put username instead of clientid since client id no longer available
try {
service.setUserCredentials(username, password);
} catch (AuthenticationException e) {
System.out.println("Invalid login credentials.");
System.exit(1);
}
Query query = null;
try {
query = new Query(new URL( FEED_URL));
} catch (MalformedURLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
ChannelFeed channelFeed = null;
try {
channelFeed = service.query(query, ChannelFeed.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(channelFeed.getEntries() + ":");
System.out.println(" Link : "+channelFeed.getLink("http://gdata.youtube.com/schemas/2007#insight.views", "text/html") + ":");
/********END**********/
i'm getting null as Link here
can anyone help me here to find what went wrong here?
Thanks,
Mike
It is most likely returning null because it can't find a link corresponding to the relative name you provided. Since the channel Insight information is only available for the channel corresponding to the user you're authenticated with it could be that it is not authorizing your user to view that channels insight data, which could be because your google account is not linked with your youtube account.
I would try printing out the response you're getting back to make sure you're getting all the data you think you're getting.

Getting a DataSouce from url and driver

I need to initialize a DataSource given url and driver.
Its need to be generic enough to support Oracle and SQL Server.
the app is running on jboss 5.
provided sample for both:
<db-connection name="TEST-ORACLE">
<url>jdbc:oracle:thin:#test:1521:ins1</url>
<driver>oracle.jdbc.xa.client.OracleXADataSource</driver>
<user>user</user>
<password>{ENCR}oRloKFKlqXs=</password>
<min-size>5</min-size>
<max-size>30</max-size>
<idle-timeout-minutes>1</idle-timeout-minutes>
</db-connection>
<db-connections>
<db-connection name="TEST-MSSQLSERVER">
<url>jdbc:jtds:sqlserver://server:1433/db;ProgramName=program;SelectMethod=cursor;useLOBs=false</url>
<driver>net.sourceforge.jtds.jdbc.Driver</driver>
<user>user</user>
<password>{ENCR}oRloKFKlqXs=</password>
<min-size>40</min-size>
<max-size>80</max-size>
<idle-timeout-minutes>1</idle-timeout-minutes>
</db-connection>
The OracleXADataSource is implementing the inteface DataSource so its quit easy... but im not sure that generic enough.
EDIT
I wonder what should be the way to achive that if i have multipile db connections and multipile instances / schemas in those connections.....
my current code looks like:
private DataSource getDataSourceForTanent(TenantConfig i_Tenant) {
DataSource result = null;
ClassLoader loader = DBConnector.class.getClassLoader();
try {
Class driverClass = loader.loadClass(i_Tenant.getDriver());
Object driver = driverClass.newInstance();
if(driver instanceof OracleDataSource){
((OracleDataSource)driver).setURL(i_Tenant.getUrl());
((OracleDataSource)driver).setUser(i_Tenant.getUser());
((OracleDataSource)driver).setPassword(i_Tenant.getPassword());
result = (DataSource) driver;
} else if(driver instanceof Driver){
Properties prop = new Properties();
prop.put("user", i_Tenant.getUser());
prop.put("password", i_Tenant.getPassword());
prop.put("min-size", i_Tenant.getMinSize());
prop.put("max-size", i_Tenant.getMaxSize());
prop.put("idle-timeout-minutes", i_Tenant.getIdleTimeoutMinute());
Connection con = ((Driver)driver).connect(i_Tenant.getUrl(), prop);
if(con != null){
//TODO: SQLServer handling
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
TenantConfig is a java bean holding the xml properties.
Here's a generic code snippet to get a DataSource by JNDI name:
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/mydatasource");
But from your XML file I am not sure what the JNDI name is. What XML dialect is it?

Categories