Simple Apache-commons configuration example throws ConfigurationRuntimeException - java

I'm trying to test a very simple example given in the Apache-commons configuration library user's guide regarding declaring and creating beans. I copied the code in the example almost word by word, and yet I'm getting a ConfigurationRuntimeException (this after overcoming a different exception, see this question).
Here is the xml file I'm using - windowcongif.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<config>
<gui>
<windowManager config-class="test.DefaultWindowManager"
closable="false" resizable="true" defaultWidth="400"
defaultHeight="250">
</windowManager>
</gui>
</config>
Here is the code in the file WindowManager.java:
package test;
public interface WindowManager {}
Here is the code in the file DefaultWindowManager.java:
package test;
public class DefaultWindowManager implements WindowManager {
private boolean resizable;
private boolean closable;
private int defaultWidth;
private int defaultHeight;
}
Here is the code in the file Main.java:
package test;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.beanutils.BeanDeclaration;
import org.apache.commons.configuration.beanutils.BeanHelper;
import org.apache.commons.configuration.beanutils.XMLBeanDeclaration;
import org.apache.commons.beanutils.PropertyUtils;
public class Main {
public static void main(String[] args) throws ConfigurationException {
XMLConfiguration config = new XMLConfiguration("windowconfig.xml");
BeanDeclaration decl = new XMLBeanDeclaration(config, "gui.windowManager");
WindowManager wm = (WindowManager) BeanHelper.createBean(decl);
}
}
Here is the output during runtime:
Exception in thread "main" org.apache.commons.configuration.ConfigurationRuntimeException: org.apache.commons.configuration.ConfigurationRuntimeException: Property defaultHeight cannot be set on test.DefaultWindowManager
at org.apache.commons.configuration.beanutils.BeanHelper.createBean(BeanHelper.java:341)
at org.apache.commons.configuration.beanutils.BeanHelper.createBean(BeanHelper.java:358)
at org.apache.commons.configuration.beanutils.BeanHelper.createBean(BeanHelper.java:372)
at test.Main.main(Main.java:24)
Caused by: org.apache.commons.configuration.ConfigurationRuntimeException: Property defaultHeight cannot be set on test.DefaultWindowManager
at org.apache.commons.configuration.beanutils.BeanHelper.initProperty(BeanHelper.java:271)
at org.apache.commons.configuration.beanutils.BeanHelper.initBeanProperties(BeanHelper.java:229)
at org.apache.commons.configuration.beanutils.BeanHelper.initBean(BeanHelper.java:166)
at org.apache.commons.configuration.beanutils.DefaultBeanFactory.initBeanInstance(DefaultBeanFactory.java:108)
at org.apache.commons.configuration.beanutils.DefaultBeanFactory.createBean(DefaultBeanFactory.java:64)
at org.apache.commons.configuration.beanutils.BeanHelper.createBean(BeanHelper.java:336)
... 3 more
How do I make this simple example work?
I'm using version 1.9 of the commons-configuration package and version 1.8.3 of the commons-beanutils package, auto-imported by IntelliJ IDEA after putting the dependencies in the pom.xml file, and version 1.7.0_17 of java running on Windows 8 64bit.

If you are using JavaBeans you will need to add a setter for each field you want to set.
I suggest using the add setter and getter in IntelliJ for these fields.
The example states
// getters and setters ommitted, also the WindowManager methods

Related

Soap Webservice Client for JAVAFX Application

I am trying to call the webservice for my application. If I call it in a sample project it is working perfectly fine. But when I merge it with My Java FX it is giving me so many errors. Web Service Client is auto generated using the Eclipse. I am trying to call the Methods only. Can Anyone help me?
Error: **Correction** I have edited it and I am using now JAVASE-15 and JVAFX-SDK 11.0.2
The package javax.xml.namespace is accessible from more than one module: java.xml, jaxrpc
Correction Update 2: I have removed Java.xml dependencies and module-info file as well.
but the new error is this
**Error: Could not find or load main class gload.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application**
and IF I keep the module info file it shows:
**Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.graphics not found, required by gload**
Model:
package gload.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JOptionPane;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data.CustomerItem;
import org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data.Result;
import org.tempuri.IService;
import org.tempuri.ServiceLocator;
public class PdmData
{
public String scode;
public boolean state = false;
public static String CdfFile;
public static String pdflocation;
public static String Custom_Ci;
public static String Generic_Ci;
public static String Mp_ref;
public static String Interface;
public static String Comments;
public static String PersoAppli;
public static String Code;
public static String Revision;
public static String Customer_Name;
public static String Customer_reference;
public static String getCode() {
return Code;
}
public static void setCode(String code) {
Code = code;
}
public static String getRevision() {
return Revision;
}
public static void setRevision(String revision) {
Revision = revision;
}
public static String getCustomer_Name() {
return Customer_Name;
}
public static void setCustomer_Name(String customer_Name) {
Customer_Name = customer_Name;
}
public static String getCustomer_reference() {
return Customer_reference;
}
public static void setCustomer_reference(String customer_reference) {
Customer_reference = customer_reference;
}
public static String getPersoAppli() {
return PersoAppli;
}
public static void setPersoAppli(String persoAppli) {
PersoAppli = persoAppli;
}
public static String getGeneric_Ci() {
return Generic_Ci;
}
public static void setGeneric_Ci(String generic_Ci) {
Generic_Ci = generic_Ci;
}
public static String getCdfFile() {
return CdfFile;
}
public static void setCdfFile(String cdfFile) {
CdfFile = cdfFile;
}
public static String getPdflocation() {
return pdflocation;
}
public static void setPdflocation(String pdflocation) {
PdmData.pdflocation = pdflocation;
}
public String Cdffile(String reference) {
ServiceLocator locator = new ServiceLocator(); -------->Web Service Locator and call
try {
IService basicHttpBinding_IService = locator.getBasicHttpBinding_IService();
Result result = basicHttpBinding_IService.getFilebyDcode(reference);
//To download the files
String link = result.getLocation();
System.out.println(link);
File out = new File("C:\\TempDownload\\" + reference +".zip"); //Creating a zip file to store the contents of download file
new Thread(new Download(link,out)).start();
//To Unzip the file
Path source = Paths.get("C:\\TempDownload\\" + reference +".zip");
Path target = Paths.get("C:\\TempDownload\\Unzip");
try {
unzipFolder(source, target);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
//Creating a File object for directory
File directoryPath = new File("C:\\TempDownload\\Unzip\\Pre Ppc" + reference + "A_Released");
//List of all files and directories
String[] contents = directoryPath.list();
System.out.println("List of files and directories in the specified directory:");
FilenameFilter pdffilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".pdf")) {
return true;
} else {
return false;
}
}
};
String[] contents1 = directoryPath.list(pdffilter);
for(String fileName : contents1) {
System.out.println(fileName);
setCdfFile(fileName);
setPdflocation(directoryPath.toString());
}
//To extract the Data From PDF
File file = new File(getPdflocation() + "\\" + getCdfFile());
//FileInputStream fis = new FileInputStream(file);
PDDocument document = PDDocument.load(file);
PDFTextStripper pdfReader = new PDFTextStripper();
String docText = pdfReader.getText(document);
System.out.println(docText);
document.close();
//To extract details from document
String CI_Ref = "CI Ref";
int pos ;
pos = docText.indexOf(CI_Ref);
setGeneric_Ci(docText.substring(pos+7 , pos+15));
System.out.println("Generic CI: " + getGeneric_Ci());
//To get Details of CI
CustomerItem customerItem = basicHttpBinding_IService.getCiDetails(getGeneric_Ci());
setPersoAppli(customerItem.getPersoAppli());
setCode(customerItem.getCode());
setRevision(customerItem.getRevision());
setCustomer_Name(customerItem.getCustomerName());
setCustomer_reference(customerItem.getCustomerReference());
}catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Unable to reach Service : " + e.getMessage());
}
return getPersoAppli();
}
Module info file
module gload {
requires javafx.controls;
requires javafx.fxml;
requires java.desktop;
requires java.rmi;
requires java.base;
requires axis;
requires jaxrpc;
requires org.apache.pdfbox;
opens gload;
opens gload.views.main;
opens gload.utils;
opens gload.model;
opens gload.controllers;
opens org.tempuri;
opens org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data;
}
and IF I keep Jaxrpc in classpath instead of module path I get error like this Description
The type javax.xml.rpc.ServiceException cannot be resolved. It is indirectly referenced from required .class files
OK, this won't really be an answer, more pointers to related issues and potential approaches to come up with solutions. But I'll post it as an answer as it is likely better to do that than lots of comments.
Unfortunately, you have multiple errors and issues, so I'll try to deal with some of them seperately.
According to:
Java FX Modular Application, Module not found (Java 11, Intellij)
The error:
Error occurred during initialization of boot layer
java.lang.module.FindException:
Module X not found, required by Y
can occur when --module-path is wrong and the module can't be found. Probably, that is at least one of your issues. The linked answer is for Idea and I don't use Eclipse, so I don't know how to resolve the issue in Eclipse, but perhaps you could do some research to find out.
Regarding:
The package javax.xml.namespace is accessible from more than one module
there is some info on what is going on here:
Eclipse is confused by imports ("accessible from more than one module").
This fix appears tricky to me. Please review the linked questions and solutions. It looks like either you need to either
Forego Java 9+ modularity OR
Manage your dependencies to not include the violating transitive dependency OR
Change to a library that doesn't rely on the broken library (probably the preferred solution in this case).
The broken library causing this issue is likely the version of jaxrpc you are using. My guess is that some of the relevant XML libraries were only added to standard Java in Java 9, but the jaxrpc library you are using was developed prior to that. So, jaxrpc either includes the XML libraries in its classes or makes use of a transitive library that does the same. This causes a conflict because the XML libraries can only be included once in the project.
Further info on your issues is in this answer:
Eclipse can't find XML related classes after switching build path to JDK 10
The info is so ugly . . . you could read the answer, it may either help or discourage you.
Some things you could do to help resolve the situation
What should be done about this is kind of tricky and will depend on your skill level and how or if you can solve it. I'll offer up some advice on some things you could do, but there are other options. You know your application better than I so you may be able to come up with better solutions for your application.
I'd advise separating these things out, just as a way of troubleshooting, get a project which works with all of the JavaFX components and one which works with all of the SOAP components and make sure they build and do what you want. Then try to combine the two projects either by integrating them into one project or running them in separate VMs with communication between the two (e.g. via an added REST API, though that is a much more complicated solution, so think hard about that before attempting it).
Also, upgrade to the latest version of JavaFX. I don't think it will fix your issue, but it can't hurt and it is possible some refinements in recent JavaFX versions may have done some things which might help ease some of your issues (though not all of them, as some of your issues stem from jaxrpc usage in a modular project, which is unrelated to JavaFX).
Also, and probably more importantly, consider using a different SOAP client framework that interacts better with modular Java 9+ than the broken implementation that jaxrpc appears to have.
In terms of whether you should make your application modular or not (include a module-info or not), I don't really know the best approach for you. Certainly, whichever way you choose you will run into issues. But, the issues and how to resolve them will be different depending on the chosen solution path (as I guess you have already discovered during the course of your investigation for the question).
If necessary, isolate the issues down to single separate issues. If you need help in resolving each separate issue post new questions that feature minimal reproducible example code to replicate the issue. Mind if you do so, that the code is absolutely minimal and also complete so that it replicates and asks about only one issue, not a combination of more than one and that the questions are appropriate tagged - e.g. if the question is about jaxrpc and modularity it should include jaxrpc and modular tags and no JavaFX code or tags (and vice versa) and certainly on pdf code or dependencies anywhere if that isn't part of the problem.

Best way to override java.util.logging Level class to change the level strings

My aim is to use the java.util.logging Level class and change the Level strings like 'FINE' to 'VERBOSE'.
public static final Level FINE = new Level("FINE", 500);
I know we can do this by extending the Level as follows:
public class MyLogLevel extends Level {
private static final long serialVersionUID = -8176160795706313070L;
private static final Level FINE = new MyLogLevel("VERBOSE", 500);
protected MyLogLevel(String name, int level) {
super(name, level);
}
}
I would like to know, is this the good way to do it or are there any better ways to do it.
If you are running Oracle JDK or OpenJDK you can simply override the localized names of the existing levels. You do this by creating new resource bundle (properties file or resource bundle class) under the package sun.util.logging.resources. The bundle name must be in the form of logging_LANG_COUNTRY.
For example, here is a test program under project called LevelTest:
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
public class NewLevels {
public static void main(String[] args) {
System.out.println(Locale.getDefault());
ResourceBundle rb = ResourceBundle.getBundle("sun.util.logging.resources.logging");
System.out.println(rb.getLocale());
System.out.println(Level.FINE.getLocalizedName());
System.out.println(Level.FINER.getLocalizedName());
System.out.println(Level.FINEST.getLocalizedName());
}
}
When I execute this test the locale printed is en_US. Therefore my resource bundle name will be logging_en_US.properties.
The properties resource bundle will contain the following:
FINE=VERBOSE
FINER=VERBOSE
FINEST=VERBOSE
Here is a listing of the project structure:
%USERPROFILE%\Documents\Projects\LevelTest\src\NewLevels.java
%USERPROFILE%\Documents\Projects\LevelTest\src\sun\util\logging\resources\logging_en_US.properties
When I run the program I get the following output:
en_US
en_US
VERBOSE
VERBOSE
VERBOSE
On a larger project, you might have to fight some of the class loader issues to ensure that the correct resource bundle is located.
Alternatively, if you don't want to do that you can resort to creating a custom formatter.

How to use java properties file in OSGI Declarative Services Annotations

I'm trying to use bndtools to create my OSGI program. Here is my previous code, and it can work well with the felix console.
package com.buaa.ate.service.data.command;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.felix.service.command.CommandProcessor;
import com.buaa.ate.service.api.data.Publisher;
#Component(
service=PublishCommand.class,
property={
CommandProcessor.COMMAND_SCOPE + ":String=example",
CommandProcessor.COMMAND_FUNCTION + ":String=publish",
}
)
public class PublishCommand {
private Publisher publishSvc;
#Reference
public void setPublisher(Publisher publishSvc) {
this.publishSvc = publishSvc;
}
public void publish(String content) {
publishSvc.start();
long result = publishSvc.publish(content);
System.out.println(result);
publishSvc.stop();
}
}
Now, I want to change the annotation like this:
package com.buaa.ate.service.data.command;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.felix.service.command.CommandProcessor;
import com.buaa.ate.service.api.data.Publisher;
#Component(
service=PublishCommand.class,
properties="com/buaa/ate/service/data/command/config.properties"
)
public class PublishCommand {
private Publisher publishSvc;
#Reference
public void setPublisher(Publisher publishSvc) {
this.publishSvc = publishSvc;
}
public void publish(String content) {
publishSvc.start();
long result = publishSvc.publish(content);
System.out.println(result);
publishSvc.stop();
}
}
And this is my properties file:
config.properties
It's content like this:
osgi.command.scope\:String:example
osgi.command.function\:String:publish
When I run the program, input the command 'publish something', and then the problem happens:
'gogo: CommandNotFoundException: Command not found: publish'
So, what should I do to fix the problem?
Well, I just realize that it's so easy to fix the problem. This is a part of the osgi javadoc:
property
public abstract java.lang.String[] property
Properties for this Component.
Each property string is specified as "key=value". The type of the property value can be specified in the key as key:type=value. The type must be one of the property types supported by the type attribute of the property element of a Component Description.
To specify a property with multiple values, use multiple key, value pairs. For example, "foo=bar", "foo=baz".
See Also:
"The property element of a Component Description."
Default:{}
So I add the 'type' property to config.properties, and then the code can work well. Here is the current properties file:
current properties file
And it's content like this:
osgi.command.scope=example
osgi.command.scope\:type:String
osgi.command.function=publish
osgi.command.function\:type:String
The program can work well now.

Using Processing libraries - in a Java file in a Processing sketch?

Somewhat of a followup to How to use public class frome .java file in other processing tabs?; using the example from Usage class from .java file - is there a full doc for that? - Processing 2.x and 3.x Forum, I have this:
/tmp/Sketch/Sketch.pde
// forum.processing.org/two/discussion/3677/
// usage-class-from-java-file-is-there-a-full-doc-for-that
Foo tester;
void setup() {
size(600, 400, JAVA2D);
smooth(4);
noLoop();
clear();
rectMode(Foo.MODE);
fill(#0080FF);
stroke(#FF0000);
strokeWeight(3);
tester = new Foo(this);
tester.drawBox();
}
/tmp/Sketch/Foo.java
import java.io.Serializable;
//import peasy.org.apache.commons.math.geometry.Rotation;
//import peasy.org.apache.commons.math.geometry.Vector3D;
import processing.core.PApplet;
import processing.core.PGraphics;
public class Foo implements Serializable {
static final int GAP = 15;
static final int MODE = PApplet.CORNER;
final PApplet p;
Foo(PApplet pa) {
p = pa;
}
void drawBox() {
p.rect(GAP, GAP, p.width - GAP*2, p.height - GAP*2);
}
}
The example runs fine as is - but if I uncomment the import peasy.org... lines, then compilation fails with:
The package "peasy" does not exist. You might be missing a library.
Libraries must be installed in a folder named 'libraries' inside the 'sketchbook' folder.
Of course, I do have PeasyCam installed, under /path/to/processing-2.1.1/modes/java/libraries/peasycam/ - and it works fine, if I do a import peasy.*; from a .pde sketch.
I guess, this has something to do with paths - apparently pure Java files in a sketch, do not refer to the same library paths as .pde files in a sketch.
Is it possible to get this sketch to compile with the import peasy.org... lines (other than, I guess, copying/symlinking the peasycam library in the sketch folder, here /tmp/Sketch/ <--- EDIT: just tried symlinking as described, it doesn't work; the same error is reported)?
This is where you learn that Processing isn't actually Java, it just has a similar(ish) syntax and can run its code in the JVM by aggregating all .pde files into a single class that can be compiled for running on the JVM. Processing has its own rules for dealing with imports and the like.
Why not just do this entirely in Processing instead?
class Foo {
static int MODE = ...;
static int GAP = ...;
PApplet sketch;
public Foo(PApplet _sketch) {
sketch = _sketch;
...
}
void drawBox() {
sketch.rect(GAP, GAP, p.width - GAP*2, p.height - GAP*2);
}
...
}
and then make sure to have that in a file Foo.pde or something in the same dir as your sketch, with your sketch loading in the peasy library through the regular Processing import mechanism?
Ok, thanks to #MikePomaxKamermans answer, especially "by aggregating all .pde files into a single class", I simply tried importing peasy in the .pde file before the first reference to foo; that is, in /tmp/Sketch/Sketch.pde I now have:
// forum.processing.org/two/discussion/3677/
// usage-class-from-java-file-is-there-a-full-doc-for-that
import peasy.*; // add this
Foo tester;
...
... and then the sketch compiles without a problem (but note: while this approach works for this example, it somehow didn't work in the original problem that drove me to post the question).

About Adding import package in Groovy by customizing compilation process

I am writing a java file in which i am parsing the given groovy file using GroovyClassLoader to find the class in it. To do this, i have to import some class (like org.junit.Test) and add package and add static import also. Since i am using old groovy version 1.6, i can not use compilation customizers as these classes not available in this version. So to import custom classes, i had to write custom groovy class loader by extending groovy class loader class like below,
...
public static class DefaultImportClassLoader extends GroovyClassLoader {
public DefaultImportClassLoader(ClassLoader cl){
super(cl);
}
public CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource codeSource) {
CompilationUnit cu = super.createCompilationUnit(config, codeSource);
cu.addPhaseOperation(new SourceUnitOperation() {
public void call(SourceUnit source) throws CompilationFailedException {
//source.getAST().addImport("Test",ClassHelper.make("org.junit.Test")); //working
source.getAST().addImportPackage("org.junit.");
}}, Phases.CONVERSION);
return cu;
}
}
here add import package is not working. Would any one give right suggestion way of using addImportPackage().
I've tested your code and works perfectly for me. (with groovy-all-1.6.9.jar) (edit: groovy-all-1.6.0.jar works fine too)
How do you use your class DefaultImportClassLoader?
I've done:
public static void main(String[] args) throws InstantiationException, IllegalAccessException{
GroovyClassLoader loader = new DefaultImportClassLoader(new GroovyClassLoader());
Class groovyClass = loader.parseClass(DefaultImportClassLoader.class.getClassLoader().getResourceAsStream("so_22729226/test.groovy"));
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
groovyObject.invokeMethod("run", null);
}
With this Groovy class:
class so_22729226_Test {
def run(){
print Test.class
}
}
And I get the expected output: interface org.junit.Test
If I use the standard loader I get:
Caused by: groovy.lang.MissingPropertyException: No such property: Test for class: so_22729226_Test
Which is the expected behaviour too.

Categories