I am trying to create my first Spring app. It is showing the following error:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:73)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:61)
at com.spring1.FirstSpring1.main(FirstSpring1.java:20)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
... 4 more
GetterSetter.java
package com.spring1;
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public void displayInfo()
{
System.out.println("hello "+name);
}
FirstSpring1.java
package com.spring1;
public static void main(String[] args)
{
GetterSetter gt=new GetterSetter();
gt.setName("Google");
gt.displayInfo();
Resource resource = new ClassPathResource("applicationContext");
BeanFactory factory = new XmlBeanFactory(resource);
GetterSetter gt1 = (GetterSetter)factory.getBean("name1");
gt1.displayInfo();
}
The XML file is in the src folder.
Instead of:
Resource resource = new ClassPathResource("applicationContext");
Use:
Resource resource = new ClassPathResource("applicationContext.xml");
Related
I am getting Exception in thread "main" org.yaml.snakeyaml.error.YAMLException: java.io.IOException: Stream closed when reading yaml file in my code:
Below is my project structure:
-rc
- main
- java
- MyMainClass
- resources
- application.yaml
Here is the sample code:
public class LoadYaml {
private static final Logger LOGGER = LoggerFactory.getLogger(LoadYaml.class);
public void loadYaml() {
Yaml yaml = new Yaml(new Constructor(Config.class));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("resources/application.yaml");
Config config = yaml.load(inputStream);
LOGGER.info(config.toString());
}
Below is my custom class for yaml:
package org.finra.dapi.parttioncleanup;
import java.util.List;
public class Config {
private String url;
private String userName;
private String pwsKey;
private List<Tables> tables;
....getters and setters
Error stack:
Exception in thread "main" org.yaml.snakeyaml.error.YAMLException: java.io.IOException: Stream closed
at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:218)
at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:176)
at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:171)
at org.yaml.snakeyaml.reader.StreamReader.peek(StreamReader.java:126)
at org.yaml.snakeyaml.scanner.ScannerImpl.scanToNextToken(ScannerImpl.java:1177)
at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:287)
at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:227)
at org.yaml.snakeyaml.parser.ParserImpl$ParseImplicitDocumentStart.produce(ParserImpl.java:195)
at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:158)
at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:148)
at org.yaml.snakeyaml.composer.Composer.getSingleNode(Composer.java:107)
at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:139)
at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:524)
at org.yaml.snakeyaml.Yaml.load(Yaml.java:452)
at org.finra.dapi.parttioncleanup.LoadYaml.loadYaml(LoadYaml.java:23)
at org.finra.dapi.parttioncleanup.LambdaHandler.main(LambdaHandler.java:25)
Caused by: java.io.IOException: Stream closed
at java.io.PushbackInputStream.ensureOpen(PushbackInputStream.java:74)
at java.io.PushbackInputStream.read(PushbackInputStream.java:166)
at org.yaml.snakeyaml.reader.UnicodeReader.init(UnicodeReader.java:92)
at org.yaml.snakeyaml.reader.UnicodeReader.read(UnicodeReader.java:124)
at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:183)
... 15 more
Any help would be appreciated, thank you
I have class Dropbox.java which contains upload file function :
public class Dropbox {
static final String ACCESS_TOKEN = "<My-Access-Token>";
DbxRequestConfig config = new DbxRequestConfig("dropbox/java-tutorial", "en_US");
static final DbxClientV2 clientV2 = new DbxClientV2(config, ACCESS_TOKEN);
static public void UploadFile(String path, InputStream in) throws UploadException, DbxException, IOException
{
clientV2.files.uploadBuilder(path).run(in);
}
}
and call method as below
InputStream in = getInputStream();
String path="/newFileName.jpg";
Dropbox.CreateFile(path, in);
I have added these three jars for dropbox:
dropbox-core-sdk-1.8.2.jar
dropbox-core-sdk-2.0-beta-4.jar
jackson-core-2.6.1.jar
I get this error:
java.lang.IllegalAccessError: tried to access method com.dropbox.core.DbxRequestUtil.addAuthHeader(Ljava/util/ArrayList;Ljava/lang/String;)Ljava/util/ArrayList; from class com.dropbox.core.v2.DbxRawClientV2
at com.dropbox.core.v2.DbxRawClientV2.uploadStyle(DbxRawClientV2.java:176)
at com.dropbox.core.v2.DbxFiles.upload(DbxFiles.java:8290)
at com.dropbox.core.v2.DbxFiles.access$5900(DbxFiles.java:25)
at com.dropbox.core.v2.DbxFiles$UploadBuilder.start(DbxFiles.java:8338)
at com.dropbox.core.v2.DbxFiles$UploadBuilder.start(DbxFiles.java:8304)
at com.dropbox.core.v2.DbxUploadStyleBuilder.run(DbxUploadStyleBuilder.java:29)
at classes.Dropbox.CreateFile(Dropbox.java:30)
at servlets.UploadServlet.doPost(UploadServlet.java:50)
...
I just removed the old jar :
dropbox-core-sdk-1.8.2.jar
and used DbxClientV1 instead of DbxClient in the class
I am trying to use ResourceBundle inside .drl file. But its throwing an exception like
`java.util.MissingResourceException: Can't find bundle for base name messages, locale en_US.`
My code is as follows
public class KnowledgeHelper {
#BeforeClass
public static KnowledgeBase getKnowledgeBase() throws Exception {
KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
String droolsRuleFilePath = System.getenv("JBOSS_HOME") + "/pp-Conf/rules/Validator.drl";
builder.add(ResourceFactory.newFileResource(droolsRuleFilePath), ResourceType.DRL);
if (builder.hasErrors()) {
throw new RuntimeException(builder.getErrors().toString());
}
KnowledgeBaseConfiguration configuration = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(configuration);
knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages());
return knowledgeBase;
}
I am accessing this helper class to generate KnowledgeBase
I am creating the Knowledge session in my controller class as follows
knowledgeBase=knowledgeHelper.getKnowledgeBase();
knowledgeSession = knowledgeBase.newStatefulKnowledgeSession();
knowledgeSession.insert(olmvo);
knowledgeSession.insert(validationResponse1);
knowledgeSession.fireAllRules();
and my drl file is as follows
rule "OLM_PRODUCTION_VALIDATOR"
when
$olm : OLMVO(workflow.code == "OLM_PRODUCTION" ,workflow_type : workflow.processKey)
$validationResponse : ValidationResponse()
then
System.out.println("MESSAGE FILE-----"+EdgeAppConstant.EDGE_APP_MESSAGES_FILE);
ResourceBundle edgeappErrorBundle = ResourceBundle.getBundle(EdgeAppConstant.EDGE_APP_MESSAGES_FILE);
System.out.println("Workflow Type-----"+workflow_type);
end
I have imported all the classes that i'm using in this drl.
So i want to know how to access properties file directly inside .drl file.
Please Help!!
this my project strucuture:
and i found the next exception:
aused by: org.springframework.webflow.engine.model.builder.FlowModelBuilderException: Couldtion at class path resource [WEB-INF/flow/consultaDeutes/consultaDeutes.xml]
at org.springframework.webflow.engine.model.builder.xml.XmlFlowModelBuilder.init(Xml at org.springframework.webflow.engine.model.builder.DefaultFlowModelHolder.assembleF.java:86)
at org.springframework.webflow.engine.model.builder.DefaultFlowModelHolder.getFlowMo:61)
at org.springframework.webflow.engine.builder.model.FlowModelFlowBuilder.doInit(Flow ... 47 more
Caused by: java.io.FileNotFoundException: class path resource [src/main/webapp/WEB-INF/flow/consultaDeutes/consultaDeutes.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.ja at org.springframework.webflow.engine.model.builder.xml.DefaultDocumentLoader.loadDova:98)
at org.springframework.webflow.engine.model.builder.xml.XmlFlowModelBuilder.init(Xml ... 50 more
What is wrong here? i'm pretty desperate ty.
#Override
protected FlowDefinitionResource getResource(FlowDefinitionResourceFactory resourceFactory) {
FlowDefinitionResource resource = resourceFactory.createResource("consultaDeutes.xml");
Assert.assertNotNull(resource);
return resource;
}
/*[src/main/webapp/WEB-INF/flow/consultaDeutes/consultaDeutes.xml]*/
#Test
public void testFlowShouldEnterStartState()
{
this.startFlow(context);
// assertCurrentStateEquals("a_cargar_info");
}
Below are some code fragments that indicate what I am trying at the moment, but its unreliable. Princiaply I think
because you can only register a protocol handler once, and occasionally other libraries may be doing this first.
import org.apache.xerces.util.XMLCatalogResolver;
public static synchronized XMLCatalogResolver getResolver() {
String c[] = {"classpath:xml-catalog.xml"};
if (cr==null) {
log.debug("Registering new protcol handler for classpath");
ConfigurableStreamHandlerFactory configurableStreamHandlerFactory = new ConfigurableStreamHandlerFactory("classpath", new org.fao.oek.protocols.classpath.Handler(XsdUtils.class.getClassLoader()));
configurableStreamHandlerFactory.addHandler("http", new sun.net.www.protocol.http.Handler());
URL.setURLStreamHandlerFactory(configurableStreamHandlerFactory);
log.debug("Creating new catalog resolver");
cr = new XMLCatalogResolver(c);
}
return cr;
}
xml-catalog.xml contains:
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<group prefer="public" xml:base="classpath:org/me/myapp/xsd/" >
<uri name="http://www.w3.org/XML/1998/namespace" uri="xml.xsd"/>
<uri name="http://www.w3.org/1999/xlink" uri="xlink.xsd" />
<uri name="http://www.w3.org/2001/XMLSchema" uri="XMLSchema.xsd" />
<uri name="http://purl.org/dc/elements/1.1/" uri="dc.xsd" />
<uri name="http://www.loc.gov/mods/v3" uri="mods-3.3.xsd" />
</group>
</catalog>
Obviously - the xsd files exist at the right place in the classpath.
The resolver acted properly with the following minimum set of code:
public class XsdUtils {
static {
System.setProperty("java.protocol.handler.pkgs", "org.fao.oek.protocols");
}
private static XMLCatalogResolver cr;
public static synchronized XMLCatalogResolver getResolver() {
if (cr == null) {
cr = new XMLCatalogResolver(new String[] { "classpath:xml-catalog.xml" });
}
return cr;
}
public static void main(String[] args) throws MalformedURLException, IOException {
XMLCatalogResolver resolver = getResolver();
URL url0 = new URL("classpath:xml-catalog.xml");
URL url1 = new URL(resolver.resolveURI("http://www.loc.gov/mods/v3"));
url0.openConnection();
url1.openConnection();
}
}
You can alternatively specify java.protocol.handler.pkgs as a JVM argument:
java -Djava.protocol.handler.pkgs=org.fao.oek.protocols ...
The Handler class was implemented as follows:
package org.fao.oek.protocols.classpath;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class Handler extends java.net.URLStreamHandler {
#Override
protected URLConnection openConnection(URL u) throws IOException {
String resource = u.getPath();
if (!resource.startsWith("/")) resource = "/" + resource;
System.out.println(getClass().getResource(resource));
return getClass().getResource(resource).openConnection();
}
}
It is important to have the forward slash ("/") when requesting the resource, as answered by this Stack Overflow question: "open resource with relative path in java."
Note the main method in XsdUtils. The output to the program when xml-catalog.xml and mods-3.3.xsd are on the classpath but not in a JAR is:
file:/workspace/8412798/target/classes/xml-catalog.xml
file:/workspace/8412798/target/classes/org/me/myapp/xsd/mods-3.3.xsd
The output to the program when the files are in a JAR is:
jar:file:/workspace/8412798/target/stackoverflow.jar!/xml-catalog.xml
jar:file:/workspace/8412798/target/stackoverflow.jar!/org/me/myapp/xsd/mods-3.3.xsd
With respect to this code in the original question:
new org.fao.oek.protocols.classpath.Handler(XsdUtils.class.getClassLoader())
your Handler does not need a specific class loader unless you have configured your application to use a special class loader, like one extended from URLClassLoader.
"A New Era for Java Protocol Handlers" is a good resource about protocol handlers.
Just to bring everything full circle, the following class uses XsdUtils.getResolver() to parse XML. It validates against the schemas specified in the XMLCatalogResolver:
public class SampleParser {
public static void main(String[] args) throws Exception {
String xml = "<?xml version=\"1.0\"?>" + //
"<mods ID=\"id\" version=\"3.3\" xmlns=\"http://www.loc.gov/mods/v3\">" + //
"<titleInfo></titleInfo>" + //
"</mods>";
ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
XMLReader parser = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName());
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
parser.setProperty("http://apache.org/xml/properties/internal/entity-resolver", XsdUtils.getResolver());
parser.setErrorHandler(new ErrorHandler() {
#Override
public void error(SAXParseException exception) throws SAXException {
System.out.println("error: " + exception);
}
#Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatalError: " + exception);
}
#Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println("warning: " + exception);
}
});
parser.parse(new InputSource(is));
}
}