File sending Via Java - java

My code is:
public class RemotePlay {
static final String USER_NAME = "bwisniewski";
static final String PASSWORD = "xxx";
static final String NETWORK_FOLDER = "smb://192.168.1.141/ADMIN$/";
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
String fileContent = "This is a test File";
new RemotePlay().copyFiles(fileContent, "testFile1.txt");
}
public boolean copyFiles(String fileContent, String fileName) {
boolean successful = false;
try{
String user = USER_NAME + ":" + PASSWORD;
System.out.println("User: "+user);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = NETWORK_FOLDER + fileName;
System.out.println("Path: "+path);
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
sfos.write(fileContent.getBytes());
successful = true;
System.out.println("Successful "+successful);
}
catch(Exception e) {
successful = false;
e.printStackTrace();
}
return successful;
}}
How can I change it to send exe file to ADMIN$ share. I prefer to use this method because I have to authenticate to remote pc. If you got better ideas to copy file to ADMIN$ share I am looking forward to hear about it.
Thanks.

sfos.write(fileContent.getBytes());
if your data is text, then why not to use PrintWriter to write down your file
public static void main(String [] args) throws Exception { // temporary
File fileOne = new File("testfile1.txt");
PrintWriter writer = new PrintWriter(fileOne);
// write down data
writer.println("This is a test File");
// free resources
writer.flush();
writer.close();
}
and about the extension, you can use any extension you want while creating the file, it will still hold the data, and can be opened if you renamed it to the correct extension on the hard drive
if you named your file testfile.exe it will still hold your data, but when you double click it it wont work until you rename it to testfile.txt (or it will work if the extension is compatible with the data in the file)

Related

Error with CognitiveJ/ExampleCode

I would like to use CognitiveJ (GitHub from CognitiveJ) but all I get is:
Status:401; Body: {"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}
Here is the Code:
public static String lic1 = "xxx";
public static String lic2 = "xxx";
public static void main(String[] args) throws IOException {
new Bildkontrolle();
}
public Bildkontrolle() throws IOException {
File imageFile = new File("E:\\DSC00306.jpg");
new FaceRecognicion(lic1, lic2, imageFile);
}
And here the second class:
public FaceRecognicion(String lic1, String lic2, File imageFile) throws IOException {
BufferedImage bufImage = ImageIO.read(imageFile);
InputStream inpStream = new FileInputStream(imageFile);
FaceScenarios faceScenarios = new FaceScenarios(lic1,
lic1);
ImageOverlayBuilder imageOverlayBuilder = ImageOverlayBuilder.builder(bufImage);
imageOverlayBuilder.outlineFacesOnImage(faceScenarios.findFaces(inpStream), RectangleType.FULL,
CognitiveJColourPalette.STRAWBERRY).launchViewer();
}
Does anyone have an examplecode where I can look up how to use the API.
I stuck at the point where to send the Request.

Adding a String to a file name and still be able to use it

I have a xml file that I'm getting its full path, and pass it to a function where I add a String to its name. However I'm not being able to use it (the initial fullpath) after adding the string. How can it be done, that after getting the fullpath in search(String dirName), and adding the string in lk(String fullpath), I can still use the path which is returned by search(String dirName).
public String search( String dirName)throws Exception{
String fullPath = null;
File dir = new File(dirName);
if ( dir.isDirectory() )
{
String[] list = dir.list(new FilenameFilter()
{
#Override
public boolean accept(File f, String s )
{
return s.endsWith(".xml");
}
});
if ( list.length > 0 )
{
fullPath = dirName+list[0];
lockFile(fullPath);
return fullPath;
}
}
return "";
}
public void lk( String fullPath) throws Exception {
File f = new File(fullPath);
String fileNameWithExt = f.getName();
try {
File newfile =new File(fileNameWithExt+".lock");
if(f.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
try this
File originalFile = new File(<file parent path>, "myxmlfile");
File cloneFile = new File(originalFile.getParent(),
originalFile.getName()+"<anything_i_want_to_add>");
Files.copy(originalFile.toPath(),cloneFile.toPath());
//now your new file exist and you can use it
originalFile.delete();//you delete the original file
...
//after you are done with everything and you want the path back
Files.copy(cloneFile.toPath(),originalFile.toPath());
cloneFile.delete();
In your lock method, you are calling renameTo method. Because of that, the original filename is now gone, and is replaced by the new filename that ends with .lock.
The java.io.File class is not a file pointer but an object to hold a filename. Using a file object that still refers to an old filename will cause an error.
To answer your question: If you want the old filename after locking, you must use a different approach in locking your file. For example, MS Access locks their .accdb files by creating a lockfile with the same filename as the opened .accdb file.
You may use this code as a reference:
public boolean fileIsLocked(File file) {
File lock = new File(file.getAbsolutePath() + ".lock");
return lock.exists();
}
public void lockFile(File file) {
if (!fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.createNewFile();
lock.deleteOnExit(); // unlocks file on JVM exit
}
}
public void unlockFile(File file) {
if (fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.delete();
}
}

Write String into a file, which the user chooses from <input type="file">

I want to write a String to a file, which the user chooses from . I'm unable to do it because I need the fileName and fileLocation to write my String to the file. But the request.getParamater("") gives me just the fileName. I know that it won't return the fileLocation because of security issues. Then, how do I write my String from the file chosen on my jsp. Please advise.
You cannot write to that file directly.
Short answer : Make a copy file on server.
Long answer:
1) Get the file.
2) Save it on server.
3) Append to that file. Do not overwrite.
4) Again send back the file to user with response.
Do some steps
Get file name using getFileName() method. Store it on server side
if some one wants to Save Same file name again then you append Some Date after file Name. so you can easily get all the files without any code changes.
After write String into file close the file and flush .
See i have upload the file form Front End and Store it on Some local system . when you try to upload Same file again then it append Date with File name
public class uploadFile {
private File myFile;
private String myFileContentType;
private String myFileFileName;
private String destPath;
public String upload() throws IOException {
try {
destPath = System.getProperty("user.home") + System.getProperty("file.separator") + "File-Uploads";
File destFile = new File(destPath, myFileFileName);
File file1 = new File(destFile.toString());
boolean b = false;
Date date = new Date();
if (!(file1.exists())) {
b = file1.createNewFile();
}
if (b) {
FileUtils.copyFile(myFile, destFile);
} else {
String fileContent = "";
File f = new File(file1.toString());
FileInputStream inp = new FileInputStream(f);
byte[] bf = new byte[(int) f.length()];
inp.read(bf);
fileContent = new String(bf, "UTF-8");
System.out.println("file===>" + fileContent);
String filename = destFile.toString() + date;
FileWriter fw = new FileWriter(filename, true);
fw.write(fileContent);
fw.close();
FileUtils.copyFile(myFile, destFile);
}
return SUCCESS;
} catch (IOException e) {
return SUCCESS;
}
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}

RestFul web service which reads properties file

I have got couple of Jersey REST Web services say SendPassword and ResetPassword whose purpose is to send email .
For sending email , i have configured a properties file under tomcat and all this works fine
The code of the SendPassword.java is somewhat this way
#Path("/sendpassword")
public class SendPassword {
#GET
#Produces("application/json")
public String sendPasswordToEmail(#QueryParam("empid") String empid)
throws JSONException
{
try {
SendEmailUtility.sendmail("weqw","2312");
}
catch(Exception e)
{
}
}
SendEmailUtility.java
public class SendEmailUtility
{
public static String sendmail(String sendemalto,String generatedpwd) throws IOException {
String result = "fail";
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
Properties props_load = new Properties();
props_load.load(stream);
final String username = props_load.getProperty("username");
final String password = props_load.getProperty("password");
Properties props_send = new Properties();
props_send.put("mail.smtp.auth","true");
props_send.put("mail.smtp.starttls.enable","true");
Transport.send(message);
// Some code to send email
result = "success";
} catch (MessagingException e) {
result = "fail";
e.printStackTrace();
}
return result;
}
}
As you can see i am reading the properties file for every call of the websercice
(As reading operation is somewhat costly) , Is there any way to resolve this ??
Could you please let me know whats the best approach to handle this.
Thanks in advance .
There are few ways to do this the one way of doing it is to make the props_load a private static member of the class and call it like this
public class SendEmailUtility
{
private static Properties props;
private static Properties getProperties() {
if (props == null) {
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
props = new Properties();
props.load(stream);
}
return props;
}
public static String sendmail(String sendemalto,String generatedpwd) throws IOException {
String result = "fail";
Properties props_load = getProperties();
final String username = props_load.getProperty("username");
final String password = props_load.getProperty("password");
Properties props_send = new Properties();
props_send.put("mail.smtp.auth","true");
props_send.put("mail.smtp.starttls.enable","true");
Transport.send(message);
// Some code to send email
result = "success";
} catch (MessagingException e) {
result = "fail";
e.printStackTrace();
}
return result;
}
}
The other design I would suggest is to make an email service class like EmailSender or EmailService and then inject it into SendPassword class
#Path("/sendpassword")
public class SendPassword {
#Autowired
EmailService emailService;
#GET
#Produces("application/json")
public String sendPasswordToEmail(#QueryParam("empid") String empid)
throws JSONException
{
I would recommend using resource bundle, which does not need InputStream
create a properties file and put directly inside your packages along with your java code
example folder structure
com
- preethi
-SendPassword.java
-email.properties
Then you can code like
ResourceBundle props_load = ResourceBundle.getBundle("com.preethi.email");
final String username = props_load.getString("username");
This way you don't have to worry about opening and closing the stream or file path
You could use a lazy-getter to fetch and cache the Properties object.
private static Properties props;
private static Properties getProperties() {
if (props == null) {
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
props = new Properties();
props.load(stream);
}
return props;
}
Each time you want to use the Properties, call getProperties(). It will cache it the first time it's called. Each subsequent call will just return the cached object.
Note: This example does not catch any exceptions.

Reading file data from shared folder with authentication (FileNotFound Exception)

Following is the code I use to access file from a share folde by authenticating and reading data from the file.(using JCIFs)
public void findFiles() throws Exception{
String url = rs.getString("addPolicyBatchFolder_login_url"); //username, url, password are specified in the property file
String username = rs.getString("addPolicyBatchFolder_login_userName");
String password = rs.getString("addPolicyBatchFolder_login_password");
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
SmbFile dir = null;
dir = new SmbFile(url, auth);
SmbFilenameFilter filter = new SmbFilenameFilter() {
#Override
public boolean accept(SmbFile dir, String name) throws SmbException {
return name.startsWith("starting string of file name");//picking files which has this string on the file name
}
};
for (SmbFile f : dir.listFiles(filter))
{
addPolicyBatch(f.getCanonicalPath()); //passing file path to another method
}
}
With this code, I'm successfully authenticating and I'm able to list the files. And I tried printing canonical path(i tried with just f.path() also) and im able to print the complete path.
Following is the next method.
public void addPolicyBatch(String filename) throws Exception{
File csvFile = new File(filename);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(csvFile)); //FileNotFound exception
while((line = br.readLine()) != null){
//more code
In the above method, when it comes to bufferReader, its showing FleNotFoundException.
If I print the canonical path, following is the output.
smb://sharePath/file.csv correct path
But in the second method(where I get Exception), the exception is as follows.
java.io.FileNotFoundException: smb:\sharePath\file.csv (The filename, directory name, or volume label syntax is incorrect)
As you can see, there is only one \ after smb:.
I'm not sure why its not passing the exact file path as printed in the first method.
If you remove the leading smb: from the name it should work.
Alternatively, you can change your method as follows and use the smb file to create a reader:
public void addPolicyBatch(SmbFile smbFile) throws Exception {
BufferedReader br = null;
try {
SmbFileInputStream smbStream = new SmbFileInputStream(smbFile);
br = new BufferedReader(new InputStreamReader(smbStream));
String line;
while((line = br.readLine()) != null){
//....
Edit, renaming a file.
If you want to use SmbFile to rename, you need the authentication object
public static void renameSmbFile(SmbFile srcFile, String completeUrl,
NtlmPasswordAuthentication auth) throws Exception {
SmbFile newFile = new SmbFile(completeUrl,auth);
srcFile.renameTo(newFile);
}
Wenn using a File object, that is not neccessary:
public static void renameFile(SmbFile srcFile, String nameWithoutProtocol,
NtlmPasswordAuthentication auth) throws Exception {
String fileName = srcFile.getCanonicalPath();
fileName = fileName.substring(4);//removing smb-protocol
new File(fileName).renameTo(new File(nameWithoutProtocol));
}

Categories