Apache Camel Check Directory Read Permission (AWS Environment) - apache-camel

I have an API for validating FTP directory as follows:
public boolean validateDirectory(FtpLocation ftpLocation) throws CustomException{
FTPClient client = new FTPClient();
try {
client.connect(ftpLocation.getSystem(), Integer.parseInt(ftpLocation.getPort()));
client.login(ftpLocation.getUser(), ftpLocation.getPassword());
client.changeWorkingDirectory(ftpLocation.getDirPath());
int returnCode = client.getReplyCode();
if (returnCode == 550) {
LOG.error("Directory ["+ ftpLocation.getDirPath() + "] does not exist");
return false;
}
File dir = new File(ftpLocation.getDirPath());
if(dir!=null){
if (!dir.canRead()) {
LOG.error("Directory ["+ ftpLocation.getDirPath() + "] does not have read permission");
return false;
}
}
return true;
} catch (NumberFormatException | IOException e) {
LOG.error("Failed to validate Source Directory Path [" + ftpLocation.getDirPath() + "]", e);
throw new CustomException("Failed to validate Source Directory Path [" + ftpLocation.getDirPath() + "]", e);
} finally {
try {
client.disconnect();
} catch (IOException e) {
LOG.warn("Error occured while disconnecting FTPClient", e);
}
}
}
My FTP root is / (absolute path /home/soumya)
I want to route files from /source (absolute path /home/soumya/source)
The following behaviors I found during the testing of my API:
if source with permission rwxrwxr-x then throws validation message (actually expecting a successful file routing).
if source with permission -wx-wx--x then validated successfully.
if source is not present then validated successfully.
if source is not a directory (source is a file) then validated successfully.
Log is as follows for the above four scenarios:
07:41:59.799 [pool-2-thread-1] ERROR c.n.d.m.b.f.Validator - Directory [/source] does not have read permission
07:42:48.801 [pool-2-thread-1] ERROR c.n.d.m.b.f.Validator - Directory [/source] does not have read permission
07:43:27.093 [pool-2-thread-1] ERROR c.n.d.m.b.f.Validator - Directory [/source] does not exist
07:44:00.215 [pool-2-thread-1] ERROR c.n.d.m.b.f.Validator - Directory [/source] does not exist
Question:
Is there any alternate way to solve the problem of 1, to route the files of source successfully ?
How to validate the directory to check the read permission ?
NOTE: Camel version is 2.12.1

I found a solution for my problem, here is it as follows:
public void validateDirectory(FtpLocation ftpLocation) throws CustomException {
FTPClient client = new FTPClient();
try {
client.connect(ftpLocation.getSystem(), Integer.parseInt(ftpLocation.getPort()));
client.login(ftpLocation.getUser(), ftpLocation.getPassword());
client.enterLocalPassiveMode();
client.changeWorkingDirectory(ftpLocation.getDirPath());
int returnCode = client.getReplyCode();
LOG.debug("FTP return code: "+ returnCode);
if (returnCode == 550) {
LOG.error("Directory ["+ ftpLocation.getDirPath() + "] does not exist");
throw new CustomException("Directory ["+ ftpLocation.getDirPath() + "] does not exist");
}
String targetDir = client.printWorkingDirectory();
client.cdup();
targetDir = StringUtils.substring(targetDir, StringUtils.lastIndexOf(targetDir, File.separator) + 1);
FTPFile ftpFiles[] = client.listFiles();
for(FTPFile ftpFile : ftpFiles){
if(StringUtils.equals(ftpFile.getName(), targetDir) && !ftpFile.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)){
LOG.error("No read permission for directory [" + ftpLocation.getDirPath() + "]");
throw new CustomException("No read permission for directory [" + ftpLocation.getDirPath() + "]");
}
}
} catch (NumberFormatException | IOException e) {
LOG.error("Failed to validate Source Directory Path [" + ftpLocation.getDirPath() + "]", e);
throw new CustomException("Failed to validate Source Directory Path [" + ftpLocation.getDirPath() + "]", e);
} finally {
try {
client.disconnect();
} catch (IOException e) {
LOG.warn("Error occured while disconnecting FTPClient", e);
}
}
}
However if you have a better solution then please post it.

Related

How to get path of isolated storage in silverlight?

I read a similar post here... I tried implementing it but getting an exception saying
Attempt by method 'get_path_isolated.Page.button1_Click(System.Object, System.Windows.RoutedEventArgs)' to access field 'System.IO.IsolatedStorage.IsolatedStorageFileStream.m_FullPath' failed.
I have this code
public void button1_Click(object sender, RoutedEventArgs e)
{
isoStore = IsolatedStorageFile.GetUserStoreForApplication();
isoStore.CreateDirectory("root_dir");
IsolatedStorageFileStream iostream = new IsolatedStorageFileStream("sampleFile.txt", FileMode.Create, isoStore);
StreamWriter writer = new StreamWriter(iostream);
writer.Write("jaimokar");
try
{
FieldInfo pi = iostream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic);
string path = pi.GetValue(iostream).ToString();
}
catch (Exception ex)
{
textBox1.Text += ex.Message;
}
where I'm going wrong? Please help me..
For those that have Elevated Permissions (especially in browser) I have come up with a semi-functional solution to determine the path. Unfortunately, if you switch from dev to live you will see a different folder path, so you have to include it here, also you should add a check for which version you are running (dev or live) via a passed in page parameter or the host url or so
private string GetProfilePath() {
var fullname = string.Empty;
try
{
// ReSharper disable IdentifierTypo
// ReSharper disable CommentTypo
var profilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
profilePath = Path.GetDirectoryName(profilePath);
profilePath = Path.Combine(profilePath, #"LocalLow\Microsoft\Silverlight\is");
//profilePath = Path.Combine(profilePath, IsoPathStaging + "\\");
var directoryInfo = new DirectoryInfo(profilePath); // C:\Users\<username>\AppData\LocalLow\Microsoft\Silverlight\is --constant
var dirs = directoryInfo.EnumerateDirectories();
// ReSharper disable PossibleMultipleEnumeration
fullname = "1: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \ir5ffeej.4of --random
fullname = "2: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \lfab1wva.xmb --random
fullname = "3: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \1 --constant
fullname = "4: " + dirs.First().FullName;
dirs = dirs.Where(d => d.Name == "s"); // \s --constant
fullname = "5: " + dirs.First().FullName;
var dirs2 = dirs.First().EnumerateDirectories()
.Where(d => d.Name == "sbudlbc2oqx0eo0odi5nzpo2qppp3zmxxxxxxxxxxxxxxxxxxxxxxxxx").ToList(); // \<dev dir> --constant-ish
if (!dirs2.Any())
{
dirs2 = dirs.First().EnumerateDirectories()
.Where(d => d.Name == "2gbsxl5no1wzqebnzbj2wglhi33za1rxxxxxxxxxxxxxxxxxxxxxxxxx").ToList(); // \<live dir> --constant-ish
}
if (!dirs2.Any())
{
throw new Exception("Unable to locate silverlight storage");
}
fullname = "6: " + dirs2.First().FullName;
dirs = dirs2.First().EnumerateDirectories().Where(d => d.Name == "f"); // \f --constant
fullname = "7: " + dirs.First().FullName;
var dir = dirs.First(); // final
fullname = dir.FullName;
// ReSharper restore CommentTypo
// ReSharper restore PossibleMultipleEnumeration
return fullname;
// ReSharper restore IdentifierTypo
}
catch (NotSupportedException ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run (Not Supported):"
+ Environment.NewLine + fullname
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
CheckElevatedPermissions();
return string.Empty;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run:"
+ Environment.NewLine + fullname
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
return string.Empty;
}
}
Again, you must have elevated rights for this to work, later I would use this path to locate a file for some other use:
var fullPath = Path.Combine(GetProfilePath(), FileName);
Run(fullPath.Replace("\\\\", "\\"));
private static void Run(string fullPath)
{
try
{
CheckElevatedPermissions();
var shell = AutomationFactory.CreateObject("WScript.Shell");
shell.Run("\"" + fullPath + "\"");
}
catch (NotSupportedException ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run (Not Supported):"
+ Environment.NewLine + fullPath
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
CheckElevatedPermissions();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run:"
+ Environment.NewLine + fullPath
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
}
}

Opening a file for editing

I want to create a method that will load a txt file and then change it but thats another method.
private void openFile() {
fileChooser.getSelectedFile();
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(frame);
}
What must go next in order to get data from the file after choosing it to manipulate its data?
The JFileChooser documentation has an example on how to continue your code, and get the name of the file chosen, which can then be turned into a File object. You should be able to modify that example to meet your needs:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Here's an example that might help you. I would want to read up on and try some simple examples on different buffers that will read and write. In fact, i have worked with these a lot in the last few months and I still have to go and look.
public class ReadWriteTextFile {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
static public void setContents(File aFile,
String aContents)
throws FileNotFoundException,
IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
output.write( aContents );
}
finally {
output.close();
}
}
public static void main (String... aArguments) throws IOException {
File testFile = new File("C:\\Temp\\test.txt");//this file might have to exist (I am not
//certain but you can trap the error with a
//TRY-CATCH Block.
System.out.println("Original file contents: " + getContents(testFile));
setContents(testFile, "The content of this file has been overwritten...");
System.out.println("New file contents: " + getContents(testFile));
}
}

unzip and read each file on Google App Engine (Java)

I'm trying to create a servlet that is able to unzip a folder which contains 3 csv files and then print out the data of each csv file.
I have been trying to use ZipInputStream but it does not provide me the capability of reading/printing content of each csv.
As i'm building this web app on GAE, I'm unable to use FileOutputStream.
Are there ways to use ZipInputStream to unzip and read individual csv without the need to create a csv on GAE?
public class AdminBootStrap extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
try {
ServletFileUpload upload = new ServletFileUpload();
resp.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if (item.isFormField()) {
out.println("Got a form field: " + item.getFieldName());
} else {
out.println("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(in));
ZipEntry entry;
// Read each entry from the ZipInputStream until no
// more entry found indicated by a null return value
// of the getNextEntry() method.
//
while ((entry = zis.getNextEntry()) != null) {
out.println("Unzipping: " + entry.getName());
//until this point, i'm only available to print each csv name.
//What I want to do is to print out the data inside each csv file.
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
// throw new ServletException(ex);
}
}
}
ZipInputStream is an InputStream, so you can read from it as normal:
while ((entry = zis.getNextEntry()) {
byte[] buf = new byte[1024];
int len;
while ((len = zis.read(buf)) > 0) {
// here do something with data in buf
}
   

WindowsExplorer Drop Get Files and Files From Folders

From what I can tell there is not way of telling if the drop was a file or a folder.
if (fi.Extension == "") is not sufficient as that matches a directory and also a file with no extension.
The only way I found was to .GetFiles() and handle the exception.
Is there a better way?
private void ListView0_DragDrop(object sender, DragEventArgs e)
{
// Can only drop files, so check
if (!e.Data.GetDataPresent(DataFormats.FileDrop))
{
return;
}
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
FileInfo fileInfo;
DirectoryInfo dirInfo;
foreach (string str in files)
{
dirInfo = new DirectoryInfo(str);
try
{
foreach(FileInfo fi in dirInfo.GetFiles())
{
Debug.WriteLine("File in dir " + fi.Name);
}
}
catch
{
fileInfo = new FileInfo(str);
Debug.WriteLine("File " + str);
}
}
I would use Directory.Exists and File.Exists before adding a try catch - although you may need the try anyway due to security on the files / directories (both of these Exists methods can throw FileIOException.
DirectoryInfo dirInfo;
foreach (string str in files)
{
if (Directory.Exists(str))
{
dirInfo = new DirectoryInfo(str);
foreach(FileInfo fi in dirInfo.GetFiles())
{
Debug.WriteLine("File in dir " + fi.Name);
}
}
else if (File.Exists(str))
{
fileInfo = new FileInfo(str);
Debug.WriteLine("File " + str);
}
}

Special symbols in subject of emails

We are currently working on a defect to allow special symbols also to be seen in email subject. The email is text/html mime type.
Currently, if the subject should have a heart symbol it is shown as "&heart" but in the email body a "heart" symbol is shown.
Can someone help us with the solution to have special symbols also part of subject?
Here is the code snippet.
public boolean send(String to, String from, String subject, String templatePath, Map map) {
// create a mime message using the mail sender implementation
MimeMessage mimeMessage = mailSender.createMimeMessage();
// create the message using the specified template
MimeMessageHelper helper;
try
{
helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
helper.setFrom(from);
String text = VelocityEngineUtils.mergeTemplateIntoString(engine, templatePath, map);
helper.setText(text, true);
send(mimeMessage);
log.debug("in send at start" + this.getClass().getName()
+ ":SUCCESS: Sendig mail to" + to + " from " + from + " subject "
+ subject);
} catch (MessagingException e)
{
throw new MailPreparationException("unable to create the mime message helper", e);
} catch (Exception e)
{
log.debug("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ to + " from " + from + " subject " + subject);
// throw new
// MailPreparationException("unable to create the mime message helper",
// e);
}
return false;
}
public boolean send(MimeMessage mimeMessage) throws Exception {
try
{
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
multipart.addBodyPart(bodyPart);
bodyPart.setContent(mimeMessage.getContent(), "text/html");
mimeMessage.setContent(multipart);
mailSender.send(mimeMessage);
} catch (Exception e)
{
log.error("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ e.getMessage());
// e.printStackTrace();
throw e;
// return false;
}
return true;
}
public static String HTMLDecode(String encodedHTML) {
return encodedHTML.replaceAll("¡", "\u00A1")
.replaceAll("¢", "\u00A2")
.replaceAll("£", "\u00A3")
.replaceAll("¤", "\u00A4")
.replaceAll("¥", "\u00A5")
.replaceAll("¦", "\u00A6")
.replaceAll("§", "\u00A7")
.replaceAll("¨", "\u00A8")
........
You can send as Unicode / UTF-8.

Resources