How to read data of CtMethod - java

Greetings I'm would like to read the data of a method I try to change with Bytecode manipulation with javassist and a java agent.
The reason is that my program (a webApplication) won't work (javassist.CannotCompileException: [source error] ) is missing what is this?)
and no one could help me at the moment .
So I wanna no what is inside my Methode maybe something produces a bug ... so I want to know if I can read and print the content of a CtMethod
My code
private byte[] transformClass(Class classToTransform, byte[] b, String className) {
if (className.startsWith("de/example")) {
ClassPool pool = ClassPool.getDefault();
CtClass cl = null;
try {
cl = pool.makeClass(new ByteArrayInputStream(b));
} catch (IOException e) {
e.printStackTrace();
}
try {
assert cl != null;
for (CtMethod ctMethod : cl.getMethods()) {
changeMethod(ctMethod);
System.out.println(ctMethod.getMethodInfo());
System.out.println(ctMethod.getMethodInfo2());
}
b = cl.toBytecode();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cl != null) {
cl.detach();
}
}
}
return b;
}
private void changeMethod(CtMethod method) throws NotFoundException, CannotCompileException {
if (method.hasAnnotation(Loggable.class)) {
System.out.println(method.getMethodInfo());
System.out.println(method.getMethodInfo2());
method.insertBefore(" startTime = 0;\n" +
" startTime = System.currentTimeMillis();\n" +
" final de.example.webservice.ws.TestFolder.Logging threadLogger = de.example.webservice.ws.TestFolder.Logging.getInstance();\n" +
" Thread thread1 = new Thread(new Runnable(){\n" +
" #Override\n" +
" public void run() {\n" +
" threadLogger.info(\"Testlog\");\n" +
" try {\n" +
" threadLogger.logCall(Webservice.this.getClass().getMethod(\"startThread0\"),\"Thread\");\n" +
" } catch (Exception e) {\n" +
" e.printStackTrace();\n" +
" }\n" +
" }\n" +
" });\n" +
" thread1.start();");
}
}
I just Methods at google who can read data from files like a .txt file but that isn't usefull for my problem.

If you're trying to read the original source of the method, javassist doesn't really do that. You need a java bytecode decompiler. Google for that term. jad is a good one.

Related

Looping Main Method while Writing Output Data to TXT File

So, I am working on a java project that is concerned with genetic algorithm.
I have a main method that calls a function (Let's call it function 1) that calculates through until the specified iterations. I wanted to run the main method 100 times and collect the data, so I decided to use FileWriter inside the function 1 that I am calling in my main method.
public static int Runcnt = 0;
static int o = 0;
public static File statText = new File("C:\\Users\\ShadyAF\\Desktop\\StatTest.txt");
public static void main(String [] args){
while(Runcnt <= 100)
{
final long startTime = System.nanoTime();
MainAlgorithm mA = new MainAlgorithm("config.xml");
mA.cMA();
final long duration = System.nanoTime() - startTime;
System.out.println(duration/1000000000 + " seconds");
o = 0;
}
The above snippet of code is the main that I'm trying to loop. (function 1)
System.out.println("best = "+Main.indx+" = "+Main.val);
System.out.println("max_cnt: " + Main.max_cnt);
try {
FileOutputStream is = new FileOutputStream(Main.statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("#" + Main.Runcnt + " Best#: " + Main.indx + " BestScore: " + Main.val + " MaxCnt: " + Main.max_cnt + "\n");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to file.");
}
The above snippet of code is the mA.cMa() function that is inside the main loop.
I ran the code for a while and it appears that the program writes to the file only for the first loop and does not do anything for the rest of the looops.
Any help is much appreciated!
Edit: Why am I getting downvoted? At least leave a helpful comment :/
You should change your pattern from scratch... anyway you can try with something like this in your Main:
public static Path pathFile = Paths.get("C:\\Users\\..blah..\\stats.txt");
Then use in your loop
try {
String log = "#" + Main.Runcnt + " Best#: " + Main.indx + " BestScore: " + Main.val + " MaxCnt: " + Main.max_cnt + "\n";
Files.write(Main.pathFile, log.getBytes(), Files.exists(Main.pathFile) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (IOException e) {
// exception handling
}
It is not so efficient, in particular in case of lot of records but whole code you wrote should need strong refactoring too :)

Store 'Data' in a HashMap after every Test Execution (TestNG Class)?

Is it possible to store all test cases which have failed in a hashmap, and then call all values stored in the map at the end of a class?
Variable:
private HashMap<String, Integer> serverStatusMap = new HashMap<String, Integer>();
After Method Code:
#AfterMethod
public void trackServerStatus(ITestResult testResult) {
if (testResult.getStatus() == ITestResult.FAILURE) {
try {
String testName = this.getClass().getSimpleName().toString();
int serverStatus = ServerStatus.getResponseCode(basePage.getCurrentURL());
int i = 0;
while(i < serverStatusMap.size()) {
serverStatusMap.put(testName, serverStatus);
i++;
}
//serverStatusMap.put(testName, serverStatus);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Calling the stored values in the map After class:
#AfterClass
public void sendEmailBasedOnFailure(ITestContext context) throws WebDriverException, Exception {
String tempTime = new SimpleDateFormat("hh.mm.ss").format(new Date());
if(context.getFailedTests().size() > 0) {
SendEmailFile.sendEmailReport(
"TIME: " + tempTime + " | " + this.getClass().getPackage().toString(),
"TIME: " + tempTime + " | " + this.getClass().getPackage().toString() + " | " + "CLASS NAME: "
+ this.getClass().getSimpleName().toString() + "\n\n" +
"TOTAL NUMBER FAILED TESTS: " + context.getFailedTests().size() + "\n\n" +
"FAILED TEST CASES: " + context.getFailedTests().getAllMethods().toString() + "\n\n" +
serverStatusMap.toString());
}
Look at the last line of code: 'serverStatusMap.toString()'
Current Output of the Map:
{}
I do not understand what you are trying to do.
Do you want to send an email with failed tests?
Why not using the appropriate features like Listener or Reporter?
Have a look on the documentation about logging.
You have initialized variable "serverStatusMap". From below code
int i =0;
while(i < serverStatusMap.size()) {
serverStatusMap.put(testName, serverStatus);
i++;
}
I can see that i=0 and also serverStatusMap.size()=0. So it will never enter in while loop. so Finally when you print map there is nothing inside map. You need to change your while condition.

Request parameters coming from jsps are changed when two different users access the code same time

public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.

How to find count of files inside a folder in svn

I want to find the count of files inside the svn. i know how to check is it a file or directory.
try {
nodeKind = repository.checkPath("", -1);
} catch (SVNException ex) {
Logger.getLogger(Reassignscreen.class.getName()).log(Level.SEVERE, null, ex);
}
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
commitClient.doMkDir(new SVNURL[]{SVNURL.parseURIDecoded(url)}, "New Folder");
}
Like this is there any way to retrieve the count of files inside the svn.
Use this code it will help you,
public class DisplayRepositoryList{
static int xmlfilecount = 0;
static ArrayList<String> imagefoldercheck = new ArrayList<String>();
public static void displayrepositorytree(String url, String name, String password) {
xmlfilecount =0;
SVNSetupLibrary.setupLibrary();
SVNRepository repository = null;
try {
repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
} catch (SVNException svne) {
System.err.println("error while creating an SVNRepository for location '" + url + "': " + svne.getMessage());
// System.exit(1);
}
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
repository.setAuthenticationManager(authManager);
try {
SVNNodeKind nodeKind = repository.checkPath("", -1);
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
// System.exit(1);
} else if (nodeKind == SVNNodeKind.FILE) {
System.err.println("The entry at '" + url + "' is a file while a directory was expected.");
// System.exit(1);
}
System.out.println("Repository Root: " + repository.getRepositoryRoot(true));
System.out.println("Repository UUID: " + repository.getRepositoryUUID(true));
System.out.println("");
imagefoldercheck = new ArrayList<String>();
listEntries(repository, "");
} catch (SVNException svne) {
System.err.println("error while listing entries: "
+ svne.getMessage());
}
/*
* Gets the latest revision number of the repository
*/
long latestRevision = -1;
try {
latestRevision = repository.getLatestRevision();
} catch (SVNException svne) {
System.err.println("error while fetching the latest repository revision: "
+ svne.getMessage());
// System.exit(1);
}
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("Repository latest revision: " + latestRevision);
}
/*
* Initializes the library to work with a repository via
* different protocols.
*/
public static void listEntries(SVNRepository repository, String path)
throws SVNException {
Collection entries = repository.getDir(path, -1, null,
(Collection) null);
Iterator iterator = entries.iterator();
while (iterator.hasNext()) {
SVNDirEntry entry = (SVNDirEntry) iterator.next();
if (entry.getName().endsWith(".xml")) {
System.out.println(entry.getName() + " " + xmlfilecount);
xmlfilecount = xmlfilecount + 1;
imagefoldercheck.add(entry.getName());
}
System.out.println("imagefoldercheck --> "+imagefoldercheck);
/*
* Checking up if the entry is a directory.
*/
if (entry.getKind() == SVNNodeKind.DIR) {
listEntries(repository, (path.equals("")) ? entry.getName()
: path + "/" + entry.getName());
}
}
}
}

Method that returns null is causing java.lang.NullPointerException

I wrote this method:
#Override
protected String call() {
if (list != null) {
int s = list.size();
Metadata metadata;
for (int i = 0; i < s; i++) {
try {
File f = list.get(i);
metadata = ImageMetadataReader.readMetadata(f);
// obtain the Exif directory
ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
// query the tag's value
Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: " + sdf.format(date));
} else {
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Error: " + ex.getLocalizedMessage());
} finally {
updateProgress(i + 1, s);
}
}
}
return null;
}
Method directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL) can sometimes return null:
Source
Problem is that by just calling that method java throws Null Pointer Exception, so I cannot test it with date!=null. NetBeans also reports "Dereferencing possible null pointer" hint. I do not understand why this happens. Why I'm not able to store null value in some object and test it? Even if I don't store value in variable, that method still causes the same exception when returning null.
One solution to this problem would be using another catch statement for NullPointerException, then calling the code you would call if the Date was null. You would also have to move variable "File f" out of the try-statement block to ensure access in the catch.
Example,
catch(NullPointerException e) {
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
}

Categories

Resources