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 /.
Related
I was trying to reload config.yml file on command with Bukkit Plugin, I don't know how to do it.
I searched on google and I found one answer, but when I used it, config.yml was not generating. Here's my code:
BlockChanger
Please help
First you need to remove the final modifier from your config variables, else this can't refresh from config file.
Then you need a method for reload the config and set the config variables again. An example based on your code:
#Override
public void onEnable() {
loadConfig(this);
}
private final String prefix = ChatColor.AQUA + "[";
private String prefixTrue;
private String prefixFalse;
public void loadConfig(Plugin plugin) {
File file = new File(plugin.getDataFolder().getAbsolutePath() + "/config.yml");
FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
prefixTrue = prefix + cfg.getString("prefix") + "]" + ChatColor.GREEN + " ";
prefixFalse = prefix + cfg.getString("prefix") + "]" + ChatColor.RED + " ";
}
Make sure that you call the method loadConfig in onEnable and every time you want to reload the config
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().
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.
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;
}
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.