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().
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
I am writing a java application using Vertx. I am trying to deploy one of my modules using the following code. But I am facing IllegalArgumentException, which I am not able to solve.
Part of my main class:
System.out.println(System.getProperty("user.dir")
+ File.separator + "modules" + File.separator
+ "agents-0.0.1-SNAPSHOT-mod.zip");
InputStream agf = new FileInputStream(System.getProperty("user.dir")
+ File.separator + "conf" + File.separator
+ "dbproperties1.json");
String json = IOUtils.toString( agf );
LOGGER.debug("db json:::"+json);
JsonObject configprop = new JsonObject(json);
pm.deployModuleFromZip(System.getProperty("user.dir")
+ File.separator + "modules" + File.separator
+ "agents-0.0.1-SNAPSHOT-mod.zip", configprop, 1,
new AsyncResultHandler<String>() {
public void handle(AsyncResult<String> asyncResult) {
LOGGER.debug("Deployment agnet ID dddd");
if (asyncResult.succeeded()) {
LOGGER.debug("Deployment agnet ID is "
+ asyncResult.result());
} else {
LOGGER.debug("Deployment agnet ID is null "
+ asyncResult.result());
asyncResult.cause().printStackTrace();
}
}
});
agf.close();
The error in the console is as follows:
java.lang.IllegalArgumentException: 'other' has different root
at sun.nio.fs.WindowsPath.relativize(WindowsPath.java:392)
at sun.nio.fs.WindowsPath.relativize(WindowsPath.java:44)
at org.vertx.java.platform.impl.DefaultPlatformManager.setPathResolver(DefaultPlatformManager.java:1128)
at org.vertx.java.platform.impl.DefaultPlatformManager.access$2000(DefaultPlatformManager.java:55)
at org.vertx.java.platform.impl.DefaultPlatformManager$18.run(DefaultPlatformManager.java:1276)
at org.vertx.java.core.impl.DefaultContext$3.run(DefaultContext.java:171)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:353)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:366)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101)
at java.lang.Thread.run(Thread.java:745)
Any help in this regard will be appreciated.
I found the solution for my case.
For a vertx project, there will be mod.json file in the project. It should have the following json.
{
"main": "com.company.agent.Manager",
"preserve-cwd": true
}
"preserve-cwd": true does the help.
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 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 /.
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;
}