I am reading a code of java source file. I see the following code lines given below
GWT.runAsync(Overview.class, new LoadAsyncCallback() {
public void onSuccess() {
if (ApplicationDetails.class.getName().equals("1")))
{
...............
}
So my Point is
1. why it use ApplicationDetails.class file to access getName(). as
usually we use Java source file.
2. GWT.runAsync(Overview.class, new LoadAsyncCallback() {
what is the mean of this line.
even when I open ApplicationDetails sourse file i did not find any getName() method .
is there any difference to use class file or java sourse file
Every Class in Java has getName() method.
Read about code splitting in GWT.
Related
I am working on a Java application that will read a file and then after reading it into memory will do further processing .
The requirement for file reading is that the code should read from 'current working directory'.
I have written a method as follows:
public List<String> processFile(String fileName){
String localPath = FileSystems.getDefault().getPath(".").toAbsolutePath() + fileName;
}
This method converts the file into an ArrayList which it returns.
Then using this arraylist further processing needs to be done.
public boolean workOnFile(){
List<String> records = processFile("abc.txt");
// additional logic
}
I am blocked / stumped on how to Junit the file reading part since the requirement is that the file reading needs to occur from 'working directory' so wherever the user will run the program the input file would be read from working directory.
However in case of Junit my test files would be in '\src\main\resources'
As a result test files would not be read by the 'processFile' method since it looks for files in 'current working directory'
One thought is that I need not Junit the file reading but the entire application does something after the file is read - so do I have some 'testing' provisions where while executing Junit I read file in junit and then have provisions in my class under test to inject my testArrayList ?
#Test
public void doSomeValidation() {
String testFile = "XYZ.txt";
ClassUnderTest fixture = new ClassUnderTest();
List<String> testList = /** read file in Junit from /src/main/resources/ **/
/** inject this testList into ClassUnderTest **/
fixture.setFileContent(testList );
/** then continue testing the actual method that needs to be tested **/
assertNotFalse(fixture.workOnFile());
}
To achieve this I would have to change my actual class that needs to be tested to be able to inject the test file read . Something along these lines :
public class ClassUnderTest(){
public List<String> processFile(String fileName){
String localPath = FileSystems.getDefault().getPath(".").toAbsolutePath() + fileName;
}
/** new method used in junit to inject to **/
public void setFileContent(List<String> input){
this.input = input;
}
/** modify this method first check if injected arraylist not null **/
public boolean workOnFile(){
List<String> records;
if(this.input == null){
/** in actual runs this block will execute **/
this.input = processFile("abc.txt");
}
// additional logic
}
}
Is this the right way ?
I somehow feel I am messing around with code to just make it more testable ?
is this even the right approach ?
A simple solution: change your interfaces to be easy to test.
Meaning:
have one method that puts together a file name "in the local path" (the same way your processFile() method builds that file name
then pass the result of that operation to your processFile() method.
In other words: your code limits that method to always compute the full path itself. Which makes it really hard to control, and thus to test.
Thus: dissect your problem into the smallest pieces that are possible.
Then you only need to test:
that your new method Path getLocalPathFor(String fileName) does what it is supposed to do
and then, that your method processFile(Path absFilePath) does what it needs to do (and now, you can test that method with a path that sits anywhere, not just in the local directory)
This question is Java and Maven specific. Please note the additional constraints below as they are different from other questions.
I have several Maven (Java) projects to analyze. What I have is:
the source code
maven-compiled Jave code with binaries in target/ folder
The question is:
Given one source code file (.java) and a line number there, how can I get the fully qualified name of the method that spans over that line? If the line is not in a method then just output null. Acceptable languages to implement this are: Java, ruby, or python.
Could you please answer the question in one of the following two ways?
use the binary and extract qualified method name of that line. (This might involve weave in debug info, but that is fine.)
directly use the source file given, try to parse it and use the AST.
Using specific libraries (like BCEL) or any 3rd party ones (as long as they are well documented and usable) are OK, too.
Many many thanks for the huge help!
Unfortunately, your question is full of drawbacks:
You could, of corse, parse the input source (through an Javacc or ANTLR parser) until you reach the desired line. But it seems a waste of effort to parse the same source since you already have the .class files.
So, it seems better to analyze the .class file. But unfortunately, you have no gurantee that this is the class where your line spawns at, because there can be more than one class defined in the same source file.
Augh! That leads me to a kind of complicated solution:
I'll declare a class which will contain all the login:
public class SourceMethodsIndexer
{
private final SortedMap<Integer, List<Method>> indexOfMethodsByFirstLineNumber;
}
The constructor will be like this:
public SourceMethodsIndexer(File sourceFile)
... and should do these tasks:
1.Browse the class directory related to the target package.
File targetPackageDir=getTargetPackageDir(sourceFile);
File[] classFiles=targetPackageDir.listFiles(new FileFilter(){
public boolean accept(File dir, String name){
return name.endsWith(".class");
}
});
2.Use Apache BCEL to collect all the non public classes belonging to your input source file (you can invoke JavaClass.getSourceFileName() to filter classes), plus the public class corresponding to the name of your input source file.
Collection<JavaClass> targetClasses=getNonPublicClasses(classFiles, sourceFile.getName());
targetClasses.add(publicClass);
3.Collect then all the methods in each class.
Set<Method> targetMethods=new HashSet<Method>(1024);
for (JavaClass javaClass:targetClasses)
{
targetMethods.addAll(Arrays.asList(javaClass.getMethods()));
}
4.Now you can either search directly your line number, or index first the methods by line number to access them later more quickly: JavaClass.getMethods()[n].getLineNumberTable().getSourceLine(0) (take care that there could be repeated values).
this.indexOfMethodsByFirstLineNumber=new TreeMap<Integer, List<Method>>((int)(1.7d*methods.size()));
for (Method method: methods)
{
// Note: The -1 in this line stands to make the SortedMap work properly when searching for ranges.
int firstLine=getLineNumberTable().getSourceLine(0)-1;
List<Method> methodsInTheSameLine=indexOfMethodsByFirstLineNumber.get(firstLine);
if (methodsInTheSameLine==null)
{
methodsInTheSameLine=new ArrayList<Method>();
indexOfMethodsByFirstLineNumber.put(firstLine,methodsInTheSameLine);
}
methodsInTheSameLine.add(method);
}
5.Public a method to do the search:
public Method getMethodByLine(int lineNumber)
{
Set<Method> methodsInTheSameLine=this.indexOfMethodsByFirstLineNumber.headMap(lineNumber).lastKey();
if (methodsInTheSameLine.size()==0)
{
// There are no methods method in that line: Absurd.
}
else if (methodsInTheSameLine.size()>1)
{
// There are more than one method in that line. Hardly probable, but possible.
}
else
{
// There is one method in that line:
return methods.get(0);
}
}
There are a number of open source Maven plugins which analyse source code, and report on a per-method basis. A careful study of some of those may be your best bet.
Examples include Checkstyle, FindBugs, PMD, JDepend, JavaNCSS.
Also take a look at SonarQube.
Let's say for instance I have this scenario
C:\Users\Name\Documents\Workspace\Project\Src\Com\Name\Foo.java
Public class Foo {
public Foo() {
Bar b = new Bar();
b.method();
}
}
Then lets say that class Bar is in a .JAR file that's being used as a library, is it possible to figure out where the class that called method() was from? (in this case, the Foo class)
I've done a little looking around Google and can't find anything, and this code would definately simplify my library quite a bit.
If you need to get path of the caller class file from inside the method Bar#method then you can use something like this:
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
String callerFilePath = getClass().getClassLoader().getResource(stackTrace[1].getClassName().replace('.', '/') + ".class"));
Yes, you can get the path from where the file is being executed. For example, you have the file :
C:\Users\Name\Documents\Workspace\Project\Src\Com\Name\Foo.java
After compiling, it will change to :
C:\Users\Name\Documents\Workspace\Project\Src\Com\Name\Foo.class
You can use this to get the directory of the file:
System.getProperty("user.dir");
and then you can add this String to it:
String cPath = System.getProperty("user.dir")+"\\Foo.class";
Thus, cPath would be the complete path to the file.
You can use Foo.class.getResource("Foo.class") to get the location of the compiled class file. The question is, how will this help you simplify your library?
I need to find out the class name from Java code. For example: The target file is aa.txt, the content of this file is as below:
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World!!!!");
}
}
I want to find out the class name, in this case is HelloWorld so that I can name the .java file as HelloWorld.java.
My question is how can I get Java class name in PHP or JavaScript?
Add:
I will let users to write very simple Java code in my webpage, and I will save their code in files, run their code and return results for them. But right, there may be more than one class in a file.
In PHP:
$source = preg_replace('/\/\*[\s\S]*\*\/|\/\/.*|"(?:\\\\?.)*?"/', '', $source);
if (preg_match('/\bclass\s+(\w+)/', $source, $matches)) {
$className = $matches[1];
}
It strips comments and strings then pulls out the name of the first declared class. (This doesn't handle Unicode escapes but they're probably a non-issue as they're never practically used outside of strings.)
I was doing some work for college and my main runs this:
Spreadsheet sheet = new Spreadsheet(0,0);
SpreadsheetManager manager = new SpreadsheetManager(sheet);
/* Read an Import file, if any */
String filename = System.getProperty("import");
if (filename != null)
sheet.parseInputFile(filename, sheet);
Thing is, when I actually try to import a file it doesn't do what is supposed to and the filename is always null, so it never reaches my parseInputFile.
My teachers made a bunch of code for different programming exercises that do similar things available, and I've also looked at projects my colleagues did in previous years, but every single one does what I am doing above.
I have to run my program like this: java -Dimport=A-002-002-M-ok.import calc.textui.Calc otherwise none of the tests given by the teachers will run.
I'm sorry if this is not a useful question, but I've tried looking everywhere. If anyone could explain how the System.getProperty("import") works and why it isn't working in this case, I would be very grateful.
I suggest you take a look at the documentation of System.getProperty().
Basically it retrieves a value from the system, either already present or set by you.
To avoid retrieving null you can use another method signature that specify a default value:
System.getProperty("import", "file.txt");
To set a System property, you can specify it at launch:
java -Dimport="file.txt" your_application
or set it programatically :
System.setProperty("import", "file.txt");
When you run your program with:
java -Dimport=foo
then the method call
System.getProperty("import")
should return "foo".
Is ist possible that you write a tiny example program to convince yourself? Without any SheetManagers and all stuff, just
class ItWorks {
public static void main(String[] args) {
System.out.println(System.getProperty("import"));
}
}
Call it thus
java -Dimport=indeed ItWorks
and report what happens.
That being said: if you want to pass command line arguments, why don't you use the facility for command line arguments? (i.e. the String[] array passed to main?)
You could then call your program like this:
java calc.textui.Calc my-nice-spreadsheet.data
=====================================================
Please write the follwoing in your calc.textui.Calc program immediately after the open brace of your class definition:
public class Calc ..... { // a line like this already exists
// insert next line here
public static String filename = System.getProperty("import");
// rest of your class, as before.
}
Then comment out the getProperty() line in your method that didn't work, but leave the rest including the System.out.println(filename);
Does it change?
Maybe system properties are not the most indicated way to do that (depends on your application).
You could also use command line arguments to pass the file name to your main method:
public class CommandLineExample {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("usage: CommandLineExample <filename>");
System.exit(1);
}
String filename = args[0];
if (filename !=null && !filename.isEmpty()) {
...
}
}
}
Your program should be called as:
java CommandLineExample theFileName
the string "theFileName" will be passed to the main method in args[0] (any additional words will be passed in subsequent positions of args {args[1], args[2], ...})
EDIT
if the program must be called with
java -Dimport=filename ...
then System.getProperty("import") will return the filename.
Confirm that you are calling the correct program (class name, package, version, last compile was successful, ...) and also check that the property is not mistyped like java -Dinport=A-... or has additional spaces, uppercase letters...