Spring HelloWorld Program not giving output - spring

ApplicationContext context = new ClassPathXmlApplicationContext("HelloWorldBean.xml");
HelloWorld h1 = (HelloWorld) context.getBean("b1");
h1.getMsg();
h1.getName();
Here all things are good, maven dependencies are added , but this getMsg or getName method not giving any output.
If I write
System.out.println(h1.getMsg() + h1.getName() );
It will give value of msg and name variable.
What is wrong in this can anybody help?

In pojo , getMsg should have System.out.println(msg); then it will print, otherwise you have to manually put getMsg method to **sysout* as you shown.

Related

How can i Print own Error Message on Java Jar CMD

how can I Print adittional information to Command line Console?
Output now is:
C:\Users\admin\Desktop\java>java -jar pdf.jar
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at readDataIn.main(readDataIn.java:31)
Code:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
try {
String arg = args[0];
fileNameSource = "import/" + arg + ".xml";
fileNameTarget = "export/" + arg + ".pdf";
} catch (Exception e) {
// TODO: handle exception
**System.out.println("Personal-Number is missing");**
e.printStackTrace();
}
How can i give the information out, that the Personal Number ist Missing?
First of all, as a general rule you should check for possible exceptions before they actually occur if that is possible, which in your case it definitely is.
So instead of catching the ArrayIndexOutOfBounds insert an if statement that checks the length of the args array before accessing it.
if(args.length == 0){
// no argument has been provided
// handle error here
}
In terms of how to handle the error, there are many options available and depending of what you want to do either could be a good fit.
IllegalArgumentException
It is a common idiom in Java that whenever a function receives an invalid/ illegal argument to throw an IllegalArgumentException.
if (args.length == 0){
throw new IllegalArgumentException("Personal number is missing");
}
This will print the message that you have provided and the stack trace. However if your application should be a Command Line Interface (CLI) you should not use this kind of error handling.
Print message & exit program
if (args.length == 0){
// notice: "err" instead of "out": print to stderr instead of stdout
System.err.println("Personal number is missing");
// exit program with non-zero exit code as exit code == 0 means everything is fine
System.exit(1);
}
For more information on stdout and stderr see this StackOverflow question.
This is what many CLI applications and e.g. java itself does. When you type java fdsdfsdfs or some similar nonsense as an argument Java will give you an error message and exit with some non-zero return code ("1" in this case).
It is also common that CLI applications print an error message and following some usage information on how to correctly use the application or provide a help command so a user can get more information. This happens for example if you just enter java without any parameters.
So it is really up to you what you want to do.
If you are thinking of implementing a full featured CLI application with more (complex) commands with multiple options etc. you should consider using a CLI library like JCommander or Apache Commons CLI as parsing command line arguments can quickly get ugly. All these common things are already handled there.
Logging
In case your application is some script that will be executed in a non-interactive way logging the error to a file and exiting with a non-zero exit code might also be an option.
PS
Your code looks to me like it should not compile at all as you are not declaring a type for your variables fileNameSource and fileNameTarget.
Use String or var here (assuming you're running > Java 11).
String fileNameSource = "import/" + arg + ".xml";
var fileNameTarget = "export/" + arg + ".pdf";
You might also need to consider that your program name is part of the args array, so you might have more than 0 values in the array and therefore might need to adjust the if statements above.
You may be interested in picocli, which is a modern CLI library for Java and other JVM languages.
Picocli does some basic validation automatically, and results in very compact code that produces user-friendly applications. For example:
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
#Command(name = "myapp", mixinStandardHelpOptions = true, version = "1.0",
description = "This command does something useful.")
class MyApp implements Runnable {
#Parameters(description = "File name (without extension) of the file to import and export.")
private String personalNumber;
#Override
public void run() {
String fileNameSource = "import/" + personalNumber + ".xml";
String fileNameTarget = "export/" + personalNumber + ".pdf";
// remaining business logic
}
public static void main(String[] args) {
System.exit(new CommandLine(new MyApp()).execute(args));
}
}
If I run this class without any parameters, the following message is printed to the standard error stream, and the process finished with exit code 2. (Exit codes are customizable.)
Missing required parameter: '<personalNumber>'
Usage: myapp [-hV] <personalNumber>
This command does something useful.
<personalNumber> File name (without extension) of the file to import
and export.
-h, --help Show this help message and exit.
-V, --version Print version information and exit.
The usage help message is created automatically from the descriptions of the command, and the descriptions of its options and positional parameters, but can be further customized.
Note how the mixinStandardHelpOptions = true annotation adds --help and --version options to the command. These options are handled by the library without requiring any further logic in the application.
Picocli comes with an annotation processor that makes it very easy to turn your application into a native image with GraalVM. Native images have faster startup time and lower runtime memory overhead compared to a Java VM.

Boot M5 Bug: server.session.persistent is defaulting on, and ignoring false

Any suggestions on where to better post M5 bugs is appreciated. Test passes on latest 1.2.6, fails on 1.3.0.M5. Steps to reproduce:
1. Create a web starter project using 1.3.0.M5
2. Add a simple test method to add a session variable
3. Start the server on either your desktop, or targeted platform (linux)
4. Hit the endpoint a few times.
5. restart the container.
6. hit it again, note the counter continues on
Anything like the following will suffice to test. Another tip if figured out while using Boot: always run with -Djava.io.tmpdir="target" . This will make troubleshooting "hidden" files a lot easier
#RequestMapping("/addSessionVar")
public String addSessionVar( HttpSession session) {
if ( session.getAttribute( SAMPLE_SESSION_VAR ) == null ) session.setAttribute( SAMPLE_SESSION_VAR, new AtomicInteger(0) );
AtomicInteger val = (AtomicInteger ) session.getAttribute( SAMPLE_SESSION_VAR ) ;
int curValue = val.incrementAndGet() ;
logger.info( "Updated session variable {} : {}", SAMPLE_SESSION_VAR, curValue ) ;
return "Updated session variable " + SAMPLE_SESSION_VAR + " to: " + curValue ;
}
The property to configure session persistence is server.session.persistent, not server.session.persist. It defaults to false unless you have Spring Boot's DevTools on the classpath.
If you're seeing behaviour that's at odds with this please open an issue.

fail to use invokeExact of MethodHandle on dynamic load class object

I have some demo code as follwing.
Class<?> myClass = cl.loadClass("com.hp.ac.scriptengine.test." + generateClassName);
Object my_obj = myClass.newInstance();
MethodType mt;
MethodHandle mh;
MethodHandles.Lookup lookup = MethodHandles.lookup();
mt = MethodType.methodType(void.class, int.class);
mh = lookup.findVirtual(my_obj.getClass(), "ToDoit", mt);
mh.invokeExact(my_obj,1);
here '"com.hp.ac.scriptengine.test." + generateClassName' is a generated class.
I got the message as follows.
java.lang.invoke.WrongMethodTypeException: (I)V cannot be called as (Ljava/lang/Object;I)V
at com.hp.ac.scriptengine.test.compliebyCommandline.main(compliebyCommandline.java:138)
Here line 138 is mh.invokeExact(my_obj,1);'
I tried that demo code(such as ... mh.invokeExact("daddy",'d','n')...) in Java 7 API document. It works fine. Such call(mh.invokeExact("daddy",'d','n'))just invoke (CC)Ljava/lang/String other than (Ljava/lang/String;CC)Ljava/lang/String.
But why, in my code, mh.invokeExact(my_obj,1) invoke (Ljava/lang/Object;I)V other than (I)V ?
I think the problem is with int.class. Try Integeer.class or Integer.TYPE instead.

TRttiMethod::Invoke use

I would like to know how to use the Invoke method of the TRttiMethod class in C++Builder 2010.
This is my code
Tpp *instance=new Tpp(this);
TValue *args;
TRttiContext * ctx=new TRttiContext();
TRttiType * t = ctx->GetType(FindClass(instance->ClassName()));
TRttiMethod *m=t->GetMethod("Show");
m->Invoke(instance,args,0);
Show has no arguments and it is __published. When I execute I get a EInvocationError with message 'Parameter count mismatch'.
Can someone demonstrate the use of Invoke? Both no arguments and with arguments in the called method.
Thanks
Josep
You get the error because you are telling Invoke() that you are passing in 1 method parameter (even though you really are not, but that is a separate bug in your code). Invoke() takes an OPENARRAY of TValue values as input. Despite its name, the Args_Size parameter is not the NUMBER of parameters being passed in, but rather is the INDEX of the last parameter in the array. So, to pass 0 method parameters to Show() via Invoke(), set the Args parameter to NULL and the Args_Size parameter to -1 instead of 0, ie:
Tpp *instance = new Tpp(this);
TRttiContext *ctx = new TRttiContext;
TRttiType *t = ctx->GetType(instance->ClassType());
TRttiMethod *m = t->GetMethod("Show");
m->Invoke(instance, NULL, -1);
delete ctx;
Now, once you fix that, you will notice Invoke() start to raise an EInsufficientRtti exception instead. That happens when Runtime Packages are enabled. Unfortunately, disabling Runtime Packages will cause TRttiContext::GetType() to raise an EAccessViolation in TRttiPool::GetPackageFor() because of a known linker bug under C++:
QC #76875, RAID #272782: InitContext.PackageTypeInfo shouldn't be 0 in a C++ module:
Which causes these bugs:
QC #76672, RAID #272419: Rtti.pas is unusable in a C++ application
QC #76877, RAID #272767: AV in TRttiContext::GetType() when Runtime Packages are disabled
So you are in a catch-22 situation. The new RTTI system is not ready for production work in C++ yet. You will have to use Delphi instead for the time being.

Jython, ImageInfo

I trying to use ImageInfo and Jython to get information from a image on my harddrive.
I have imported the module fine but keep getting this error:
TypeError: setInput(): expected 2 args; got 1
And this is the code I am trying to use:
filename = "C:\\image.jpg"
img = ImageInfo.setInput(filename)
Could anyone point out what I am doing wrong.
Cheers
Eef
The missing argument Jython complains about is the ImageInfo object itself, which doesn't exist yet. You must construct it first. So:
filename = "C:\\image.jpg"
ii = ImageInfo()
img = ii.setInput(filename)
or
filename = "C:\\image.jpg"
img = ImageInfo().setInput(filename)
may work also.

Resources