Spring java.lang.NoClassDefFoundError error - java

I am new to spring framework and following the tutorial on tutorialspoint.com. After including every thing, while running the program it gives me following error:
Error: Unable to initialize main class com.raza.spring.MainApp
Caused by: java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
Below is my project structure:
enter image description here
Here is the code:
Class Hello:
package com.raza.spring;
public class Hello {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
}
Class MainApp:
package com.raza.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Hello obj = (Hello) context.getBean("helloWorld");
obj.getMessage();
}
}
Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.raza.spring.Hello">
<property name = "message" value = "Hello raza world !!!"/>
</bean>
</beans>
Not able to get what is wrong here. Thanks in advance.
I am trying tutorial on tutorialspoint.com and expecting an output on the console.

java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext tells that the Class you are using in your code is not accessible from your project.
In previous chapter on https://www.tutorialspoint.com/spring/spring_environment_setup.htm you probably downloaded spring library in step 4. Try adding it to your classpath: https://wiki.eclipse.org/FAQ_How_do_I_add_an_extra_library_to_my_project%27s_classpath%3F.
I highly recommend you start using maven. It allows you to add external libraries a lot easier, without having to manually download them from a git repo or a website.
Also, check the Baeldung courses. Their examples always use the latest Spring version https://www.baeldung.com/spring-tutorial

Related

How to add properties file to Spring XML context?

Here is the structure of sample Spring application
src
main
my.example
- MyBean.java
- AppMain.java
resources
- applicationContext.xml
- some.properties
applicationContext.xml
<beans ...>
<context:property-placeholder location="classpath:some.properties"/>
<bean id="a" class="my.example.MyBean"/>
</beans>
some.properties
myprop=something
AppMain.java
public class AppMain {
public static void main(String[] args) {
var context = new ClassPathXmlApplicationContext();
context.setConfigLocations("classpath:applicationContext.xml");
context.refresh();
var bean = context.getBean("a");
println(bean); // available
ConfigurableEnvironment environment = context.getEnvironment();
String javaHome = environment.getProperty("java.home");
String myprop = environment.getProperty("myprop");
println(environment.getPropertySources());
println("javaHome is " + javaHome); // ok
println("myprop is " + myprop); // is null
}
}
Output:
my.example.MyBean#cecf639
[PropertiesPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}]
javahome is [/mypath/to/java/17.0.5-zulu]
myprop is [null]
As the output shows the property sources do not contains some.properties file, and hence myprop is null. At the same time the bean MyBean is available, which means applicationContext.xml was processed.
Why <context:property-placeholder ...> had no effect?
How to add some.properties file to the context, and get correct myprop value?

Saxon-HE Java Extension Functions (Problem configuring)

I currently use Saxon9 open source version with extensions written in Java. I am trying to migrate to SaxonHE and I have read the documentation and examples shown here.
Java extension functions: full interface
and
Saxon Configuration File
When I try and execute my XSLT transformation I get errors like this when it encounters one of my external java functions.
XPST0017: Cannot find a 2-argument function named
Q{http://com.commander4j.Transformation.XSLT_Ext_NVL}nvl()
So here is what I've done so far.
My java extension function is written like this.
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;
public class XSLT_Ext_NVL extends ExtensionFunctionDefinition
{
#Override
public SequenceType[] getArgumentTypes()
{
return new SequenceType[]{SequenceType.SINGLE_STRING, SequenceType.SINGLE_STRING};
}
#Override
public StructuredQName getFunctionQName()
{
return new StructuredQName("c4j_XSLT_Ext_NVL", "http://com.commander4j.Transformation.XSLT_Ext_NVL", "nvl");
}
#Override
public SequenceType getResultType(SequenceType[] arg0)
{
return SequenceType.SINGLE_STRING;
}
#Override
public ExtensionFunctionCall makeCallExpression()
{
return new ExtensionFunctionCall() {
#Override
public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {
String value = ((StringValue)arguments[0]).getStringValue();
String defaultValue = ((StringValue)arguments[1]).getStringValue();
String result = "";
if (value == null)
{
value = "";
}
result = value;
if (result.equals(""))
{
result = defaultValue;
}
return StringValue.makeStringValue(result);
}
};
}
}
I have created a Saxon configuration file which looks like this. My example looks a little different than the example on the Saxon website as that example includes the function name after the class name separated by a $ - when I tried it I got an error message that Saxon could not find the class.
edition="HE"
licenseFileLocation=""
label="c4jMiddleware">
<resources>
<extensionFunction>com.commander4j.Transformation.XSLT_Ext_NVL</extensionFunction>
</resources>
</configuration>
I am loading Configuration using this syntax.
Source xmlSource = new StreamSource(new File(System.getProperty("user.dir") + File.separator + "xml" + File.separator + "config" + File.separator +"SaxonConfiguration.xml"));
Configuration.readConfiguration(xmlSource);
Below is an extract from my XSLT which tries to invoke the java function.
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:c4j="http://www.commander4j.com"
xmlns:c4j_XSLT_Ext_NVL="http://com.commander4j.Transformation.XSLT_Ext_NVL"
xmlns:c4j_XSLT_Ext="http://com.commander4j.Transformation.XSLTExtension"
exclude-result-prefixes="xs c4j c4j_XSLT_Ext" version="2.0">
<xsl:output encoding="UTF-8" indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>
.
.
.
<xsl:template match="xml">
<xsl:param name="pack_conv" select="c4j_XSLT_Ext_NVL:nvl($pack_conv_temp, '1')"/>
If someone could give me a clue as to where I've gone wrong it would be most appreciated.
Dave
As Martin suggests, the most likely explanation is that you are not actually using the configuration you have created by reading the configuration file.

Alternate for DigesterLoader.createDigester(url) in digester3

To be precise my question would be what is the alternate method for Digester.createLoader(url) in new Digester3?
commons-digester:1.8.1 code
URL url;
ClassLoader curClassLoader = this.getClass().getClassLoader();
url = curClassLoader.getResource("filepath");
if (url != null) {
Digester tempDigester = DigesterLoader.createDigester(url);
----
----
}
Now I have upgraded commons-digester-1.8.1 to org.apcahe.commons.Digester3-3.2 and in new jar I don't see any method as createDigester(ur);
How can I replace DigesterLoader.createDigester(url) using new API to get Digester object in return.
commons-digester:3.2 code
URL url;
ClassLoader curClassLoader = this.getClass().getClassLoader();
url = curClassLoader.getResource("filepath");
if (url != null) {
Digester tempDigester = ???;
----
----
}
Thanks in advance.
Haven't checked exactly what the 1.8 version does, but assuming your URL resolves to a stream of XML based rules then something like this should do the trick:
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.apache.commons.digester3.binder.RulesModule;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
final URL url = curClassLoader.getResource("filepath");
RulesModule rules = new FromXmlRulesModule() {
#Override
protected void loadRules() {
loadXMLRules(url);
}
};
DigesterLoader loader = DigesterLoader.newLoader(rules);
Digester digester = loader.newDigester();
Note you probably have to make your URL final to use it within the anonymous subclass.
Tested with the following simple rules file:
<?xml version='1.0'?>
<!DOCTYPE digester-rules PUBLIC '-//Apache Commons //DTD digester-rules XML V1.0//EN' 'http://commons.apache.org/digester/dtds/digester-rules-3.0.dtd'>
<digester-rules>
<pattern value='data'>
<object-create-rule classname='test.digester.BasicTest$ClassA'/>
<bean-property-setter-rule pattern='name' propertyname='name'/>
</pattern>
</digester-rules>
Requires the DOCTYPE declaration, but works with or without the XML declaration. Running without the DOCTYPE gives:
Parse Error at line 1 column 17: Document root element "digester-rules", must match DOCTYPE root "null"

How to get a service bean inside a custom tag library class in Grails 3

I want to get a service bean from the application context inside my custom tag library. The service name i will get it from the custom tag attribute.
This is the code i previously used.
class CustomTagLib {
static defaultEncodeAs = [taglib:'html']
//static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
def selectList = { attrs ->
try{
String servName=attrs.service
String servMethod=attrs.method
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext())
def myservice=ctx."${servName}"
attrs.from = myservice.invokeMethod(servMethod,null);
out << g.select( attrs )
}catch(Exception e){
println("Exception in CustomTagLib in method selectList:"+e)
}
}
}
This code is worked me for Grails 2.3 version but not for version 3.
Please help me to find out a solution.
Try the following:
import grails.util.Holders
def myservice = Holders.getApplicationContext().getBean( servName )
Where servName would be your service name with lowercase first letter & camel case for the remainder

java and air integration ,the error is "3214 NativeProcessStartupInfo.executable does not specify a valid executable file. " on Windows machine

Below is my JavaProcess.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="windowedapplication1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.controls.Alert;
protected var process:NativeProcess;
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
var info:NativeProcessStartupInfo = new NativeProcessStartupInfo();// holds all info about native process
info.executable = new File("C:/Program Files/Java/jre1.6.0_22/bin"); // unix "/usr/bin/java"
//window program files/java
info.workingDirectory= File.applicationDirectory;
var args:Vector.<String> = new Vector.<String>();
args.push("-cp","../bin","net.riaspace.Main");
info.arguments = args;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA,onDataOutput);
// this method will be fired when anything comes from java
process.start(info);
}
private function onDataOutput(event:ProgressEvent):void
{
var message:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
Alert.show(message);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Button label="call java" click="process.standardInput.writeUTFBytes('hello\n')"/>
</s:WindowedApplication>
And My Main.Java is
package net.riaspace;
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input;
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext("Hello|stop"))
{
input = scanner.next();
if(input.equals("hello"))
{
System.out.println("Hello Flex");
}
else if(input.equals("stop"))
{
return;
}
}
}
}
NativeProcessStartupInfo.info The
File object that references an
executable on the host operating
system. This should be the full path
to the executable including any
extension required.
It looks like you are missing a reference to your .exe file.
I found an open source project " Flerry " to integrate Flex and Java Integration
Below is the link , it works for me.
http://www.riaspace.com/tag/java/

Categories