How to get a file resource in JSF project - java

I am trying to write a simple JSF application to let a user login on a web browser then my application should verify the users credentials on a MySQL database.
I am having trouble getting my code to see the database.properties file. I use the following code for all my stand alone database programs but I had to make some modifications for this JSF application that I am writing.
About 3/4 of the way down the following line throws a ClassNotFoundException because my url variable is null and I don't know why:
FileInputStream in = new FileInputStream(url.getFile()); // Do this if on Server
Can anyone help me? Thanks! The code in question is in the first half of method init(String fileName).
Below is the entire class for getting the data source:
package com.gmail.gmjord.datasource;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* A simple data source for getting database connections.
*/
public class SimpleDataSource {
private static String urlString;
private static String username;
private static String password;
/**
* Initializes the data source.
*
* #param fileName
* the name of the property file that contains the database
* driver, URL, username, and password
*/
public static void init(String fileName) throws IOException,
ClassNotFoundException {
// ****************** Added code for getting resource on a server
// *********************
System.out.println("In SimpleDataSource.init()");
**Class cls = Class.forName("com.gmail.gmjord.datasource.SimpleDataSource");**
System.out.println("Made it here 1");
// returns the ClassLoader object associated with this Class
ClassLoader cLoader = cls.getClassLoader();
System.out.println("Made it here 2");
System.out.println(cLoader.getClass());
// finds resource with the given name
URL url = cLoader.getResource(fileName); // This is the original line I copied from the web page
//URL url = cls.getClass().getClassLoader().getResource(fileName); // This is TA's way
System.out.println("Made it here 3");
System.out.println("File: " + fileName);
System.out.println("url Value = " + url);
// ********* End of code for getting resource on a server*******************************************************
Properties props = new Properties();
//System.out.println("File: " + fileName);
//FileInputStream in = new FileInputStream(fileName); // Do this if not on server
FileInputStream in = new FileInputStream(url.getFile()); // Do this if on Server
props.load(in);
String driver = props.getProperty("jdbc.driver");
urlString = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
if (username == null)
username = "";
password = props.getProperty("jdbc.password");
if (password == null)
password = "";
if (driver != null)
Class.forName(driver);
}
/**
* Gets a connection to the database.
*
* #return the database connection
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(urlString, username, password);
}
}

First you need to move the file inside to the src folder, for the next code it must be in the root of the src folder, you can load the file in this way:
Properties properties = new Properties();
properties.load(SimpleDataSource.class.getResourceAsStream("/database.properties"));

Related

Getting a file as a resource on classpath

I'm trying to read a keystore as a resource. Sample code below. The problem I'm running into is that inputStream remains null.
import java.io.InputStream;
import java.util.List;
import org.linguafranca.pwdb.kdbx.KdbxCreds;
import org.linguafranca.pwdb.kdbx.simple.SimpleDatabase;
import org.linguafranca.pwdb.kdbx.simple.SimpleEntry;
import org.linguafranca.pwdb.Credentials;
import org.apache.log4j.Logger;
public class Security {
private static final String PATH = null;
private static final String KEYSTORE_PASSWORD = "admin";
static List<SimpleEntry> entries = null;
final static Logger logger = Logger.getLogger(Security.class);
public Security(){
//TODO: initialize security and it's passwords
}
public static void init(){
try {
//InputStream inputStream = new FileInputStream(".keePass.kdbx");
InputStream inputStream = Security.class.getClassLoader().getResourceAsStream("keePass.kdbx");
// password credentials
Credentials credentials = new KdbxCreds(KEYSTORE_PASSWORD.getBytes());
SimpleDatabase database = SimpleDatabase.load(credentials, inputStream);
// Jaxb implementation seems a lot faster than the DOM implementation
// visit all groups and entries and list them to console
entries = database.getRootGroup().getEntries();
}catch(Exception exception){
logger.error(exception);
}
}
}
First I thought it's just a matter of path, however even though the file itself resides next to the classes, I can't load it.
Even if I use absolute path, result is the same.
What is the mistake I'm making?
When you are using getClassLoader().getResourceAsStream("...") it tries to find the file in the root of classpath. Try to use:
Security.class.getResourceAsStream("keePass.kdbx");
In this case it will try to find the file in the same location as the Security class
See more What is the difference between Class.getResource() and ClassLoader.getResource()?

Google Drive API REST V2 insert file into folder file not found

I am trying to upload a file into one of my company's Google Drive folders but I haven't managed to achieve this without client intervention. So, whenever I use this:
package sample;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class DriveCommandLine_srive
{
private static String CLIENT_ID = "myClientID.apps.googleusercontent.com";
private static String CLIENT_SECRET = "myClientSecret";
private static String REDIRECT_URI = "mything";
public static void main( String[] args ) throws IOException
{
HttpTransport httpTransport = new NetHttpTransport( );
JsonFactory jsonFactory = new JacksonFactory( );
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList( DriveScopes.DRIVE ) ).setAccessType( "online" ).setApprovalPrompt( "auto" ).build( );
System.out.println("xxxxx : " + DriveScopes.DRIVE);
String url = flow.newAuthorizationUrl( ).setRedirectUri( REDIRECT_URI ).build( );
System.out.println( "Please open the following URL in your browser then type the authorization code:" );
System.out.println( " " + url );
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
String code = br.readLine( );
GoogleTokenResponse response = flow.newTokenRequest( code ).setRedirectUri( REDIRECT_URI ).execute( );
GoogleCredential credential = new GoogleCredential( ).setFromTokenResponse( response );
// Create a new authorized API client
Drive service = new Drive.Builder( httpTransport, jsonFactory, credential ).build( );
insertFile(service, "Test File Drive", "This is a test file","myCompanysFolderID" , "text/plain", "./data/document.txt");
}
/**
* Insert new file.
*
* #param service Drive API service instance.
* #param title Title of the file to insert, including the extension.
* #param description Description of the file to insert.
* #param parentId Optional parent folder's ID.
* #param mimeType MIME type of the file to insert.
* #param filename Filename of the file to insert.
* #return Inserted file metadata if successful, {#code null} otherwise.
*/
private static File insertFile(Drive service, String title, String description,
String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
// Set the parent folder.
if (parentId != null && parentId.length() > 0) {
body.setParents(
Arrays.asList(new ParentReference().setId(parentId)));
}
// File's content.
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
// Uncomment the following line to print the File ID.
System.out.println("File ID: " + file.getId());
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
}
I manage to successfully upload the file to the company's folder, but I have to authorize it manually and paste the code each time. So, as I want to make this in an automatic way, I changed the authorization "method" to one that uses a service account p12 key to authorize the client. This is the new code after the change:
package sample;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
public class DriveCommandLine2
{
private static final String KEY_FILE_LOCATION = "data/myp12Key.p12";
**//Note: this is the mail from a service account in my dev console, it is different from the OAuth client I use in the previous method.**
private static final String SERVICE_ACCOUNT_EMAIL ="myServiceAccountEmail#appspot.gserviceaccount.com";
/** Application name. */
private static final String APPLICATION_NAME =
"Drive API Java Quickstart";
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
public static void main( String[] args ) throws Exception
{
//Drive service = getServiceManual();
Drive service = initializeDrive();
//insertFile(service, "Test File Drive", "This is a test file","myCompanyFolderID" , "text/plain", "./data/document.txt");
insertFile(service, "Test File Drive", "This is a test file","" , "text/plain", "./data/document.txt");
}
/**
* Insert new file.
*
* #param service Drive API service instance.
* #param title Title of the file to insert, including the extension.
* #param description Description of the file to insert.
* #param parentId Optional parent folder's ID.
* #param mimeType MIME type of the file to insert.
* #param filename Filename of the file to insert.
* #return Inserted file metadata if successful, {#code null} otherwise.
*/
private static File insertFile(Drive service, String title, String description,
String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
// Set the parent folder.
if (parentId != null && parentId.length() > 0) {
body.setParents(
Arrays.asList(new ParentReference().setId(parentId)));
}
// File's content.
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
// Uncomment the following line to print the File ID.
System.out.println("File ID: " + file.getId());
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
/////////////////////
///NEW GOOGLE ANALYTICS AUTH
public static java.io.File convIs2File(InputStream inputStream, java.io.File file)
{
java.io.OutputStream outputStream = null;
try {
// write the inputStream to a FileOutputStream
outputStream = new java.io.FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
System.out.println("Done!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
// outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
private static Drive initializeDrive() throws Exception {
// Initializes an authorized analytics service object.
// Construct a GoogleCredential object with the service account email
// and p12 file downloaded from the developer console.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
InputStream is = DriveCommandLine2.class.getClassLoader().getResourceAsStream(KEY_FILE_LOCATION);
java.io.File f = java.io.File.createTempFile("myP12Key", ".p12");
java.io.File f_used = convIs2File(is,f);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(f_used)
.setServiceAccountScopes(DriveScopes.all())
.build();
// Construct the Analytics service object.
return new Drive.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}
}
But when I run this code, I get the following error:
An error occured: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
{
"code" : 404,
"errors" : [ {
"domain" : "global",
"location" : "file",
"locationType" : "other",
"message" : "File not found: myCompanyFolderID",
"reason" : "notFound"
} ],
"message" : "File not found: myCompanyFolderID"
}
So, my guess is that in the previous authorization way, I am using my Client_ID and Client_Secrets to authorize my app to insert things into my company's Drive space, so I find myCompanyFolder and I am able to insert the file successfully, however, in the second method, I am trying to insert the file into the service account Drive space that I am not able to access (I know this because when I try to insert it in Drive's root, it works perfectly, however, I am not able to see the file in my root).
So at the end, my question is, is there a way to insert the file into my company's drive folder without doing the manual authorization? That is, how do I authorize my app to upload the file in my company's drive without human interaction?
I think the client_secrets way won't work as I tried it before and it asks me to do it manually the first time I run the code. As I am running my code from a JAR file in a Linux server, this is not practical at all and doesn't work for me.
Thanks!
The 404: File not found means that the user does not have read access to a file or the file does not exist.
Make sure that you provide the correct access_token when making the request for file metadata. Try to regenerate the authorization code, access_token. You need to authorize and authenticate your requests on the behalf of the user, a key and your client ID will not be enough to access user's document.
The documentation suggest to report to users that they do not have read access to the file or that the file does not exist. Tell them that they should ask the owner for permission to the file.

How to take input for a web service in java

I am trying to write a simple web service that must take a number as input and return details corresponding to it.
Here is my code that I have written till now.
package webserviceapp;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
#WebService
public class WebServiceApp {
/**
* #param args the command line arguments
*/
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.100.66.28:3306/dbname";
// Database credentials
static final String USER = "user";
static final String PASS = "pass";
static Map<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
// TODO code application logic here
Connection conn;
Statement stmt;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql = "Select * from table";
ResultSet rs;
rs = stmt.executeQuery(sql);
while(rs.next()){
//do something
}
}catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
#WebMethod(action = "returnDetails")
public static String[] returnDetails(int k) throws notFoundException{
//do the work
//returns String[]
}
private static class notFoundException extends Exception {
public notFoundException(String s) {
System.out.println(s);
System.err.println(s);
}
}
}
I do not know how to take input for the above web service. I have a html page that has a text box and submit button for which I get values through a php code. I want to tunnel this number as input to my web service. Can anyone tell me how can I proceed.
Also, I want the output String[] to be returned to php code so it can be displayed on the html page.
Thanks in advance.
you can pass it in the URL and from the url you can get the values in java
Working off the assumption that you are looking to invoke a RESTful service, there are multiple ways of obtaining input parameters. You can refer to the below article for the ways to achieve this -
http://www.java4s.com/web-services/how-restful-web-services-extract-input-parameters
Code examples for each are available at http://www.java4s.com/web-services/
Another good article you can refer to is - https://vrsbrazil.wordpress.com/2013/08/07/passing-parameters-to-a-restful-web-service/

How to use Java Property File?

I need to use .properties file in Java to store database information.
Here is my database connector class. It's giving NullPointerException. What is the issue with my code ?
Note, that I haven't' assign those property file values. DB connection values are still hard coded.
import java.io.IOException;
import java.io.InputStream;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class Database {
public Connection connection;
private Statement statement;
private Properties property;
public static Database database;
private Database() {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "edus";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
InputStream is = Database.class.getClassLoader().getResourceAsStream(
"config.properties");
property.load(is);
System.out.println(property.getProperty("db_user"));
System.out.println(property.getProperty("db_password"));
System.out.println(property.getProperty("db_name"));
Class.forName(driver).newInstance();
this.connection = (Connection) DriverManager.getConnection(url + dbName,
userName, password);
}catch (IOException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver is missing");
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
public static synchronized Database getDatabaseConnection() {
if (database == null) {
database = new Database();
}
return database;
}
}
config.properties is not lying under classpath. It should be under classes folder.
you can also try
Database.class.getClassLoader().getResourceAsStream(
"com/lk/apiit/eduservice/config.properties");
As Roman C pointed out you also need to initialize Properties Object first
Properties property = new Properties();
You forgot to initialize
Properties property = new Properties();
This is an issue of NullPointerException in your code, because you referenced not initialized variable.
If you open a stream you should close it after it's not used. Do it by adding finally block.
The code where you getting a connection to the database you can move to the corresponding method. If the connection is closed you will not reinitialize the database again just reopen a connection or get a new one.
Dont keep config properties file in a package. Keep it directly inside the source folder, so that the config properties file comes directly in the build/classes folder after the build is done.
The issue is that your config properties in in the folder com/ik/apiit/eduservice folder but your code is expecting it to be directly in the classes folder (the root folder of classpath).
try this
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
prop.load(in);

Read remote file in java which needs username and password

I am trying to read a remote file in java
File f = new File("//192.168.1.120/home/hustler/file.txt");
The remote machine needs a Username and Password to allow me to access the file.
Is there a way I could pass the parameters through the java code and read the file?
package com.eiq;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemOptions;
import org.apache.commons.vfs.Selectors;
import org.apache.commons.vfs.UserAuthenticator;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.auth.StaticUserAuthenticator;
import org.apache.commons.vfs.impl.DefaultFileSystemConfigBuilder;
public class RemoteFileDemo {
public static void main(String[] args) throws IOException {
String domain = "hyd\\all";
String userName = "chiranjeevir";
String password = "Acvsl#jun2013";
String remoteFilePath = "\\\\10.0.15.74\\D$\\Suman\\host.txt";
File f = new File("E:/Suman.txt"); //Takes the default path, else, you can specify the required path
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileObject destn = VFS.getManager().resolveFile(f.getAbsolutePath());
//domain, username, password
UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password);
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile(remoteFilePath, opts);
System.out.println(fo.exists());
//fo.createFile();
destn.copyFrom(fo, Selectors.SELECT_SELF);
destn.close();
//InputStream is = new FileInputStream(f);
}
}
This is a program to read a file from the remote machine and store it in our local machine as file E:/Suman.txt.
Take care while writing the file path means instead of : we have to replace it with $ symbol, e.g.:
D:\Suman\Boorla\kpl.txt is wrong,
D$\\Suman\\Boorla\\kpl.txt is right.
In the above program, you have to change the domain name, username, password and file path of the remote machine.
To work with the above program we need to add the following jar files int the classpath.
commons-vfs.jar
commons-logging.jar
Another alternative with jCIFS you can easily specify authentication parameters:
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain", "user", "password"); // Authentication info here, domain can be null
try (InputStream is = new SmbFile("smb://192.168.1.120/home/hustler/file.txt", auth).getInputStream()) {
// Read from 'is' ...
} catch (IOException e) {
// Handle IOException
}
You can also try Commons VSF . Check UserAuthenticator
Here is the code, I've written and it is working Perfectly.
File f=new File("abc.txt"); //Takes the default path, else, you can specify the required path
if(f.exists())
{
f.delete();
}
f.createNewFile();
FileObject destn = VFS.getManager().resolveFile(f.getAbsolutePath());
UserAuthenticator auth = new StaticUserAuthenticator("", "myusername", "secret_password");
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile("\\\\192.168.0.1\\direcory\\to\\GetData\\sourceFile.txt",opts);
destn.copyFrom(fo,Selectors.SELECT_SELF);
destn.close();
Now you can use the file to perform the required operations. Something like...
InputStream is = new FileInputStream(f);

Categories