Create folder in a relative path outside the project - java

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"

Related

System.getProperty("mode") returns "null"

We recently had to set up one of the tomcat servers from scratch. Tomcat version is 8.0.20. Deploying a war file, now System.getProperty("mode") returns "null" where it should return PREPROD.
It should read this "mode" from a mode.properties file which is located in the webapps directory. The two lines commented out show another part of code that does not work anymore on the new tomcat server. I replaced it with code that should work.
//String pathOfWebInf = sce.getServletContext().getRealPath("WEB-INF");
//String pathOfLocalhostFile = pathOfWebInf + File.separator + "classes"
// + File.separator;
String pathOfLocalhostFile = this.getClass().getResource("/").getPath();
String mode = System.getProperty("mode");
String fileName = "localhost-oracle.properties." + mode;
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("xxx");
Properties dbProps = new EncryptableProperties(encryptor);
try
{
InputStream is = new FileInputStream(pathOfLocalhostFile + fileName);
dbProps.load(is);
} catch (Exception e)
{
throw new IOException("Could not read properties file " + pathOfLocalhostFile + fileName);
}
System.properties is related to all properties in the Computer where the JVM is running... there is no mode key defined there, that is why you get null as value....
check out all the properties in the pc by doing:
final Properties props = System.getProperties();
props.list(System.out);
and verify yourself, there is no mode key in that map...
You have to load mode.properties first, like this way
private Properties mode=null;
mode = new Properties();
mode.load(new FileInputStream(pathtoMODE));
String mode = mode.getProperty("mode");

replace domainName with folder path using java

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

Using Apache Commons VFS- SFTP, uploading to a server

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.

How to check if a particular folder or file is shared or not with java program?

I am working on a java networking project. One of my module need to know if a particular folder or file is shared or not and if shared to whom it is shared. I mean whether it is shared with everyone on network or it is shared with some specific people only as we have option in windows. This also must be an attribute of file but I can't find any way to check this one.
You can use file's exists method to determine if the directory is sharing folder.
Try this:
public static void main(String[] args) throws UnknownHostException {
InetAddress addr;
addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
if (hostname != null) {
File f = new File("\\\\" + hostname + "\\temp");
if (f.exists()) {
System.out.println("directory temp is shared");
}
}
}

How to load files on multiple platforms properly using Java? [duplicate]

This question already has answers here:
Platform independent paths in Java
(8 answers)
Closed 3 years ago.
I have a java swing database application which needs to be run on Windows and Linux. My database connection details are stored in a XML file and I load them.
This application can load this properties on Linux properly but it is not working on Windows.
How do I load files on multiple platforms properly using Java?
This is the code:
PropertyHandler propertyWriter = new PropertyHandler();
List keys = new ArrayList();
keys.add("ip");
keys.add("database");
Map localProps = propertyWriter.read(keys, "conf" + File.separatorChar + "properties.xml", true);//if false load from the local properties
//get properties from the xml in the internal package
List seKeys = new ArrayList();
seKeys.add("driver");
seKeys.add("username");
seKeys.add("password");
Map seProps = propertyWriter.read(seKeys, "conf" + File.separatorChar + "properties.xml", true);
String dsn = "jdbc:mysql://" + (String) localProps.get("ip") + ":3306/" + (String) localProps.get("database");
jDBCConnectionPool = new JDBCConnectionPool((String) seProps.get("driver"), dsn, (String) seProps.get("username"), (String) seProps.get("password"));
File reader method:
public Map read(List properties, String path, boolean isConfFromClassPath)
{
Properties prop = new Properties();
Map props = new HashMap();
try {
if (isConfFromClassPath) {
InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
prop.loadFromXML(in);
for (Iterator i = properties.iterator(); i.hasNext();) {
String key = (String) i.next();
props.put(key, prop.getProperty(key));
}
in.close();
} else {
FileInputStream in = new FileInputStream(path);
prop.loadFromXML(in);
for (Iterator i = properties.iterator(); i.hasNext();) {
String key = (String) i.next();
props.put(key, prop.getProperty(key));
}
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return props;
}
If the file is in a jar file and accessed by the classpath then you should always use /.
The JavaDocs for the ClassLoader.getResource say that "The name of a resource is a '/'-separated path name that identifies the resource."
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)
I'm not sure if there is the proper way, but one way is:
File confDir = new File("conf");
File propFile = new File(confDir, "properties.xml");
But in a scenario as simple as yours, I would just use /
If it's a resource located in classpath, we can load it with following snippet:
getClass().getClassLoader().getResourceAsStream(
"/META-INF/SqlQueryFile.sql")));
You can load all files on multiple platforms without any trouble.
Kindly use Matcher.quoteReplacement(File.separator) for replacing the slash.
It will works for every platform.
String fileLocation = "/src/service/files";
fileLocation = fileLocation.replaceAll("/",Matcher.quoteReplacement(File.separator));
assuming that your file is in conf/properties.xml on Linux and conf\properties.xml on Windows,
use File.pathSeparator instead of File.separator

Categories

Resources