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

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;
}

Related

Why do I get, and how do I solve this "String to object of type <objecttype>" error

I am (being an absolute beginner), trying to create a simple tool, that creates some objects and links them.
The objects are:
Customers
Licenses (2 types, extends class)
The idea is to use (one of) the customer company name when creating a license, so the license is linked to a customer.
I use ArrayLists to store the data.
I tried to use the getter for Customer cCompany, but when I try to actually create a new license object, I get errors about incompatible types (String to object of type customer)
How can I fix that error?
Any help is highly appreciated, but please explain well, me being an absolute beginner. I probably overcomplicate stuff....
Some code extracts:
From Main:
public class Main {
public static void main(String[] args) {
//Create customers
List <Customer> customers = new ArrayList <> (10);
customers.add(new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
....
//Create Elvis licenses (based on superclass License)
List <ElvisLicense> ellicenses = new ArrayList <> (10);
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
Class: Customer:
class Customer {
String cCompany;
private String cName;
private int cPhone;
private String cEmail;
public Customer( String cCompany, String cName,int cPhone, String cEmail)
{
this.cCompany = cCompany;
this.cName = cName;
this.cPhone = cPhone;
this.cEmail = cEmail;
}
//This getter should be used to link the license to the customer (Done in License.java)
public String getcCompany() {
return cCompany;
}
Class License (Superclass)
class License {
// Used no modifier to set access for Class/Package and Subclass inside the package
Customer licenseCompany;
String lVendor;
int lContractNumber;
String lCertificateNumber;
String lProductName;
String lLicenseKey;
int lNumberOfSeats;
public License(Customer cCompany, String lVendor, int lContractNumber, String lCertificateNumber,
String lProductName, String lLicenseKey, int lNumberOfSeats)
{
licenseCompany = cCompany;
this.lVendor = lVendor;
this.lVendor = lVendor;
this.lContractNumber = lContractNumber;
this.lCertificateNumber = lCertificateNumber;
this.lProductName = lProductName;
this.lLicenseKey = lLicenseKey;
this.lNumberOfSeats = lNumberOfSeats;
}
public Customer getLicenseCompany() {
return licenseCompany;
}
public void setLicenseCompany(Customer licenseCompany) {
this.licenseCompany = licenseCompany;
}
//preparations to allow for example printing the content of an arraylist element
#Override
public String toString(){
return "Customer name " + getLicenseCompany() + "\n" + "Vendor name " + getlVendor() + "\n" + "Contract number: " + getlContractNumber() + "\n"
+ "Certificate number: " + getlCertificateNumber() + "\n" +
"Product name " + getlProductName() + "\n" + "Licence key: " + getlLicenseKey() + "\n"
+ "Number of seats: " + getlNumberOfSeats();
}
}
And the extended class:
public class ElvisLicense extends License{
private boolean elIsBundle;
private boolean elIsSubscription;
public ElvisLicense(
Customer licenseCompany,
String lVendor,
int lContractNumber,
String lCertificateNumber,
String lProductName,
String lLicenseKey,
int lNumberOfSeats,
boolean elIsBundle,
boolean elIsSubscription
)
{
super(
licenseCompany,
lVendor,
lContractNumber,
lCertificateNumber,
lProductName,
lLicenseKey,
lNumberOfSeats);
this.elIsBundle = elIsBundle;
this.elIsSubscription = elIsSubscription;
}
.....
#Override
public String toString(){
return "Customer name " + licenseCompany + "\n"
+ "Vendor name " + lVendor + "\n"
+ "Contract number: " + lContractNumber + "\n"
+ "Certificate number: " + lCertificateNumber + "\n"
+ "Product name " + lProductName + "\n"
+ "Licence key: " + lLicenseKey + "\n"
+ "Number of seats: " + lNumberOfSeats + "\n"
+ "Number of seats: " + elIsBundle + "\n"
+ "Number of seats: " + elIsSubscription;
}
}
I expect that the Customername is used when creating a new license.
Below line is wrong.
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
As license need customer object an parameter. Instead, you should create customer object first.
ellicenses.add(new ElvisLicense(new Customer("TestCompany","VendorA",1234,"1234-A"),"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
for reusing that customer list to avoid create company.
for(Customer customer : customers){
// here you need some way to offer other parameters except customer parameter.
License license = new new ElvisLicense(customer,"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true);
ellicenses.add(license);
}
What you need to do is to use one of the Customer objects you have already created when creating the ElvisLicense object. To more easily find that customer by name I suggest you store them in a map instead of a list with the name as a key.
Map<String, Customer> customerMap = new HashMap<>();
Customer customer = new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
customerMap.put(customer.getcCompany(), customer);
so when creating the license you look up the customer
List <ElvisLicense> ellicenses = new ArrayList <> (10);
Customer customer = customerMap.get("TestCompany");
if (customer != null) {
ElvisLicense license = new ElvisLicense(customer,"VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
ellicenses.add(license);
} else {
//If the customer isn't found you need some kind of error handling, better than below :)
System.out.println("Can't create a license, no customer found");
}

Get the class name in the #BeforeSuite annotation - TestNG - Java

Is there a way to get the name of the class that the script was started from inside the #BeforeSuite annotation when not executed via xml file?
Doing this:
reportName = new Exception().getStackTrace()[0].getClassName();
returns the class itself that contains the #BeforeSuite annotation and this:
reportName = new Exception().getStackTrace()[1].getClassName();
returns sun.reflect.NativeMethodAccessorlmpl
If I execute a script directly from a separate class, I want to get that info because I am using it to name my Extent Report file name.
In case you are wondering what the code inside the #BeforeSuite annotation looks like:
// Set Extent Report file name from the global properties file
String reportName = ctx.getCurrentXmlTest().getSuite().getName();
if (reportName.equals("Default suite"))
{
reportName = new Exception().getStackTrace()[0].getClassName();
}
String timeStamp = new SimpleDateFormat("HH.mm.ss").format(new Date());
// Initialize Extent Reports and modify the looks/output
String extentReportPath = "";
if (extent == null) {
if (os.equals("Mac"))
{
extentReportPath = reportPath + "/" + project + "-" + reportName + "-" + environment + "-" + browser + "-" + timeStamp + ".html";
}
else if (os.equals("Windows"))
{
extentReportPath = reportPath + "\\" + project + "-" + reportName + "-" + environment + "-" + browser + "-" + timeStamp + ".html";
}
// Start new report
extent = new ExtentReports(extentReportPath, true);
}
There's more to it, but this is the part pertinent to my question.
---UPDATE---
This was my solution:
// Set Extent Report file name from the global properties file
String reportName = ctx.getCurrentXmlTest().getSuite().getName();
if (reportName.equals("Default suite"))
{
List<ITestNGMethod> allMethods = ctx.getSuite().getAllMethods();
for (ITestNGMethod method : allMethods)
{
String fullMethod = method.toString();
int indexOf = fullMethod.indexOf(".");
reportName = fullMethod.replace(fullMethod.substring(indexOf), ""); }
}
You can pass argument ITestContext to the beforesuite method. testNG will auto-inject it. This should have the information you looking for.
context.getSuite().getAllMethods -> List of TestNGMethods.getRealClass() or getTestClass().

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.

weird behaviour of setting new File Name in android

I need to create new file in andorid with Java. I do it like this :
public static File getAbosoluteFile(String relativePath, Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return new File(context.getExternalFilesDir(null), "AE " +".jpg");
} else {
Toast.makeText(context, "internal", Toast.LENGTH_SHORT).show();
return new File(context.getFilesDir(), "AE" +".jpg");
}
}
but when I put it like this - it works properly, but when I change the name , for example using string from the method :
public static String getCurrentDate()
{
String returnDate = null;
Calendar currentDate = Calendar.getInstance();
int minute = currentDate.get(Calendar.MINUTE);
String editedMinute;
if (minute<10)
editedMinute = "0" + Integer.toString(minute);
else
editedMinute = Integer.toString(minute);
returnDate= (Integer.toString((currentDate.get(Calendar.MONTH) + 1)) + "/" +Integer.toString(currentDate.get(Calendar.DAY_OF_MONTH)) + "/" +Integer.toString(currentDate.get(Calendar.YEAR)) + " " +
Integer.toString(currentDate.get(Calendar.HOUR_OF_DAY)) + ":" + editedMinute);
return returnDate;
}
So , even when I use return new File(context.getExternalFilesDir(null), "12/12/12 " +".jpg");
the file is doesn't create too. I tried to use the screening in the name - thought reason is in this, but the same result.
Is Java's new File(File dir, String name) is so depending to the name format? Or what the reason ?
You can't use / in your file name. It is used as a file separator.
For eg.If you have a folder named App in your SD card and in it a sub folder called Sub the path is something like mnt/sdcard/App/Sub(mnt/sdcard is just for example it is not fixed)
So you can see why you can't use / in a file name.
Try using _ in place of /.

NoSuchMethoException on calling DefaultValidator.getValidFileName()

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.

Categories