Read a file from shared location with access restrictions (java) - java

I have a program that has to read a file from network location - something like this
String sFileSource = "//MyShared/location/fileName.txt" ;
File inputFile = new File(sFileSource);
try {
ffBuffer = new BufferedReader(new FileReader(inputFile));
}
catch (FileNotFoundException e) { // should never happen
}
Now, the problem is that that shared location is on the different network domain and accessible only using domain credentials
How can I embed entering the credentials into this java program ? The problem is that when ran from different PCs it fails due to login.

Reading a file like that is not a secure way to do it, because you will expose your user domain credentiels.
Reversing the java app could lead to that, so it's better to use an ftp server for that.
The way I have done it before:
Read remote file in java which needs username and password

Related

FileWriter to write to user desktop in Java, rather than server desktop

As part of a search application, I want the user to be able to download a report showing the results in a CSV file. I have the following method:
public void downloadCustomerResults(String customer) {
String output = "";
output += produceCustomerID(customer);
output += produceCustomerAddress(customer);
output += produceCustomerContactDetails(customer);
output += produceOrderHeader(customer);
output += producePayments(customer);
// Writes to server desktop, not user desktop.
try {
Writer fileWriter = new FileWriter("C:\\Users\\username\\Desktop\\SAR" + customer + "C.csv");
fileWriter.write(output);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This downloads the file to the desktop of the machine running the server, not the user's desktop (accessing the app via JSP's on Tomcat). How would I change the file path string to make this download to the users' desktop? Or would I have to pass the file to the JSP for the user to download via their browser?
Thanks.
Short answer: The server has no means of accessing the client's filesystem.
Longer answer: You might either provide a service for the client to download the file (e.g. a webservice accessible through a URI, like #Kayaman mentioned) or the client provides you a service to write the file (e.g. a remote file system, an FTP server etc.). For the latter there might be libraries providing a special java.nio.FileSystem extension.
You may also provide an application running on the client to receive the file. This client application will then have acces to the client's file systems (unless it lacks the access rights, of course).
So the answer I found was to use the JavaScript package FileSaver.js.
This accepts a blob created from a string, and then saves it with a filename of your choice to the browsers preferred download folder.
I managed to pass the string from Java to JavaScript, and then pass it through FileSaver.js in the .JSP page.

How to use input from a java code and transfer it into an external application (as well as retrieving output)?

I'm actually not that great and am relatively new at Java. I wish to receive input from the user, and want to input this data into an external application.
This application processes the data and provides an output. I wish to retrieve this output using the Java code.
I have attempted in doing this but, I haven't got the slightest idea on how to start this script.
Nothin' on the internet seems to answer this question. If you have any idea or any new functions that can be useful, please help me in doing so.
Since I'm starting from ground zero, any help is appreciated.
Thanks so much.
To communicate with an external application you need to first define the communication way. For example:
Will this application read the output from a file?
If that statement it's true, then you need to learn serialization:
Will this application read the input from the standard output (like a command-line application)
If that statement it's true then you need to send with System.out.print().
Will this application get the data over HTTP.
Then you need to learn about REST and or RPC architectures.
Assuming that it will be a command-line application, then you could use something like this:
public class App
{
public static void main(String... args)
{
// You need to implement your business logic here. Not just print whatever the user passes as arguments of the command-line.
for(String arg : args)
{
System.out.print(arg);
}
}
}
There's a lot going on here but I'll suggest an example for each part of this question and assume this is just going to be written in Java, and suggesting an iterative design/development approach.
receive input from the user::getting arguments from the command line can work, but I think most users want to use familiar user interfaces like excel to input large amounts of data. Have them export files to .csv or look into reading excel files directly with apache poi. The latter is not for beginners, but not terrible to figure out or find examples. The former should be easy to figure out if you look into reading files and splitting them line by line on the delimiter. Here's an example of that:
try (BufferedReader reader = new BufferedReader(new FileReader(new File("user_input.csv"))) {
String currentLine = reader.readLine();
while (currentLine != null) {
String splitLine[] = currentLine.split(","); //choose delimiter here
//process cells as needed
//write output somewhere so other program can read it later
currentLine = reader.readLine();
}
}
catch (IOException ex) {
System.out.println(ex.getMessage()); //maybe write to an error log
System.exit(1);
}
"input" data to other app::you can use pipes if you're at the command line. but I'd recommend you write to a file and have the other app read it. here's an expansion of the previous code snippet showing how to write to a file as that might be more practical and easier to log/archive/debug.
try (BufferedReader reader = new BufferedReader(new FileReader(new File("user_input.csv")));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("process_me.csv")))) {
String currentLine = reader.readLine();
while (currentLine != null) {
String splitLine[] = currentLine.split(","); //choose delimiter here
//process cells as needed
writer.write(processed_stuff);
currentLine = reader.readLine();
}
}
catch (IOException ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
Then retrieving output::can just be reading another file with another Java program. This way you're communicating between programs using the file system. You must agree upon file formats and directories though. And you'll be limited to having both programs on the same server.
To make this at scale, you could use web services assuming the other program you're making requests to is a web service or has one wrapped around it. You can send your file and receive some response using URLConnection. This is where things will get much more complex, but now everything in your new program is just one Java program and the other code can live on another server.
Building the app first with those "intermediate" files between the user input code, the external code, and the final code will help you focus on perfecting the business logic, then you can worry about just communication over the network.

create client side file using java

i am trying to create a project which create a file in client side . i ave done the coding to create a file .but it obviously will be created in server side.. can any one help to do this. below is the code i have done..
File file = new File("d:/file.txt");
try {
String content = "This is the content to write into file";
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
I have also tried to create a file using filesysapi, which is done using HTML and javascript. but i got "Error: SECURITY_ERR"
Despite what everyone is saying, you can create a client-side file via javascript. It's a sandboxed portion of the File System, done via HTML5's FileSystem API.
HOWEVER, my guess is your SECURITY_ERR is probably because you are opening an html page with the target javascript via File://PATH_TO_HTML_PAGE in your browser. The File-System API Will not work unless your grabbing the html/javascript/css from a server (like locahost:8080/test.html - Netbeans has some options to run a glassfish/server instance pretty painlessly locally on your machine if you have no experience with servers.).
Update 1-31-2014
Found this in an article on the File-System API, which confirmed the above paragraph for me:
You may need the --allow-file-access-from-files flag if you're debugging your app from file://. Not using these flags will result in a SECURITY_ERR or QUOTA_EXCEEDED_ERR FileError.
end update
That said, in the previous comment on a different question you asked and I answered, you were using TEMPORARY Storage. I use PERSISTENT because it is more reliable, and the browser displays a message asking for permission to store the data locally on the target machine. Here is how I have been making files locally on client machines for persistent data storage for the past couple years. This to the best of my knowledge only works with a handful of browser's, I use Google Chrome - the following defeinitely works in Google Chrome.
The following is javascript and needs to be within either an external script or script tags.
//this is a callback function that gets passed to your request for the file-System.
var onInitFs = function(fileSys){
//fileSystem is a global variable
fileSystem = fileSys;
//once you have access to the fileSystem api, then you can create a file locally
makeAFile();
makeAndWriteContent();
};
var errorHandler = function(e){console.log('Error', e);};
//request 1 GB memory in a quota request
//note the internal callback `function(grantedBytes){...}` which makes the actual
//request for the Filesystem, on success `onInitFs` is called.
///on error the `errorHandler` is called
navigator.webkitPersistentStorage.requestQuota(1024*1024*1024*1, function(grantedBytes) {
window.webkitRequestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
}, errorHandler);
//this method will only work once the fileSystem variable has been initialized
function makeAFile(){
var callbackFunctionOnSuccess = function(){console.log("created new file")}
fileSystem.root.getFile("test.txt", {
create: true
}, callbackFunctionOnSuccess, function(error){console.log(error);});
}
function makeAndWriteContent(){
//this is going to be passed as a callback function, to be executed after
//contents are written to the test2.txt file.
var readFile = function(){
fileSystem.root.getFile("test2.txt", {create: false}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log(this.result);
};
reader.readAsText(file);
}, function(error){console.log(error);});
}, function(error){console.log(error);});
}
fileSystem.root.getFile("test2.txt", {
create: true
}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(e) {
writer.onwriteend = function(e){
//now, we will read back what we wrote.
readFile();
}
writer.onerror = function(e3){console.log(e3);
}
var blob = new Blob(["Hello World"]);
writer.write(blob);
};
writer.onerror = function(e3) {console.log(e3);};
//make sure our target file is empty before writing to it.
writer.truncate(0);
}, errorHandler);
}, errorHandler);
}
One thing to keep in mind is that the File-System API is asynchronous so you have to get use to using callback functions. If you try to access the File-System API before it's instantiated, or if you try to access files before they are ready, you will also get errors. Callback functions are essential.
using socket programming, 1st create a communication between server and client machines.
Socket kkSocket = new Socket(hostName, portNumber)
then use File file = new File("hostname#d:/file.txt");
if your host file does not contain hostname IP address maping, then instead of giving hostname, use IP address.
You can not create file on client side because browser does not allow doing that.

Java read/write text file on a website

Basically I've uploaded a text file to my host and I want to edit the file and read it with java. I've created the permissions for it but im not sure how to do it with Java. This is my code which read/writes locally:
Read:
BufferedReader mainChat = new BufferedReader(new FileReader("./messages/messages.txt"));
String str;
while ((str = mainChat.readLine()) != null)
{
System.out.println(decrypt.Decrypt(str, salt));
}
mainChat.close();
Write:
FileWriter chatBuffer = new FileWriter("./messages/messages.txt",true);
BufferedWriter mainChat = new BufferedWriter(chatBuffer);
mainChat.write(message);
mainChat.newLine();
mainChat.flush();
mainChat.close();
How would I have to modify this to make it work? Thanks
I don't think you can read/write directly to a file on a web server the way you would on a local filesystem. What you'll probably need to do is:
download the file
open it in the local editor
when it's saved, automatically re-upload the file
You can do this all within the editor, and hide this in the app by having it do the download-edit-save-upload in the background. Many text editors will do this by establishing a remote connection similarly, and making the file writing round trip transparent to user.
You should implement some sort of remote procedure call. Basically, from the client send the server a message containing what you'd like to put in the file. Then have the server actually open the file and write the content of the message to the file.

FTPing a file to Mainframe using Java, Apache Common Net

I'm am trying to upload a file into mainframe server using FTP. My code is below
FTPClient client = new FTPClient();
InputStream in = null;
FileInputStream fis = null;
try {
client.connect("10.10.23.23");
client.login("user1", "pass123");
client.setFileType(FTPClient.BINARY_FILE_TYPE);
int reply ;
reply = client.getReplyCode();
System.out.println("Reply Code:"+reply);
if(FTPReply.isPositiveCompletion(reply)){
System.out.println("Positive reply");
String filename ="D:\\FILE.txt";
in = new FileInputStream(filename);
client.storeFile("FILE.TXT", in);
client.logout();
fis.close();
} else {
System.out.println("Negative reply");
}
} catch(final Throwable t){
t.printStackTrace();
}
The code gets struck in client.storeFile("FILE.TXT", in);
I am unable to debug. Please suggest ways / solutions.
First there is what Lukas said fis is null, but I have a bunch of other questions. What is FTPClient? It is not sun.net.ftp.FtpClient as that class has no store() method. Other things to consider is logging into the mainframe, where I work you can't just grab files off the mainframe without first logging in. There can be more things to consider but lets start there.
You don't appear to be changing to a specific directory before uploading the file. There are two ways of changing directories on the Mainframe. If you need to upload to a PDS you would execute a command like the following from with in the windows ftp client.
cd USERID.DATASET.PREFIX
If you need to upload a file to the USS subsystem you would execute a command like the following.
cd '/direone/dirtwo'
Have you checked that user1 has access permissions to ftp? It is possible to grant those on a very granular level so that you can list files and submit jobs, but not put files.
The fact that it dies right after your SEND seems like that might be a good candidate. I would call your RACF / ACF2 / Whatever-security-product person you have and ask them.
first remove the file extension from the file name
enclose the resultant file name after trimming within single quotes
now put the above string as the first parameter of storeFile() method

Categories