java.lang.reflect.UndeclaredThrowableException - java

In my ejb client code
package client;
import com.homeif.HelloWorldHome;
import com.remoteif.HelloWorld;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import java.awt.image.LookupOp;
import java.util.Properties;
public class HelloClient {
public static void main(String args[]) {
try {
Context initialContext = new InitialContext();
Object object = initialContext.lookup("HelloWorldBean");
System.out.println("Object:-"+object);
HelloWorldHome home =
(HelloWorldHome) PortableRemoteObject.narrow(object,
HelloWorldHome.class);
HelloWorld myHelloWorld = home.create();
String message = myHelloWorld.sayHello();
System.out.println(message);
} catch (Exception e) {
System.err.println(" Error : " + e);
System.exit(2);
}
}
}
I am getting the following error
java.lang.Exception: java.lang.NoSuchMethodError: org.jboss.remoting.Version.getDefaultVersion()
It is in the following line
HelloWorldHome home =(HelloWorldHome) PortableRemoteObject.narrow(object, HelloWorldHome.class);
Why it is so? How can I solve this?
The jar I am using is jboss-remoting-1.4.1.final.jar. But the Version class in it doesn't contain the function getDefaultVersion. Can anyone please tell me the jar file for this?

I added jboss-remoting-4.2.2.GA.jar. that solved the problem

Related

MiniKdc not available from org.springframework.security.kerberos.test.MiniKdc

I am trying to use "MiniKdc" in my code implementation like "MiniKdc.main(config)" but am getting error "can not resolve symbol 'MiniKdc' ".
I am following this example https://www.baeldung.com/spring-security-kerberos-integration
i have added this dependecy in my build.gradle
implementation 'org.springframework.security.kerberos:spring-security-kerberos-test:1.0.1.RELEASE'
i tried to search the dependecy from maven central/repository and i can't find it.
here is the class i am working on, i want to be able to import Minikdc in the second import statement.
import org.apache.commons.io.FileUtils;
import org.springframework.security.kerberos.test.MiniKdc;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
class KerberosMiniKdc {
private static final String KRB_WORK_DIR = ".\\spring-security-sso\\spring-security-sso-kerberos\\krb-test-workdir";
public static void main(String[] args) throws Exception {
String[] config = MiniKdcConfigBuilder.builder()
.workDir(prepareWorkDir())
.confDir("minikdc-krb5.conf")
.keytabName("example.keytab")
.principals("client/localhost", "HTTP/localhost")
.build();
MiniKdc.main(config);
}
private static String prepareWorkDir() throws IOException {
Path dir = Paths.get(KRB_WORK_DIR);
File directory = dir.normalize().toFile();
FileUtils.deleteQuietly(directory);
FileUtils.forceMkdir(directory);
return dir.toString();
}
}
is there anything am doing wrong?
As of 2021, spring-security-kerberos is not well maintained.
I suggest using Apache Kerby instead, either directly or via other library like Kerb4J. See an example here.
package com.kerb4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.kerby.kerberos.kerb.client.KrbConfig;
import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import java.io.File;
public class KerberosSecurityTestcase {
private static final Log log = LogFactory.getLog(KerberosSecurityTestcase.class);
private static int i = 10000;
protected int kdcPort;
private SimpleKdcServer kdc;
private File workDir;
private KrbConfig conf;
#BeforeAll
public static void debugKerberos() {
System.setProperty("sun.security.krb5.debug", "true");
}
#BeforeEach
public void startMiniKdc() throws Exception {
kdcPort = i++;
createTestDir();
createMiniKdcConf();
log.info("Starting Simple KDC server on port " + kdcPort);
kdc = new SimpleKdcServer(workDir, conf);
kdc.setKdcPort(kdcPort);
kdc.setAllowUdp(false);
kdc.init();
kdc.start();
}
#AfterEach
public void stopMiniKdc() throws Exception {
log.info("Stopping Simple KDC server on port " + kdcPort);
if (kdc != null) {
kdc.stop();
log.info("Stopped Simple KDC server on port " + kdcPort);
}
}
public void createTestDir() {
workDir = new File(System.getProperty("test.dir", "target"));
}
public void createMiniKdcConf() {
conf = new KrbConfig();
}
public SimpleKdcServer getKdc() {
return kdc;
}
public File getWorkDir() {
return workDir;
}
public KrbConfig getConf() {
return conf;
}
}
Disclaimer: I'm the author of Kerb4J

Java, how could we log and store it into local file, a stateless session bean?

I am trying to log the program's execution flow to better understand how servlets, EJBs and JSPs work together.
Currently the difficulty I am facing is to output the log to a local file.
I have first tried with the Java logger API, studying this example:
Using Java log API:
http://wiki4.caucho.com/Java_EE_Servlet/JSP_tutorial_:_Adding_an_error_page,_logging,_and_other_forms_of_debugging#Using_Java_log_API
And I have written:
package beans;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
#Stateless
public class ComentarioNota {
private static final Logger log = Logger.getLogger(ComentarioNota.class.getName());
public String convierteComentarioNota(String evaluacion, String comentario) {
log.logp(Level.WARNING,
this.getClass().getName(),
this.getClass().getName(), this.getClass().getName() + "::convierteComentarioNota::el usuario introdujo: " + evaluacion + comentario);
if (evaluacion.trim().equals("Apto") && comentario != null && comentario.length() > 5) {
return "Apto";
} else {
return "No Apto";
}
}
And it indeed outputs the log with ClassName::ClassMethod::User input info.
However it outputs the log info to the console, I need it in a local file, how could we log into a local file?
I have tried to use the PrintWriter and creating a new file with its contents:
package beans;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
#Stateless
public class ComentarioNota {
private static final Logger log = Logger.getLogger(ComentarioNota.class.getName());
public String convierteComentarioNota(String evaluacion, String comentario) {
try (PrintWriter out = new PrintWriter("log.txt")) {
out.println(this.getClass().getName() + "::convierteComentarioNota::el usuario introdujo: " + evaluacion + comentario);
if (evaluacion.trim().equals("Apto") && comentario != null && comentario.length() > 5) {
return "Apto";
} else {
return "No Apto";
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ComentarioNota.class.getName()).log(Level.SEVERE, null, ex);
}
return "No Apto";
}
}
However this does not create a new file.
How could we create that new local file and send the log output to it?
Thank you for your help!.
I have also read:
How do I save a String to a text file using Java?
Where does the ServletContext.log messages go in tomcat 7?
EDIT: I have read the comment's tutorial: http://tutorials.jenkov.com/java-logging/handlers.html#streamhandler
ANd I have found that we can add handlers to the logger, and there is a built in handler which is FileHandler which is supposed to create one file with the log's contents. I have tried the following:
package beans;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
#Stateless
public class ComentarioNota {
private static final Logger log = Logger.getLogger(ComentarioNota.class.getName());
public String convierteComentarioNota(String evaluacion, String comentario) {
try {
FileHandler handler = new FileHandler("comentarioNota.txt");
log.addHandler(handler);
log.logp(Level.WARNING,
this.getClass().getName(),
"convierteComentarioNota", this.getClass().getName() + "::convierteComentarioNota::el usuario introdujo: " + evaluacion + comentario);
if (evaluacion.trim().equals("Apto") && comentario != null && comentario.length() > 5) {
return "Apto";
} else {
return "No Apto";
}
} catch (IOException ex) {
Logger.getLogger(ComentarioNota.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(ComentarioNota.class.getName()).log(Level.SEVERE, null, ex);
}
return "No Apto";
}
}
However I still seeing the log being outputted to the console and no file is being created:
And no file is being creted because at least it does not show up in the IDE and I have also try to find it:
Could you help me figuring out how to log to a local file properly?
Thank you for your help.
you need to configure java.util.logging. what you're looking for is the FileHandler. I actually prefer other logging APIs but for your purposes please start here: Tutorial: Java Logging Configuration

RMI dynamic class loading

I'm trying to learn RMI. Managed to launch a simple example but I can't achieve dynamic loading of classes.
Hello.java
package com.example;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String greet(String name) throws RemoteException;
}
HelloImpl.java
package com.example;
public class HelloImpl implements Hello {
public String greet(String name) {
System.out.println("Call from " + name);
return "Hello " + name + "!";
}
}
Server.java
package com.example;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server extends HelloImpl {
public Server() {}
public static void main(String args[]) {
System.setSecurityManager(new SecurityManager());
try {
HelloImpl greeter = new HelloImpl();
Hello stub = (Hello) UnicastRemoteObject.exportObject(greeter, 0);
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client.java
package com.example;
import java.rmi.Naming;
public class Client {
private Client() {}
public static void main(String[] args) {
System.setSecurityManager(new SecurityManager());
try {
Hello stub = (Hello) Naming.lookup("//localhost/Hello");
System.out.println(stub.greet(args[0]));
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
rmi.policy
grant {
permission java.security.AllPermission;
};
I started rmiregistry, web-server and executed java -Djava.security.policy=rmi.policy com.example.Server. When I try to start the client application with command
java -Djava.rmi.server.codebase=http://localhost:8000/ -Djava.security.policy=rmi.policy com.example.Client Hivemaster
web-server get request
127.0.0.1 - - [13/Dec/2017 14:06:45] "GET /com/example/Hello.class HTTP/1.1" 200
but program get exception
Exception in thread "main" java.lang.NoClassDefFoundError: com/example/Hello
at com.example.Client.main(Client.java:17)
Caused by: java.lang.ClassNotFoundException: com.example.Hello
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
Why?
If the client is using the Hello interface by name, it must be present on its classpath. Same as it does when compiling it.
The codebase feature is for classes derived from those mentioned in remote interfaces. In this case there is no apparent need to use the codebase feature at all: but if you do, the codebase property needs to be set at the JVM which is sending instances of those classes.

Exception thrown when trying to load Pentaho report through java program

This code was mostly taken from Pentaho's website on sample programs. The goal is to use their API to generate HTML output with a Pentaho report.
The report was created with Pentaho 3.5.0-RC2
The version of jars I am using are the following:
pentaho-reporting-engine-classic-core-3.5.0-RC2.jar
libloader-1.1.1.jar
libbase-1.1.1.jar
The exception I am getting is the following:
org.pentaho.reporting.libraries.resourceloader.ContentNotRecognizedException: None of the selected factories was able to handle the given data: ResourceKey{schema=org.pentaho.reporting.libraries.resourceloader.loader.URLResourceLoader, identifier=file:/C:/Users/elias.kopsiaftis/workspace_experimental/TestPentahoReport/bin/Test.prpt, factoryParameters={}, parent=null}
at org.pentaho.reporting.libraries.resourceloader.DefaultResourceManagerBackend.create(DefaultResourceManagerBackend.java:295)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:387)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:342)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.createDirectly(ResourceManager.java:205)
at ReportTester.getReportDefinition(ReportTester.java:74)
at ReportTester.getReport(ReportTester.java:25)
at ReportTester.main(ReportTester.java:84)
java.lang.NullPointerException
at ReportTester.getReport(ReportTester.java:26)
at ReportTester.main(ReportTester.java:84)
And finally, the code snippet!
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.io.*;
import org.pentaho.reporting.engine.classic.core.DataFactory;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlReportUtil;
import org.pentaho.reporting.libraries.resourceloader.Resource;
import org.pentaho.reporting.libraries.base.util.StackableException;
import org.pentaho.reporting.libraries.resourceloader.ResourceException;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
public class ReportTester {
private String reportName = "FormCompleteUsagePerPartnerByMonth.prpt";
private String reportPath = "";
public void getReport() {
try {
final MasterReport report = getReportDefinition();
report.getParameterValues().put("partner", "");
report.getParameterValues().put("startingdate", "2015-03-01");
report.getParameterValues().put("endingdate", "2015-03-05");
HtmlReportUtil.createStreamHTML(report, System.out);
} catch(Exception e) {
e.printStackTrace();
}
}
private MasterReport getReportDefinition() {
try {
// Using the classloader, get the URL to the reportDefinition file
final ClassLoader classloader = this.getClass().getClassLoader();
final URL reportDefinitionURL = classloader.getResource(reportPath + reportName);
if(reportDefinitionURL == null) {
System.out.println("URL was null");
}
// Parse the report file
final ResourceManager resourceManager = new ResourceManager();
resourceManager.registerDefaults();
final Resource directly = resourceManager.createDirectly(reportDefinitionURL, MasterReport.class);
return (MasterReport) directly.getResource();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
ReportTester rt = new ReportTester();
rt.getReport();
}
}
Any advice on this would be much appreciated as I have been scratching my head on this all day. Thanks in advance!

Remote Method Invocation(different directory)

I am learning RMI by myself now.I put all my files in the same directory and they are working well.But after I separate the server and client in different directory,there will be an error said
RemoteException
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: CalculatorImpl_Stub (no security manager: RMI class loader disabled).
I dont know how to fix it.and here is my code :
Server
import java.rmi.Naming;
public class CalculatorServer{
public CalculatorServer(){
try{
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
}catch(Exception e){
System.out.println("Trouble: "+ e);
}
}
public static void main(String args[]){
new CalculatorServer();
}
}
Client
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
public class CalculatorClient{
public static void main(String[] args){
try{
Calculator c = (Calculator)Naming.lookup("rmi://localhost/CalculatorService");
System.out.println(c.sub(4,3));
System.out.println(c.add(4,5));
System.out.println(c.mul(3,6));
System.out.println(c.div(9,3));
}catch(MalformedURLException murle){
System.out.println();
System.out.println("MalformedURLException");
System.out.println(murle);
}
....
}
You've over-separated. Some of the .class files are common to both the server and the client. The class mentioned in the exception is one of them, and so are any others that show up in subsequent such exceptions.

Categories

Resources