I use derby embedded in a desktop app. But when there is a space in the database path (in any level of directories) the derby driver fails to connect to the database.
Regards, :)
update
public static final String connectionUrl = "jdbc:derby:[path]database;user=app;password=pass;";
String path = Utils.getPathOfJar();
String dbPath = connectionUrl.replace("[path]", path);
dbConnection = DriverManager.getConnection(dbPath);
First of all this problem only occurs in Linux.
The path to the database should be set in the system properties like this:
derby.system.home
like this:
String path = Utils.getPathOfJar();
path = path.jarFilePath.replaceAll("%20", "\\ ");
System.setProperty("derby.system.home", path);
public static final String connectionUrl = "jdbc:derby:database;user=app;password=pass;";
dbConnection = DriverManager.getConnection(connectionUrl);
Related
So I am working in a team of people on a small school project, and we're developing java/jsp web app with apache.. I created simple properties.config file so I can store values and use them later and it looks something like this:
home_url = http://localhost:8080/to3/
to3_path = C:/Users/User2/Documents/workspace/TO-3
db_url = jdbc:mysql://localhost:3306/to3?useUnicode=true&characterEncoding=UTF-8
Problem I have is when I commit it and someone do a checkout they have to change values for url-s and paths so it fits their machine.. I heard I can make a custom properties file which will override these default values if it recognizes certain machine, but I don't know how to do it.
Thank you all in advance for your help.
Don't commit project settings. Put them in .gitignore and commit a copy of it (e.g. properties.config.sample). Make sure to keep it up to date with any new keys you add, but each developer should make their own untracked copy.
As Amadan point out you should not commit project properties. My suggestion is to create a file with .properties extension and place your properties inside. To use this file in java you can create a class like that
public class MyProperties{
private String homeUrl = "";
private String to3Path = "";
private String dbPath = "";
private final String configPath = System.getProperty("user.home") + File.separator + "my-props.properties";
public void loadProperties(){
try {
Properties prop = new Properties();
InputStream input = null;
File filePath = new File(configPath);
input = new FileInputStream(filePath);
// load a properties file
prop.load(input);
homeUrl = prop.getProperty("home_url");
to3Path = prop.getPropert("to3_path");
dbPath = prop.getProperty("db_url");
}catch (Exception e) {
e.printStackTrace();
}
}
// getters & setters
}
Then in your app you can do
MyProperties props = new MyProperties();
props.loadProperties();
String homeUrl = props.getHomeUrl();
System.getProperty("user.home") will give home path depending on the OS.
For example in windows this is path is C:\Users\yourName
This way all your co-workers can place their own properties in their personal pc inside their home path and you will be able to work without conflicts.
I am trying to replace apache image path to linux ubuntu folder path while retrieving file path from DB.
http://test.mydomain.com/MainFolder/subFolder/image1.jpg
should be
/var/www/MainFolder/subFolder/image1.jpg
here MainFolder is static folder. so how can i replace "http://test.mydomain.com/" to "/var/www/" where before MainFolder/
You can get domain part of url and replace that part of string like below way..
String imageURL = "http://test.mydomain.com/MainFolder/subFolder/image1.jpg";
String domainPart = getDomainPart(imageURL);
String folderPath = imageURL.replace(domainPart, "/var/www");
public String getDomainPart(String url) {
URI uri = new URI(url);
String scheme = uri.getScheme();
String hostname = uri.getHost();
String domainPart = scheme + "://" + hostname;
return domainPart;
}
How can i save a file to a relative path outside my project ? So i can create a folder of resources on any computer the program runs on?
I tried:
String folderPath=getClass().getClassLoader().getResource(".").getPath()+other stuff
to create a folder path where i save images. It creates a me a folder like tomcat%20v7.0 where indeed my images are saved. I keep absolute path for every picture in my database and then load them in a jsp file. When running the app in eclipse, everything works fine. When trying to run in browser, photos aren't shown.
Browser are installed on C: and tomcat/eclipse on E:
public static List<String> getEndPoints() throws
MalformedObjectNameException,
NullPointerException, UnknownHostException,
AttributeNotFoundException, InstanceNotFoundException,
MBeanException, ReflectionException {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objs = mbs.queryNames(new ObjectName(
"*:type=Connector,*"), Query.match(Query.attr("protocol"),
Query.value("HTTP/1.1")));
String hostname = InetAddress.getLocalHost().getHostName();
InetAddress[] addresses = InetAddress.getAllByName(hostname);
ArrayList<String> endPoints = new ArrayList<String>();
for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
ObjectName obj = i.next();
String scheme = mbs.getAttribute(obj, "scheme").toString();
String port = obj.getKeyProperty("port");
for (InetAddress addr : addresses) {
String host = addr.getHostAddress();
String ep = scheme + "://" + host + ":" + port;
endPoints.add(ep);
}
}
return endPoints;
}
//use above code to get path like "http://yourip:yourport/yourwebapppath"
I'm attempting to use Apache Commons VFS to SFTP a file onto a server, but I keep getting the following error:
java.lang.RuntimeException: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "sftp://user:***#xxx.x.xxx.xxx/".
Is it normal for it to not include the remote file path (remoteFilePath) here? It's in my code to include it in the connection string (see below)
I have the following jars included in my pom:
commons-logging-1.1.3.jar
commons-vfs2-2.0.jar
hamcrest-core-1.3.jar
jsch-0.1.50.jar
Code:
public void SftpMethod(String strMsg, String tableName){
String host = "xxx.x.xxx.xxx";
String user = "user";
String pass = "password!";
String localFilePath = "C:\\Users\\exampleDir\\Desktop\\loc.dat";
String remoteFilePath = "/dir/home/user/export/loc.dat";
StandardFileSystemManager manager = new StandardFileSystemManager();
File file = new File(localFilePath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");
try{
manager.init();
// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(
createConnectionString(host, user, pass, remoteFilePath),
createDefaultOptions());
// Copy local file to SFTP server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("File upload success");
}catch(IOException e){
throw new RuntimeException(e);
}finally{
manager.close();
}
}
public static String createConnectionString(String hostName, String username, String password, String remoteFilePath) {
return "sftp://" + username + ":" + password + "#" + hostName + "/" + remoteFilePath;
}
public static FileSystemOptions createDefaultOptions() throws FileSystemException {
// Create SFTP options
FileSystemOptions opts = new FileSystemOptions();
// SSH Key checking
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
/*
* Using the following line will cause VFS to choose File System's Root
* as VFS's root. If I wanted to use User's home as VFS's root then set
* 2nd method parameter to "true"
*/
// Root directory set to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
// Timeout is count by Milliseconds
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
return opts;
}
Without the full stack trace its hard to give a conclusive answer, but this is what I saw recently:
Caused by: org.apache.commons.vfs2.FileSystemException: Could not load private key from "/Users/<user>/.ssh/id_rsa".
at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:131)
Unfortunately, I wasn't trying to use a public/private key. I was only intending to log in with a username/password. I needed a way for it to stop trying to read my private key.
The root cause was that the code was using a default location for my key, and attempting to read it (even though thats not what I wanted).
So the workaround was to override the default location by setting the following property:
System.setProperty("vfs.sftp.sshdir", "/");
This bypassed the attempt to read the ssh key altogether, and successfully connected.
I am creating a website with jsp&servlet
and I want to ask :
What's the best way to store an image in a database (mysql) and retrieve it
to using it as profile's picture
And how can i do that?
Thanks you all in advance.
Two common solutions :
directly in the database in a byte field
on the disk, with the path stored in database (I personnaly like to use as name the SHA1 of the file, so I cannot have two times the same file, with the path being a/b/cdef if the SHA1 is abcdef)
Both solutions work very well. The first solution has for advantage to have only one file to backup, to enable rollback, and so on. The second may be more natural as a disk file system is made to store files.
save image in a folder on the server.
save image path in db .
at the time of display get the image path from db and retrieve image.
Store image in database.
import java.sql.*;
import java.io.*;
public class insertImage{
public static void main(String[] args) {
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";;
String dbName = "databasename";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("images.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre = con.prepareStatement("insert into Tablename values(?)");
pre.setBinaryStream(3,fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Inserting Successfully!");
pre.close();
con.close();
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
Retrieve image from database using Servlet
http://www.roseindia.net/servlets/retreiveimage.shtml