I want to read property file on Server side. I have DBConfig.java, useDBConfig.java and DBConfig.properties all placed in server package. I can't read the values from property file on Server Side. Your help is highly appreciated.
public interface DBConfig extends Constants {
#DefaultStringValue("host")
String host(String host);
#DefaultStringValue("port")
String port(String port);
#DefaultStringValue("username")
String username(String username);
#DefaultStringValue("password")
String password(String password);
}
public void useDBConfig() {
DBConfig constants = GWT.create(DBConfig.class);
Window.alert(constants.host());
host = constants.host(host);
port = constants.port(port);
username = constants.username(username);
password = constants.password(password);
}
property file...
host=127.0.0.1
port=3306
username=root
password=root
Thanks in advance.
GWT.Create can be used only in client mode.
Are you sure that code execute in server side?
If i write in my application GWT.Create in server side i get this error:
java.lang.UnsupportedOperationException: ERROR: GWT.create() is only usable in client code! It cannot be called, for example, from server code. If you are running a unit test, check that your test case extends GWTTestCase and that GWT.create() is not called from within an initializer or constructor.
You can read a properties files in java. The file is similar that Constants files in GWT.
Example of Properties file:
key = value
host = 127.0.0.1
port = 80
username = guest
password = guest
EOF
You can read this file, see the next code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
String fileToRead = "MY_PATH"+File.separator+"MY_FILE.properties";
Properties prop = new Properties();
try {
File propertiesFile = new File(fileToRead);
prop.load(new FileInputStream(propertiesFile));
String host = prop.getProperty("host");
String port = prop.getProperty("port");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(host);
System.out.println(port);
System.out.println(username);
System.out.println(password);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If the key doesnt exists getProperty(String key) return null.
You can use prop.containsKey(String key); to see if the key exists. This function return a boolean (True if exists False in other case).
Greetings
Related
I'm making a script to turn on and off my lights using email and EVERYTHING works besides the fact that it won't update to the newest email and I don't know why. I couldn't find anything online, and I didn't try anything because I'm completely lost. BTW for more info the first time the script runs it runs the newest email but it doesn't do it again after that
This is my code please help
to my understanding the way the while loop should work is get a subject, then check to see if it matches what im asking it to look for then weather it is or isnt it goes about to the top and checks the most recent subject again then checing if its what im looking for then doing it again and again and again
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class GetEmails {
public static void on(){
SSH on = new SSH();
on.command = "python3 on.py";
on.run();
}
public static void off(){
SSH off = new SSH();
off.command = "python3 off.py";
off.run();
}
public static void check(String host, String storeType, String user,
String password)
{
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array
Message[] messages = emailFolder.getMessages();
boolean power = true;
while(true){
int i = messages.length - 1;
Message message = messages[i];
String subject = message.getSubject();
// System.out.println(subject);
if(subject.equals("+myRoom") & power == false){
on();
power = true;
System.out.println("Light on");
}
else if (subject.equals("-myRoom") & power == true){
off();
power = false;
System.out.println("Light Off");
}
else{
continue;
}
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "EMAIL#gmail.com";// change accordingly
String password = "PASSWORD";// change accordingly
check(host, mailStoreType, username, password);
}
}
The problem is that you only call getMessages() before the while loop and then continuously check the same set of downloaded messages over and over again in the while-loop.
You need to change the while-loop to download the latest (set of) messages.
I would also point out that your code does not account for the possibility of receiving non-command messages that might push the latest command message into the "not the latest" slot (e.g. latest command message might have index messages.length - 2 while the non-command message has the messages.length - 1 index) nor does it account for the possibility of getting disconnected due to network outages or the server dropping your connection (which happens all the time for any number of reasons).
This is a followup of this question. The correct answer leads to an attempt to use the SFTPClient class in the Apache Commons library.
I can connect. The next step is to upload a file. There is a lot of reference material with sample source code. I used this one as my guide. It's not secure FTP, but it's simple to follow. This is the java code I was attempting to emulate:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPUploadFileDemo {
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// This was considered unnecessary because I was sending n ASCII file
// APPROACH #1: uploads first file using an InputStream
File firstLocalFile = new File("D:/Test/Projects.zip");
String firstRemoteFile = "Projects.zip";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
and some more code that's not relevent,
This is my ColdFusion equivalent:
localFilename = "d:\dw\dwtest\dan\textfiles\randomText.txt";
remoteFileName = "randomText.txt";
javaFtpClient = CreateObject("java",
"org.apache.commons.net.ftp.FTPSClient").init("SSL", JavaCast("boolean",true));
// note that I am using a secure client
javaInputFile = createObject("java", "java.io.File").init(localFilename);
javaInputStream = createObject("java", "java.io.FileInputStream").init(javaInputFile);
// connect and login
javaFtpClient.connect(JavaCast("string","something"),990);
loginStatus = javaFtpClient.login('valid username','valid password');
writeoutput("login status " & loginStatus & "<br>");
javaFtpClient.enterLocalPassiveMode();
uploadStatus = javaFtpClient.storeFile(remoteFileName, javaInputStream);
writeOutput("upload status " & uploadStatus & "<br>"); javaInputStream.close();
// logout and disconnect
javaFtpClient.logout();
javaFtpClient.disconnect();
writeoutput("done" & "<br>");
The output shows a successful login and an unsuccessful file upload. The lack of file was confirmed using FileZilla.
Can anybody see why the file was not uploaded?
The command javaFtpClient.execProt("P") is required. Setting PROT to "P" sets the Data Channel Protection Level to private.
I'm trying to use the printWorkingDirectory() from Apache Commons FTP but it's only returning null. I can't navigate directories, list files, etc.
Log in pass all is success but how ever I try I can not change current directory.
I use this following code:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FTPDownloadFileDemo {
public static void main(String[] args) {
String server = "FTP server Address";
int port = portNo;
String user = "User Name";
String pass = "Pasword";
FTPClient ftpClient = new FTPClient();
String dir = "stocks/";
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
System.out.println( ftpClient.printWorkingDirectory());//Always null
//change current directory
ftpClient.changeWorkingDirectory(dir);
boolean success = ftpClient.changeWorkingDirectory(dir);
// showServerReply(ftpClient);
if (success)// never success
System.out.println("Successfully changed working directory.");
System.out.println(ftpClient.printWorkingDirectory());// Always null
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This is rather old question that deserves an answer. This issue is likely a result of using FTPClient when secure connection is required. You may have to switch to FTPSClient if that is, indeed, the case. Further, output the response from the server with the following code snippet to troubleshoot the issue if secure client doesn't solve the it:
ftpClient.addProtocolCommandListener(
new PrintCommandListener(
new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")), true));
Also, a server can reject your login attempt if your IP address is not white listed. So, being able to see the logs is imperative. The reason you see null when printing current working directory is because you are not logged in. Login method will not throw an exception but rather return a boolean value indicating if the operation succeeded. You are checking for success when changing a directory but not doing so when logging in.
boolean success = ftpClient.login(user, pass);
I faced the same, but I came across with a simple step.
Just added this.
boolean success = ftpClient.changeWorkingDirectory(dir);
ftpClient.printWorkingDirectory(); //add this line after changing the working directory
System.out.println(ftpClient.printWorkingDirectory()); //wont be getting null
Here I have the code and the console output
FTPClient.changeWorkingDirectory - Unknown parser type: "/Path" is current directory
I know I replied too soon ;-P, but I saw this post recently. Hope this helps to future searchers ;-)
I am trying to download a file from a server. The server has a guest account without a login or password.
The code was adapted from http://www.dreamincode.net/forums/topic/32031-ftp-in-java-using-apache-commons-net. The reply code is 220, which means "Service ready for new user", but the size of the downloaded file is 0 Bytes. The size of the file on the server is 845 Bytes.
Thank you for your time.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpTest {
public static FTPClient ftp = new FTPClient();
public static void main(String []args) throws IOException{
String ftpStr = "ftp.ncbi.nih.gov";
String path = "ftp.ncbi.nih.gov/genomes/MapView/Mus_musculus/non_sequence/README";
try {
ftp.connect(ftpStr);
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
int reply = ftp.getReplyCode();
System.out.println(reply); //Output: 220
System.out.println("Connected");
File file = new File("README");
FileOutputStream dfile = new FileOutputStream(file);
ftp.retrieveFile(path,dfile);
ftp.disconnect();
System.out.println("Finished");
}
}
To access an FTP server with a guest account (without username or password), you should use the username anonymous with an empty password.
I know this is two years late, but I had the same issue. The variable remote in: public boolean retrieveFile(String remote, OutputStream local) throws IOException
expects a file name, not the the full address to the file. So you should pass "README" instead of path. Before doing that, you should change the working directory of your ftp client to "genomes/MapView/Mus_musculus/non_sequence"
Using this code:
import java.io.*;
import java.util.*;
import javax.mail.*;
public class Mbox {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", "mstor");
properties.setProperty("mstor.mbox.metadataStrategy", "none");
properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
properties.setProperty("mstor.cache.disabled", "true");
properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
properties.setProperty("mstor.metadata", "disabled");
Session session = Session.getDefaultInstance(properties);
try {
Store store = session.getStore(new URLName("mstor:C:/INBOX"));
store.connect();
Folder inbox = store.getDefaultFolder().getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message m = inbox.getMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to setup an mbox reading program in java. I have tried both on Linux and Windows but every time I get the exception javax.mail.NoSuchProviderException: No provider for mstor on session.getStore("mstor:C:/INBOX"). I searched for a while and made the properties file as shown above but still the error persited.
javax.mail.NoSuchProviderException: No provider for mstor
at javax.mail.Session.getProvider(Session.java:473)
at javax.mail.Session.getStore(Session.java:547)
at Mbox.main(Mbox.java:23)
What am I doing wrong?