My requirement is there is an export button,onclick the data in the database is loaded and then converted into a .csv ,.doc or .html file ,which can be opened or saved somehere, this needs to be converted into a file , save it in the local path and uploaded to the SFTP server and deleted from the loacl path. My code goes like this .....
public String a(String tableName, String format,String jsondataAsString,String jsonKeyName,String userName,
String password, String hostName,String remotePath) throws IOException{
userName="a";
password="a";
hostName="10.100.10.100";
remotePath="/tmp";
System.out.println("TableName-->" +tableName);
System.out.println("Format-->" +format);
System.out.println("JsonData-->" +jsondataAsString);
System.out.println("userName-->" +userName);
System.out.println("password-->" +password);
System.out.println("hostname-->" +hostName);
System.out.println("RemotePath-->" +remotePath);
String mimeType = null;
String fileName = null;
String seperator = null;
String lineSeperator = null;
boolean isFileTransferComplete=true;
OutputStream f1 =null;
if (format.equalsIgnoreCase("CSV")) {
fileName = tableName + ".csv";
mimeType = "application/CSV";
seperator = ",";
lineSeperator = "\n";
} else if (format.equalsIgnoreCase("Word")) {
fileName = tableName + ".doc";
mimeType = "application/msword";
seperator = " ";
lineSeperator = "\n\n";
} else {
fileName = tableName + ".html";
mimeType = "application/html";
seperator = " ";
lineSeperator = "<br><br>";
}
String localfilePath="D:/aaa/" +fileName;
String error="";
try{
String data = convertJsonToString(jsondataAsString, seperator, jsonKeyName,lineSeperator,format);
if (data == null || data.length() == 0) {
data = "[BLANK]";
}
boolean isFileTobeDeleted=true;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.out.println("Buffer-->" +buffer);
buffer.flush();
buffer.write(data.getBytes());
f1 = new FileOutputStream(localfilePath);
buffer.writeTo(f1);
isFileTransferComplete = new SFTPHandler(hostName,
PicoEmsGuiConstants.SFTP_Port, userName, password)
.uploadFile(remotePath,localfilePath);
System.out.println("FileTransfer" +isFileTransferComplete);
File target = new File(localfilePath);
target.delete();
}
System.out.println("isFileTobeDeleted" +isFileTobeDeleted);
}catch(Exception e){
System.out.println("Exception :::>" +e.getMessage());
}finally{
f1.close();
}
return isFileTransferComplete+"--"+ remotePath;
}
I am able to create file but after the completion of uploading unable to delete form the loacl path...Can anyone tell me where i am goin wrong
Don't you have to close the stream and then attempt to delete it?
finally {
f1.close();
if(file != null && file.exists()) {
file.delete();
}
}
Related
On clicking the download button a file will be downloaded in my project dir and I want to read that file content this is pdf
File name is dynamic. It starts with same name but in middle the content is dynamic and ends with .pdf extension.
Code:
public static String isFileDownloaded(String fileText, String fileExtension, int timeOut) {
String folderName = System.getProperty("user.dir")+"\\src\\test\\resources\\Download\\";
File[] listOfFiles;
int waitTillSeconds = timeOut;
boolean fileDownloaded = false;
String filePath = null;
long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
while (Instant.now().getEpochSecond() < waitTillTime) {
listOfFiles = new File(folderName).listFiles();
for (File file : listOfFiles) {
String fileName = file.getName().toLowerCase();
if (fileName.contains(fileText.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) {
fileDownloaded = true;
filePath = fileName.getAbsolutePath();
break;
}
}
if (fileDownloaded) {
break;
}
}
return filePath;
}
public static String readPdfContent(String fileName) throws IOException {
File file = new File(System.getProperty(fileName));
PDDocument doc = PDDocument.load(file);
int numberOfPages = getPageCount(doc);
System.out.println("The total number of pages "+numberOfPages);
String content = new PDFTextStripper().getText(doc);
doc.close();
return content;
}
try {
JSclick(download);
String filePath = isFileDownloaded("Personal Data", ".pdf", 30);
if(filePath != null){
String pdfContent = readPdfContent(filePath);
Assert.assertTrue(pdfContent.contains("Test Kumar"));
Assert.assertTrue(pdfContent.contains("XXXXX"));
}else {
System.out.println("Some issue with file downloading");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
it show me error-:The method getAbsolutePath() is undefined for the type String
Can you please help on this?
Create a method to check whether a file is fully downloaded or not.
Call that method wherever it's required.
Method to check file is downloaded or not: This method is to search for specific file with partial or full text in download folder for given time and returns the absolute path of the file.
#param fileText - Partial or full file name
#param fileExtension - .pdf, .txt
#param timeOut - How many seconds you are expecting for file to be downloaded.
public static String isFileDownloaded(String fileText, String fileExtension, int timeOut) {
String folderName = "location of download folde";
File[] listOfFiles;
int waitTillSeconds = timeOut;
boolean fileDownloaded = false;
String filePath = null;
long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
while (Instant.now().getEpochSecond() < waitTillTime) {
listOfFiles = new File(folderName).listFiles();
for (File file : listOfFiles) {
String fileName = file.getName().toLowerCase();
if (fileName.contains(fileText.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) {
fileDownloaded = true;
filePath = file.getAbsolutePath();
break;
}
}
if (fileDownloaded) {
break;
}
}
return filePath;
}
Call the isFileDownloaded method:
As you know the partial file name then you can pass the input like below to get the file path.
String filePath = isFileDownloaded("Personal Data", ".pdf", 30);
System.out.println("Complete path of file:"+ filePath);
Output:
C:\Users\Download\Personal data...pdf
Updated code for OP's logic:
Try block:
try {
JSclick(download);
String filePath = isFileDownloaded("Personal Data", ".pdf", 30);
if(filePath != null){
String pdfContent = readPdfContent(filePath);
Assert.assertTrue(pdfContent.contains("Test Kumar"));
Assert.assertTrue(pdfContent.contains("XXXXX"));
}
}else{
System.out.println("Some issue with file downloading");
}
Read pdf content method:
public static String readPdfContent(String fileName) throws IOException {
File file = new File(System.getProperty(fileName);
PDDocument doc = PDDocument.load(file);
int numberOfPages = getPageCount(doc);
System.out.println("The total number of pages "+numberOfPages);
String content = new PDFTextStripper().getText(doc);
doc.close();
return content;
}
Well you can simply list all files in folder and take the newest
Like something:
File f = new File("download_folder");
String[] pathnames = f.list();
then you can use for-loop to find what you need
As part of our system, we are extracting Mail messages from Exchange Inbox Folder.
All goes well , except the point of extracting the Email Body.
Email body saved as an HTML however CIDS ( INLINE Attachments) are required to be kept in the HTML document as Base64.
how this is possible to do ?
Any examples?
private void downloadAttachment(Part part, String folderPath) throws Exception {
String disPosition = part.getDisposition();
String fileName = part.getFileName();
String decodedText = null;
logger.info("Disposition type :: " + disPosition);
logger.info("Attached File Name :: " + fileName);
if (disPosition != null && disPosition.equalsIgnoreCase(Part.ATTACHMENT)) {
logger.info("DisPosition is ATTACHMENT type.");
File file = new File(folderPath + File.separator + decodedText);
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
} else if (fileName != null && disPosition == null) {
logger.info("DisPosition is Null type but file name is valid. Possibly inline attchment");
File file = new File(folderPath + File.separator + decodedText);
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
} else if (fileName == null && disPosition == null) {
logger.info("DisPosition is Null type but file name is null. It is email body.");
File file = new File(folderPath + File.separator + "mail.html");
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
}
}
protected int saveEmailAttachment(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = null;
InputStream is = null;
int ret = 0, count = 0;
try {
bos = new BufferedOutputStream(new FileOutputStream(saveFile));
part.writeTo(new FileOutputStream(saveFile));
} finally {
try {
if (bos != null) {
bos.close();
}
if (is != null) {
is.close();
}
} catch (IOException ioe) {
logger.error("Error while closing the stream.", ioe);
}
}
return count;
}
I have got some method from the stackoverflow about uploading file in spark java, but I try and did't work.
post("/upload",
(request, response) -> {
if (request.raw().getAttribute("org.eclipse.jetty.multipartConfig") == null) {
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(System.getProperty("java.io.tmpdir"));
request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);
}
Part file = request.raw().getPart("file");
Part name = request.raw().getPart("name");
String filename = file.getName();
if(name.getSize() > 0){
try{
filename = IOUtils.toString(name.getInputStream(), StandardCharsets.UTF_8);
} catch(Exception e){
e.printStackTrace();
}
}
Path filePath = Paths.get(".",filename);
Files.copy(file.getInputStream(),filePath);
return "Done!";
});
}
I use postman to send the message
And I got the Error like this
The error points to the code Part file = request.raw().getPart("file");
post("/upload", "multipart/form-data", (request, response) -> {
String location = "image"; // the directory location where files will be stored
long maxFileSize = 100000000; // the maximum size allowed for uploaded files
long maxRequestSize = 100000000; // the maximum size allowed for multipart/form-data requests
int fileSizeThreshold = 1024; // the size threshold after which files will be written to disk
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
location, maxFileSize, maxRequestSize, fileSizeThreshold);
request.raw().setAttribute("org.eclipse.jetty.multipartConfig",
multipartConfigElement);
Collection<Part> parts = request.raw().getParts();
for (Part part : parts) {
System.out.println("Name: " + part.getName());
System.out.println("Size: " + part.getSize());
System.out.println("Filename: " + part.getSubmittedFileName());
}
String fName = request.raw().getPart("file").getSubmittedFileName();
System.out.println("Title: " + request.raw().getParameter("title"));
System.out.println("File: " + fName);
Part uploadedFile = request.raw().getPart("file");
Path out = Paths.get("image/" + fName);
try (final InputStream in = uploadedFile.getInputStream()) {
Files.copy(in, out);
uploadedFile.delete();
}
// cleanup
multipartConfigElement = null;
parts = null;
uploadedFile = null;
return "OK";
});
This will work well, I found it in https://groups.google.com/forum/#!msg/sparkjava/fjO64BP1UQw/CsxdNVz7qrAJ
I'm retrieving files list from FTPClient using ftpClient.listFiles(); and it returns an array with correct file names and appropriate quantity.
I'm trying to read content from files, but only ftpClient.retrieveFileStream(fileName) is available for that purpose. And it somehow breaks after reading the first file and returns null.
Is there a way to convert FTPFile directly into String?
ftp.connect();
ftp.changeWorkingDirectoryToFrom();
List<String> idsList = new ArrayList<String>();
List<String> names = ftp.listFileNames();
for (String fileName : names) {
String content = fromFTPFileToString(fileName);
Matcher matcher = FILES_PATTERN.matcher(content);
String id = extractId(content);
if (matcher.find()) {
boolean duplicate = idsList.contains(id);
LOG.info("MATCHED: " + fileName);
if (!duplicate) {
ftp.moveFileFromTo(fileName);
idsList.add(id);
} else {
LOG.info("DUPLICATE: " + fileName);
duplicated++;
ftp.deleteFileOnFromFtp(fileName);
}
}
processed++;
}
ftp.disconnect();
private String fromFTPFileToString(String fileName) {
String content = "";
try {
InputStream is = ftp.readContentFromFTPFile(fileName);
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, ENCODING);
content = writer.toString();
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(writer);
} catch (Exception ex) {
LOG.error(ex);
}
return content;
}
void deleteFileOnFromFtp(String fileName) {
changeWorkingDirectory(properties.getProperty(PropertiesType.FOLDER_FROM.toString()));
deleteFile(fileName);
}
InputStream readContentFromFTPFile(String fileName) {
changeWorkingDirectory(properties.getProperty(PropertiesType.FOLDER_FROM.toString()));
InputStream inputStream = null;
try {
inputStream = ftpClient.retrieveFileStream(fileName);
} catch (IOException ex) {
LOG.error("Unable to extract content from file:" + O_Q + fileName + C_Q);
}
return inputStream;
}
void moveFileFromTo(String fileName) {
String from = FORWARD_SLASH + properties.getProperty(PropertiesType.FOLDER_FROM.toString()) + FORWARD_SLASH + fileName;
String to = FORWARD_SLASH + properties.getProperty(PropertiesType.FOLDER_TO.toString()) + FORWARD_SLASH + fileName;
try {
ftpClient.rename(from, to);
} catch (IOException ex) {
LOG.error("Unable to move file file from:" + O_Q + from + C_Q + " to: " + O_Q + to + C_Q);
throw new RuntimeException(ex.getCause());
}
}
3 Hints
1) You can use retrieveFile
And use a ByteArrayOutputStream as the 2nd parameter.
To get a String from it simply "new String(baos.toByteArray(),[The Charset you used]);"
2) Check for ftpClient.completePendingCommand();
If some commands are still pending
3) I had once a similar issue setting ftp.enterLocalPassiveMode() helped
I'm trying to read a text files and insert the data from these text files into a URL;
but i have this error "java.lang.illegalargumentexception contains a path separator file"
this is the read method that im using
>
public String ReadFile (String Path){
String res = null;
try {
String filePath = android.os.Environment.getExternalStorageDirectory().getPath() + "/" + Path;
File file = new File(filePath);
if(file.exists()){
InputStream in = openFileInput(filePath);
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
res = "";
String line;
while (( line = buffreader.readLine()) != null) {
res += line;
}
in.close();
}else{
}
}else{
Toast.makeText(getApplicationContext(), "The File" + Path + " not Found" ,Toast.LENGTH_SHORT).show();
}
} catch(Exception e){
Toast.makeText(getApplicationContext(),e.toString() + e.getMessage(),Toast.LENGTH_SHORT).show();
}
return res;
}
> String sendername = ReadFile ("SenderName.txt");
String AccountName = ReadFile ("AccountName.txt");
String AccountPassword = ReadFile ("AccountPassword.txt");
String MsgText = ReadFile ("MsgText.txt");
Thanks,
- Though this error doesn't points there, but still have you given the permission to read External Storage in the Manifest.xml file
Try something like this..
public void readFile(String path){
File f = new File(path);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String read = new String();
String temRead = new String();
while((temRead = br.readLine())!=null){
read = read + temRead;
}
}