NoSuchMethoException on calling DefaultValidator.getValidFileName() - java

I am trying to use getValidFileName (String, String, list, boolean) method of DefaultValidator class from ESAPI provided jar (esapi-2.0_rc11) to validate file name. But on run time getting No such method exception.
This is my code:
public static String getValidFileName(String input,String[] strFileExtns, Boolean isNullable) throws Exception
{
List <String> fileExtnsList = new ArrayList <String>();
if (strFileExtns != null && strFileExtns.length > 0)
for(int i=0; i<strFileExtns.length; i++)
fileExtnsList.add(strFileExtns[i]);
return new DefaultValidator().getValidFileName("FileNameValidation", input, fileExtnsList, isNullable);
}
I am getting
java.lang.NoSuchMethodError:org/owasp/esapi/reference/DefaultValidator.getValidFileName(Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Z)Ljava/lang/String;
Code present in the jar:
public String getValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull)
throws ValidationException, IntrusionException
{
if ((allowedExtensions == null) || (allowedExtensions.isEmpty())) {
throw new ValidationException("Internal Error", "getValidFileName called with an empty or null list of allowed Extensions, therefore no files can be uploaded");
}
String canonical = "";
try
{
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException(context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context);
}
canonical = new File(input).getCanonicalFile().getName();
getValidInput(context, input, "FileName", 255, true);
File f = new File(canonical);
String c = f.getCanonicalPath();
String cpath = c.substring(c.lastIndexOf(File.separator) + 1);
if (!(input.equals(cpath)))
throw new ValidationException(context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context);
}
catch (IOException e)
{
throw new ValidationException(context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context);
}
Iterator i = allowedExtensions.iterator();
while (i.hasNext()) {
String ext = (String)i.next();
if (input.toLowerCase().endsWith(ext.toLowerCase()))
return canonical;
}
throw new ValidationException(context + ": Invalid file name does not have valid extension ( " + allowedExtensions + ")", "Invalid file name does not have valid extension ( " + allowedExtensions + "): context=" + context + ", input=" + input, context);
}
Someone please help me on this.

java.lang.NoSuchMethodError errors are often caused by a dependency issue. If you are using maven (I assume you may be, as this error often occurs with it), troubleshoot the error as follows:
Try issuing "mvn dependency:tree -Dverbose" on the command line and check that the library containing org/owasp/esapi/reference/DefaultValidator is the version you intended. If not, you can use the exclusions tag to exclude the incorrect version from the dependency that is including the incorrect version.
Also check that your resulting classpath lists the dependencies in the correct order.

Related

Problem with getting list of names of attached files in NotesDocument

I am getting sometimes problems with creating a list of names of the attached files in a NotesDocument. The custom message looks as followed:
AttachmentDominoDAO - General problem during reading attachment from
entry 39E411CEC4AD22F3C1258821003399EF in database mail.nsf.
fileObject.getName() returns null. Files found in document
[contract.pdf]
Here is the method that I am calling:
private Attachment loadFromEntry(ViewEntry entry) {
utils.printToConsole(this.getClass().getSimpleName().toString() + " - loadFromEntry(...) unid=" + entry.getUniversalID());
Attachment attachment = new Attachment();
try{
attachment.setUnid(entry.getUniversalID());
Document doc = entry.getDocument();
if (null != doc){
attachment.setCreated(doc.getCreated().toJavaDate());
if(doc.hasItem("$FILE")){
List<String> files = doc.getAttachmentNames();
for (int j = 0; j < files.size(); ++j) {
EmbeddedObject fileObject = doc.getAttachment(files.get(j));
if(null != fileObject.getName()) {
if(null != fileObject.getName()) {
attachment.setFile(fileObject.getName());
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", fileName.getName() returns " + fileObject.getName(), Level.SEVERE, null);
}
if(null != fileObject.getName() && !utils.Right(fileObject.getName(),".").isEmpty()) {
attachment.setExtension(utils.Right(fileObject.getName(),"."));
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", extension is empty for file " + fileObject.getName(), Level.SEVERE, null);
}
attachment.setSizeHuman(FileUtils.byteCountToDisplaySize(fileObject.getFileSize()));
if(fileObject.getFileSize() > 0) {
attachment.setSize(fileObject.getFileSize());
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", fileName.size() returns " + fileObject.getFileSize(), Level.SEVERE, null);
}
if(null != doc.getAuthors() && null != doc.getAuthors().firstElement()) {
attachment.setCreator(doc.getAuthors().firstElement());
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", doc.getAuthors().firstElement() returns " + doc.getAuthors().firstElement(), Level.SEVERE, null);
}
String fieldName = "type";
if (doc.hasItem(fieldName)) {
attachment.setType(fieldName);
}
}else {
XspOpenLogUtil.logEvent(null, "AttachmentDominoDAO - General problem during reading attachment from entry " + entry.getUniversalID() + " in database " + entry.getDocument().getParentDatabase().getFileName() + ". fileObject.getName() returns null. Files found in document " + doc.getAttachmentNames().toString(), Level.SEVERE, null);
}
}
}
}
}catch (Exception e) {
XspOpenLogUtil.logEvent(e, "General problem with reading attachment from entry " + entry.getUniversalID() + " in database " + entry.getDocument().getParentDatabase().getFileName(), Level.SEVERE, null);
}
return attachment;
}
One document can only contain one file. When I check the document there is only one attachment and the attachment mentioned in the error message.
Anyone has a suggestion how to fix this issue?
Note: in 99% of the cases the error does not occur.
If getName() returns null for an attachment, try using getSource() instead. As long as it's an actual attachment (as opposed to an OLE embedded object), then getSource() always returns the original file name.
NotesDocument.getAttachment does not find attachments that were created in rich text fields. It only finds attachments that were created directly in the document itself.
We used to call an attachment that is directly acceessed through the document a "V2 attachment" because that's the way things worked in Notes V2 -- over 30 years ago. Objects created through OLE launch properties on the form can also attach objects that are directly in the document instead of inside rich text. Since OLE and V2 are both relics of the deep, dark past, almost all attachments are created inside rich text fields these days.
Attachments that are inside rich text fields are accessed through the getEmbeddedObject method of the RichTextItem class.

NPE in a do/while loop due to EOF...catching the EOF earlier to avoid the NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have written this program to compare 2 files. They are 500mb to 2.8gb in size and are created every 6 hours. I have 2 files from 2 sources (NMD and XMP). They are broken up into lines of text that have fields separated by the pipe(|) character. Each line is a single record and may be up to 65,000 characters long. The data is about TV shows and movies, showing times and descriptive content. I have determined that any particular show or movie has a minimum of 3 pieces of data that will uniquely identify that show or movie. IE: CallSign, ProgramId and StartLong. The two sources for this data are systems called NMD and XMP hence that acronym added to various variables. So my goal is to compare a file created by NMD and one created by XMP and confirm that everything that NMD produces is also produced by XMP and that the data in each matched record is the same.
What I am trying to accomplish here is this: 1. Read the NMD file record by record for the 3 unique data fields. 2. Read the XMP file record by record and look for a match for the current record in the NMD file. 3.The NMD file should iterate one record at a time. Each NMD record should then be searched for in the entire XMD file, record by record for that same record. 4. Write a log entry in one of 2 files indicating success or failure and what that data was.
I have an NPE issue when I reach the end of the testdataXMP.txt file. I assume the same thing will happen for testdataNMD.txt. I'm trying to break out of the loop right after the readLine since the epgsRecordNMD or epgsRecordXMP will have just reached the end of the file if it at that point in the file. The original NPE was for trying to do a string split on null data at the end of the file. Now I'm getting an NPE here according to the debugger.
if (epgsRecordXMP.equals(null)) {
break;
}
Am I doing this wrong? If I'm really at the end of the file, the readLine ought to return null right?
I did it this way too, but to my limited experience they feel like they are effectively the same thing. It too threw an NPE.
if (epgsRecordXMP.equals(null)) break;
Here's the code...
public static void main(String[] args) throws java.io.IOException {
String epgsRecordNMD = null;
String epgsRecordXMP = null;
BufferedWriter logSuccessWriter = null;
BufferedWriter logFailureWriter = null;
BufferedReader readXMP = null;
BufferedReader readNMD = null;
int successCount = 0;
readNMD = new BufferedReader(new FileReader("d:testdataNMD.txt"));
readXMP = new BufferedReader(new FileReader("d:testdataXMP.txt"));
do {
epgsRecordNMD = readNMD.readLine();
if (epgsRecordNMD.equals(null)) {
break;
}
String[] epgsSplitNMD = epgsRecordNMD.split("\\|");
String epgsCallSignNMD = epgsSplitNMD[0];
String epgsProgramIdNMD = epgsSplitNMD[2];
String epgsStartLongNMD = epgsSplitNMD[9];
System.out.println("epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD );
do {
epgsRecordXMP = readXMP.readLine();
if (epgsRecordXMP.equals(null)) {
break;
}
String[] epgsSplitXMP = epgsRecordXMP.split("\\|");
String epgsCallSignXMP = epgsSplitXMP[0];
String epgsProgramIdXMP = epgsSplitXMP[2];
String epgsStartLongXMP = epgsSplitXMP[9];
System.out.println("epgsCallsignXMP: " + epgsCallSignXMP + " epgsProgramIdXMP: " + epgsProgramIdXMP + " epgsStartLongXMP: " + epgsStartLongXMP);
if (epgsCallSignXMP.equals(epgsCallSignNMD) && epgsProgramIdXMP.equals(epgsProgramIdNMD) && epgsStartLongXMP.equals(epgsStartLongNMD)) {
logSuccessWriter = new BufferedWriter (new FileWriter("d:success.log", true));
logSuccessWriter.write("NMD match found in XMP " + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logSuccessWriter.write("\n");
successCount++;
logSuccessWriter.write("Successful matches: " + successCount);
logSuccessWriter.write("\n");
logSuccessWriter.close();
System.out.println ("Match found");
System.out.println ("Successful matches: " + successCount);
}
} while (epgsRecordXMP != null);
readXMP.close();
if (successCount == 0) {
logFailureWriter = new BufferedWriter (new FileWriter("d:failure.log", true));
logFailureWriter.write("NMD match not found in XMP" + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logFailureWriter.write("\n");
logFailureWriter.close();
System.out.println ("Match NOT found");
}
} while (epgsRecordNMD != null);
readNMD.close();
}
}
You should not make this:
if (epgsRecordXMP.equals(null)) {
break;
}
If you want to know if epgsRecordXMPis null then the if should be like this:
if (epgsRecordXMP == null) {
break;
}
To sum up: your app throws NPE when try to call equals method in epgsRecordXMP.

Dropbox java api get file details

I am java developer.I need to get file information from dropbox using java api.
I tried with metadata class.Here i am getting only id,name,path,size of the file.
But i need to get other information like owner name,mimetype,Createddate
ListFolderResult result = client.files().listFolderBuilder("")
.withIncludeDeleted(false)
.withRecursive(true)
.withIncludeMediaInfo(true)
.start();
while (true) {
List<Metadata> entries = result.getEntries();
int idx = 0;
for (Metadata metadata : entries) {
if (metadata instanceof FolderMetadata) {
System.out.println("" + ++idx + ": FOLDER [" + metadata.getPathDisplay() + "], [" + metadata.getName() + "]");
} else if (metadata instanceof FileMetadata) {
System.out.println("" + ++idx + ": File [" + metadata.getPathDisplay() + "], [" + metadata.getName() + "]");
String filePath = metadata.getPathLower().replace(metadata.getName().toLowerCase(), "");
System.out.println(metadata.getPathLower());
System.out.println("FILE PATH"+filePath);
System.out.println("Dropbox"+((FileMetadata) metadata).getRev());
System.out.println("Dropbox"+((FileMetadata) metadata).getClientModified());
System.out.println("Dropbox"+((FileMetadata) metadata).getMediaInfo());
System.out.println("Dropbox"+((FileMetadata) metadata).getMediaInfo().getMetadataValue());
System.out.println("Dropbox"+((FileMetadata) metadata).getSharingInfo());
..
Thanks advance
The FileMetadata object that you get back is documented here:
https://dropbox.github.io/dropbox-sdk-java/api-docs/v2.0.x/com/dropbox/core/v2/files/FileMetadata.html
It doesn't offer the additional information you're looking for, and there isn't another way to get it via the API, but we'll consider this a feature request.
You can keep your own file extension to mime type mapping if you'd like though. For example, you can find our groupings for some file types permission here:
https://www.dropbox.com/developers-v1/reference/devguide

java metadata-extractor tag description

I am using the Java library Metadata-extractor and cannot extract the tag
description correctly using the getUserCommentDescription method code below,
although the tag.getDescription does work:
String exif = "File: " + file;
File jpgFile = new File(file);
Metadata metadata = ImageMetadataReader.readMetadata(jpgFile);
for (Directory directory : metadata.getDirectories()) {
String directoryName = directory.getName();
for (Tag tag : directory.getTags()) {
String tagName = tag.getTagName();
String description = tag.getDescription();
if (tagName.toLowerCase().contains("comment")) {
Log.d("DEBUG", description);
}
exif += "\n " + tagName + ": " + description; //Returns the correct values.
Log.d("DEBUG", directoryName + " " + tagName + " " + description);
}
if (directoryName.equals("Exif IFD0")) {
// create a descriptor
ExifSubIFDDirectory exifDirectory = metadata.getDirectory(ExifSubIFDDirectory.class);
ExifSubIFDDescriptor descriptor = new ExifSubIFDDescriptor(exifDirectory);
Log.d("DEBUG","Comments: " + descriptor.getUserCommentDescription()); //Always null.
}
Am I missing something here?
You are checking for the directory name Exif IFD0 and then accessing the ExifSubIFDDirectory.
Try this code outside the loop:
Metadata metadata = ImageMetadataReader.readMetadata(jpgFile);
ExifSubIFDDirectory exifDirectory = metadata.getDirectory(ExifSubIFDDirectory.class);
ExifSubIFDDescriptor descriptor = new ExifSubIFDDescriptor(exifDirectory);
String comment = descriptor.getUserCommentDescription();
If this returns null then it may be an encoding issue or bug. If you run this code:
byte[] commentBytes =
exifDirectory.getByteArray(ExifSubIFDDirectory.TAG_USER_COMMENT);
Do you have bytes in the array?
If so then please open an issue in the issue tracker and include a sample image that can be used to reproduce the problem. You must authorise any image you provide for use in the public domain.

Check if folder exists and if so add "New Folder 2"

I have a web application that I inherited. I am new to Java so don't beat me up too bad. I have the following method to add new folders to an attachment page. User can create new folders on the page and rename, but how do check to see if a "New Folder" already exists and if so create "New Folder (2)" or "New Folder (3)" etc...
Here is my method from my attachments servlet:
protected void newFolderAction(HttpServletRequest request, HttpServletResponse response, User user, String folderId) throws UnsupportedEncodingException,
IOException {
String key = request.getParameter("key");
String value = request.getParameter("value");
Attachment parent = AttachmentRepository.read(UUID.fromString(key));
String path = parent.getPath();
logger.debug("newFolder: key=" + key + " value=" + value + " path=" + path);
if (AttachmentRepository.read(path + "New Folder/") == null) {
long size = 0L;
boolean isFolder = true;
boolean isPicture = false;
UUID attachmentId = UUID.randomUUID();
Attachment attachment = new Attachment(attachmentId, UUID.fromString(folderId), user.getUnitId(), UUID.fromString("11111111-1111-1111-1111-111111111111"), path + "New Folder/", size, isFolder, isPicture,
"", "0", "0", user.getName(), new Date());
AttachmentRepository.add(attachment);
File directory = new File(Settings.instance().getAttachmentsDir() + "/" + attachment.getPath());
directory.mkdirs();
}
Attachment rootAttachment = AttachmentRepository.read(folderId + "/");
writeJsonAttachmentsTree(response, user, request.getRequestURI(), rootAttachment);
}
There is no custom built-in function in Java that create for you directory if the desired name already exists, You should implement one by Yourself.
public static void main(String[] args) {
File folderPath = new File("c:\\New Folder");
// Check whatever folderPath exists
System.out.println(folderPath.getPath() + " is directory ? " + folderPath.isDirectory());
// Create new folder
File folderCreated = createFolder(folderPath);
System.out.println("The new directory path is: " + folderCreated.getPath());
// Check whatever folderPath exists
System.out.println(folderCreated.getPath() + " is directory ? " + folderCreated.isDirectory());
}
public static File createFolder(File path) {
File pathNum = new File(path.getPath());
String num = "";
int i = 1;
do {
pathNum = new File(path.getPath() + num);
num = "(" + ++i + ")";
} while (!pathNum.mkdir());
return pathNum;
}

Categories