I've tried hard to solve this and I couldn't. I'm trying to use httpClient 4.1.2 from apache. As logic I started with the example, the problem is that I'm having some strange error that I don't understand. This is the deal:
package ClientWithResponseHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class Main {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = **httpclient.execute(httpget, responseHandler);**
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
The error is with "httpclient.execute(httpget, responseHandler);" IT says that it cannot find the method execute(HttpGet,ResponseHandler)
The question shouldn't the example work? What am I doing wrong?! :S
I got the same error too. I resolved it by adding the "httpcore-4.2.1.jar". Then it started complaining about the Class Def not found for logging. So I added "commons-logging-1.1.1.jar" and now I think it works fine. Both these files can be found along with "httpclient-4.2.1.jar".
Hope this helps.
Related
I think I may be the only one experiencing this issue.
I, today, updated my eclipse install to version 2020-03 (4.15.0). I am also attempting to write a very simple JUnit 5 test for a new method I'm working on.
When I run my test, right now just a basic stub, I get the following error:
java.lang.SecurityException: class "org.junit.platform.commons.PreconditionViolationException"'s signer information does not match signer information of other classes in the same package
at java.base/java.lang.ClassLoader.checkCerts(ClassLoader.java:1150)
at java.base/java.lang.ClassLoader.preDefineClass(ClassLoader.java:905)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1014)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:821)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:719)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:642)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:600)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createUnfilteredTest(JUnit5TestLoader.java:75)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createTest(JUnit5TestLoader.java:66)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.loadTests(JUnit5TestLoader.java:53)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:526)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
I also see the following dialog
My run Configuration is:
I've tried all major junit-jupiter (aggregator) releases back to 5.5.0 all resulting in the same issue.
I've tried this solution. However, that question deals with a class not found issue. I also tried that same solution using using junit-platform-commons version 1.6.1. no change.
However, I can run maven configuration with -Dtest=DeaFileListTest test the the tests run.
My test case is simple, I instantiate an object that has the method I want to test and then my test.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.core.Response;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.mfgweb.FileRepo;
class DeaFileListTest {
private static FileRepo filerepo;
private static Response response;
#BeforeAll
static void setUpBeforeClass() throws Exception {
filerepo = new FileRepo();
response = filerepo.getDeaFiles();
}
#AfterAll
static void tearDownAfterClass() throws Exception {
response = null;
filerepo = null;
}
#Test
public void deaFileListIsNotEmptyTest() throws IOException {
#SuppressWarnings ( "unchecked" )
List< String > files = ( List< String > )response.getEntity();
assertThat( files, not( empty() ) );
}
}
So I am curious why I'm receiving the Security Exception when I run the test in eclipse, yet Maven seems to execute them fine.
I am working on putting some business rules in drool engine.We cannot use KIE workspace UI to author rules.So that is out.
Problem Statement:Create a application(front end angular UI) back end spring boot microservice to author rules.Those authored rules needs to be dynamically refreshed without having to restart the jvm and other micro services which want to use these rules,should use them.For e.g:granting credit or interest rates based dealer credit history ,duration with bank and any new rules which might be designed as per author.I started looking on this and theoretically one could build something like this by using API of drools compiler library.
There is code example here.
for real time refreshing,there is something called KnowledgeAgent.
https://docs.jboss.org/drools/release/5.2.0.Final/drools-guvnor-docs/html/ch09.html
What is the new accepted way of programmatically creating new drools rules in Drools 6?
My problem is I am not able to make this work.Code is running fine but I am not able to see the drl file getting written.In debug mode,I can see string object with proper drl structure.Has anyone encountered this problem before.?
I have seen some examples on github where people have done yoman job to integrate drools in spring boot.I can start with building my service,but I need to be sure that this something which is possible to do
Following code will help you create drool rule using code.It is not recommended way and most of people use kie-web interface to design and modify drool rules.Not sure about how we can modify already created .drl files.But this has given me start.Going
package com.sample.model;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.drools.compiler.lang.DrlDumper;
import org.drools.compiler.lang.api.DescrFactory;
import org.drools.compiler.lang.api.PackageDescrBuilder;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
//#SuppressWarnings("restriction")
public class GenerateRule {
public static void main(String[] args) {
// TODO Auto-generated method stub
KieContainer container=build(KieServices.Factory.get());
System.out.println(container.getReleaseId());
System.out.println(container.getKieBase());
}
public static KieContainer build(KieServices kieServices){
KieFileSystem fileSystem=kieServices.newKieFileSystem();
ReleaseId releaseId=kieServices.newReleaseId("com.example.rulesengine",
"model-test", "1.0-SNAPSHOT");
fileSystem.generateAndWritePomXML(releaseId);
//fileSystem.write("D:/workspace/DroolSamples/src/main/resources/rules/rules.drl", getResource(kieServices, "D:/workspace/DroolSamples/src/main/resources/rules/rules.drl"));
addRule(fileSystem);
KieBuilder kieBuilder = kieServices.newKieBuilder(fileSystem);
kieBuilder.buildAll();
if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
throw new RuntimeException("Build Errors:\n" +
kieBuilder.getResults().toString());
}
return kieServices.newKieContainer(releaseId);
}
#SuppressWarnings("restriction")
private static void addRule(KieFileSystem kieFileSystem) {
PackageDescrBuilder packageDescrBuilder = DescrFactory.newPackage();
packageDescrBuilder
.name("com.sample.model")
.newRule()
.name("Is of valid age")
.lhs()
.pattern("Person").constraint("age < 18")
.id("$a", true).end()
//.pattern().id("$a", false).end()
.end()
.rhs("$a.setShowBanner( false );")
//.rhs("insert(new Person())")
.end();
String rules = new DrlDumper().dump(packageDescrBuilder.getDescr());
KieFileSystem fileSystem=kieFileSystem.write("D:/newrule.drl", rules);
try{
// create new file
File file = new File("src/main/resources/rules/test.drl");
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(rules);
// close connection
bw.close();
System.out.println("File Created Successfully");
}catch(Exception e){
System.out.println(e);
}
}
private static Resource getResource(KieServices kieServices, String resourcePath) {
try {
// InputStream is = com.google.common.io.Resources.getResource(resourcePath).openStream(); //guava
InputStream is=new FileInputStream(new File(resourcePath));
return kieServices.getResources()
.newInputStreamResource(is)
.setResourceType(ResourceType.DRL);
} catch (IOException e) {
throw new RuntimeException("Failed to load drools resource file.", e);
}
}
}
I have implementated a Rest web service (the function is not relevant) using JAX-RS. Now I want to generate its documentation using Swagger. I have followed these steps:
1) In build.gradle I get all the dependencies I need:
compile 'org.glassfish.jersey.media:jersey-media-moxy:2.13'
2) I documentate my code with Swagger annotations
3) I hook up Swagger in my Application subclass:
public class ApplicationConfig extends ResourceConfig {
/**
* Main constructor
* #param addressBook a provided address book
*/
public ApplicationConfig(final AddressBook addressBook) {
register(AddressBookService.class);
register(MOXyJsonProvider.class);
register(new AbstractBinder() {
#Override
protected void configure() {
bind(addressBook).to(AddressBook.class);
}
});
register(io.swagger.jaxrs.listing.ApiListingResource.class);
register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.2");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8282");
beanConfig.setBasePath("/");
beanConfig.setResourcePackage("rest.addressbook");
beanConfig.setScan(true);
}
}
However, when going to my service in http://localhost:8282/swagger.json, I get this output.
You can check my public repo here.
It's times like this (when there is no real explanation for the problem) that I throw in an ExceptionMapper<Throwable>. Often with server related exceptions, there are no mappers to handle the exception, so it bubbles up to the container and we get a useless 500 status code and maybe some useless message from the server (as you are seeing from Grizzly).
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class DebugMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable exception) {
exception.printStackTrace();
if (exception instanceof WebApplicationException) {
return ((WebApplicationException)exception).getResponse();
}
return Response.serverError().entity(exception.getMessage()).build();
}
}
Then just register with the application
public ApplicationConfig(final AddressBook addressBook) {
...
register(DebugMapper.class);
}
When you run the application again and try to hit the endpoint, you will now see a stacktrace with the cause of the exception
java.lang.NullPointerException
at io.swagger.jaxrs.listing.ApiListingResource.getListingJson(ApiListingResource.java:90)
If you look at the source code for ApiListingResource.java:90, you will see
Swagger swagger = (Swagger) context.getAttribute("swagger");
The only thing here that could cause the NPE is the context, which scrolling up will show you it's the ServletContext. Now here's the reason it's null. In order for there to even be a ServletContext, the app needs to be run in a Servlet environment. But look at your set up:
HttpServer server = GrizzlyHttpServerFactory
.createHttpServer(uri, new ApplicationConfig(ab));
This does not create a Servlet container. It only creates an HTTP server. You have the dependency required to create the Servlet container (jersey-container-grizzly2-servlet), but you just need to make use of it. So instead of the previous configuration, you should do
ServletContainer sc = new ServletContainer(new ApplicationConfig(ab));
HttpServer server = GrizzlyWebContainerFactory.create(uri, sc, null, null);
// you will need to catch IOException or add a throws clause
See the API for GrizzlyWebContainerFactory for other configuration options.
Now if you run it and hit the endpoint again, you will see the Swagger JSON. Do note that the response from the endpoint is only the JSON, it is not the documentation interface. For that you need to use the Swagger UI that can interpret the JSON.
Thanks for the MCVE project BTW.
Swagger fixed this issue in 1.5.7. It was Issue 1103, but the fix was rolled in last February. peeskillet's answer will still work, but so will OP's now.
I have implemented web service:
#WebServiceClient(//parameters//)
#HandlerChain(file = "handlers.xml")
public class MyWebServiceImpl {...}
Also I have implemented ObjectFactory with list of classes for creating my requests and responses. For Example class Test.
I need to get xml of response.
I try to use JAX-WS SOAP handler, so I add this #HandlerChain(file = "handlers.xml") anotation.
My handlers.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
<handler-chain>
<handler>
<handler-class>java.com.webservice.service.LoggingHandler</handler-class>
</handler>
</handler-chain>
</handler-chains>
My LoggingHandler class is:
import java.io.PrintWriter;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class LoggingHandler implements javax.xml.ws.handler.soap.SOAPHandler<SOAPMessageContext> {
public void close(MessageContext messagecontext) {
}
public Set<QName> getHeaders() {
return null;
}
public boolean handleFault(SOAPMessageContext messagecontext) {
return true;
}
public boolean handleMessage(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean) smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
System.out.println("\nOutbound message:");
} else {
System.out.println("\nInbound message:");
}
SOAPMessage message = smc.getMessage();
try {
PrintWriter writer = new PrintWriter("soap_responce" + System.currentTimeMillis(), "UTF-8");
writer.println(message);
writer.close();
message.writeTo(System.out);
System.out.println(""); // just to add a newline
} catch (Exception e) {
System.out.println("Exception in handler: " + e);
}
return outboundProperty;
}
}
I have test class which creates request, here are part of code:
MyWebServiceImpl impl = new MyWebServiceImpl(url, qName);
ws = impl.getMyWebServicePort();
Test req = new Test();
I suppose to get xml response in file "soap_responce" + System.currentTimeMillis(). But such file isn't even created. Please suggest how to get xml response, I'm new to web services and may do something wrong. Thanks
Using SOAP handlers is IMHO perfectly fine for such a task. I would approach it the same way.
I was able to use your configuration with minor modifications to get the example running. As a result I am able to see generated files. If you can't see them please check whether you check correct path, e.g. using:
File file = new File("soap_responce" + System.currentTimeMillis());
System.out.println(file.getAbsolutePath());
What I changed is:
package from java.com.webservice.service.LoggingHandler to com.webservice.service.LoggingHandler as packages starting with java are forbidden
Complete project can be found here:
https://github.com/destin/SO-answers/tree/master/SO-how-get-xml-responce-using-jax-ws-soap-handler
org.dpytel.jaxws.jaxws_java_first_jboss.client.Main class shows how I get and execute the web service.
BTW. you don't need to implement client stub and object factory etc when you have WSDL file. You can use wsimport tool. You can check how to use it in mentioned project.
So here is my source code :
import com.jaspersoft.mongodb.MongoDbConnection;
import com.jaspersoft.mongodb.MongoDbDataSource;
import java.io.File;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
public class Generate {
public static void main(String[] args) throws UnknownHostException {
try {
// - Connexion à la base
String mongoURI = "mongodb://localhost/test";
MongoDbConnection connection = null;
Map<String, Object> parameters = new HashMap<String, Object>();
try {
connection = new MongoDbConnection(mongoURI,null,null);
parameters.put(MongoDbDataSource.CONNECTION, connection);
JasperDesign jasperDesign = JRXmlLoader.load("/home/test/gocoffee.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
File jasperFile;
jasperFile = new File("/home/test/MongoDbReport.jasper");
JasperCompileManager.compileReportToFile("/home/test/gocoffee.jrxml", "/home/test/MongoDbReport.jasper");
JasperFillManager.fillReportToFile("/home/test/MongoDbReport.jasper", parameters);
JasperExportManager.exportReportToPdfFile("/home/test/MongoDbReport.jrprint");
} catch(Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Mongo is running.
I have gocoffee.jrxml in my folder named "test" and when I compile I get BUILD SUCCESSFUL but no pdf file appears in my "test" folder.
Interesting fact : if i do a
System.out.print("123");
after this line :
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
It doesn't work.
(I just fixed this error before this one. Maybe its related)
Thanks !
Ps: mdahlman you are awesome
A report working in iReport but failing in your application that uses JasperReports probably means that you're missing the query executer. Create jasperreports.properties (or edit your existing one), make sure it's on the classpath, and add this line:
net.sf.jasperreports.query.executer.factory.MongoDbQuery=com.jaspersoft.mongodb.MongoDbQueryExecuterFactory
Note1: You should look at the working unit test (which uses this idea) in the source that's posted to jasperforge. That really ought to have all that you need.
Note2: We recently figured out that it's a hassle to have to do this, so we updated the connector to have a copy of jasperreports_extension.properties which performs the same role. But then it's included in the connector .jar file, so you don't have to worry about it. That will be posted soon.