How to turn off logging from docx4j-ImportXHTML - docx4j

When I use docx4j-ImportXHTML, I get a lot of logs.
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>3.3.1</version>
<exclusions>
<exclusion>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-ImportXHTML</artifactId>
<version>3.3.1</version>
</dependency>
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 52 - Warning: inserting missing 'title' element
InputStream: Document content looks like HTML 2.0
2 warnings, no errors were found!
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 651 - Warning: inserting missing 'title' element
InputStream: Document content looks like HTML 2.0
2 warnings, no errors were found!
org.docx4j.org.xhtmlrenderer.load INFO:: SAX XMLReader in use (parser): org.apache.xerces.parsers.SAXParser
org.docx4j.org.xhtmlrenderer.load INFO:: SAX XMLReader in use (parser): org.apache.xerces.parsers.SAXParser
org.docx4j.org.xhtmlrenderer.load INFO:: SAX XMLReader in use (parser): org.apache.xerces.parsers.SAXParser
org.docx4j.org.xhtmlrenderer.load INFO:: SAX XMLReader in use (parser): org.apache.xerces.parsers.SAXParser
org.docx4j.org.xhtmlrenderer.load INFO:: SAX XMLReader in use (parser): org.apache.xerces.parsers.SAXParser
org.docx4j.org.xhtmlrenderer.load INFO:: SAX XMLReader in use (parser): org.apache.xerces.parsers.SAXParser
org.docx4j.org.xhtmlrenderer.load INFO:: Loaded document in ~90ms
org.docx4j.org.xhtmlrenderer.load INFO:: TIME: parse stylesheets 241ms
org.docx4j.org.xhtmlrenderer.match INFO:: media = print
org.docx4j.org.xhtmlrenderer.match INFO:: Matcher created with 137 selectors
org.docx4j.org.xhtmlrenderer.load INFO:: SAX XMLReader in use (parser): org.apache.xerces.parsers.SAXParser
org.docx4j.org.xhtmlrenderer.load INFO:: Loaded document in ~3ms
org.docx4j.org.xhtmlrenderer.load INFO:: TIME: parse stylesheets 0ms
org.docx4j.org.xhtmlrenderer.match INFO:: media = print
org.docx4j.org.xhtmlrenderer.match INFO:: Matcher created with 137 selectors
How to turn that off? It's generating huge amounts of log entries on our appserver.

org.docx4j.org.xhtmlrenderer is org.xhtmlrenderer repackaged and extended for docx support; see https://github.com/plutext/flyingsaucer
flyingsaucer has its own logging system, independent of and different from docx4j (which uses slf4j).
You configure flyingsaucer's logging using xr.util-logging:
https://github.com/plutext/flyingsaucer/blob/master/src/conf/xhtmlrenderer.conf#L56
That file is typically included in your inside your docx4j-ImportXHTML jar: https://github.com/plutext/docx4j-ImportXHTML/blob/master/pom.xml#L255
So check inside that jar for the conf file, and alter it there.
For example, xr.util-logging.loggingEnabled=false

Simply create a new config file with properties you want to override and reference the new file under an environment variable.
Create a new conf file and put this in your app resources
i.e.
resources/conf/xr-overrides.conf
Add this property in your xr-overrides.conf file to disable logging
xr.util-logging.loggingEnabled = false
Add this property to your env vars to enable conf override with the lookup location
xr.conf=classpath:conf/xr-overrides.conf
Or
static {
System.setProperty("xr.conf","classpath:conf/xhtmlrenderer.conf");
}

instead of manipulating the jar, you can add the following line to your code:
XRLog.setLoggingEnabled(false);
It has to be a call before your initial call to the ImportXHTML library, but when it's loaded (first I tried to add it in main(), but it didn't work until I put it in the constructor of my class using the xhtml-import.
Bye
Jan-Patrick

It helped to copy xhtmlrenderer.conf from jar and put in project resources with modified line:
xr.util-logging.loggingEnabled = true

Related

Why is apache dtd for struts throwing errors

This morning several branches of a system I am working on all started to break with the following error messages:
(everything was fine last night)
[37m2018-09-12 11:55:34.733[0;39m [1;31mERROR[0;39m [37m--- [ main]
[0;39m [ ] 36mcom.opensymphony.xwork2.util.DomHelper
[0;39m : The markup declarations contained or pointed to by the document type declaration must be well-formed. at (-//Apache Software Foundation//DTD Struts Configuration 2.5//EN:1:3)
org.xml.sax.SAXParseException: The markup declarations contained or pointed to by the document type declaration must be well-formed.
The reference is in struts.xml which looks like the following:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts
Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
Going to the above url i get this message:
This page contains the following errors:
error on line 35 at column 2: StartTag: invalid
element name
Below is a rendering of the page up to the first
error.
Since this just started happening across several branches, some of which have not had any changes to their struts.xml file, I am guessing this is an apache problem. Anyone else seeing this?
I've got the same error just today.
Try using http-secure URL; "https://struts.apache.org/dtds/struts-2.5.dtd" as DTD.
But I don't clearly understand the true reason.
apache just posted that they fixed the issue
https://issues.apache.org/jira/browse/WW-4959

Weblogic 12.2.1.2 - How to tune the object Serializer to use Jackson 2 and strange phenomena on jaxrs enablement for application/json endpoints

On Weblogic JEE 7 (version 12.2.1.2), I am finding it quite strange to understand the behavior of the application server in relation to the enablement and configuration of the JAX-RS web services.
The first point that I am trying to understand is a phenomena that I find quite inexplicable.
On a sample application where I was testing a trivial jax-rs web service where initially there were only to components:
Component (A)
#ApplicationPath("rest")
public class RestApplication extends Application {
private static final Logger LOGGER = LoggerFactory.getLogger(RestApplication.class);
// Class loading
{
LOGGER.info("Rest application static constructor invoked");
}
/**
* Default not arguments constructor
*/
public RestApplication() {
LOGGER.info("Rest application default constructore invoked.");
}
}
Which appropriately enables the base context for all rest endpoints you may want to use in your deployment.
Works exactly as in Wildfly - 100%.
So nothing to say about this component.
And then we enter the "swamp", component B, our rest endpoint.
There are several dummy apis on this dummy endpoint, we focus just on the most trivial of all.
#Path("/exampleRestEndpoint")
#Consumes({ "application/json", "text/html" })
#Produces({ "application/json" })
public class ExampleRestEndpoint {
private static final Logger LOGGER = LoggerFactory.getLogger(ExampleRestEndpoint.class);
#PostConstruct
public void postConstruct() {
LOGGER.info("Rest Endpoint constructed.");
}
#GET
#Path("/ping")
public BasicJsonResponseDto<String> ping() {
Instant date = Instant.now();
return new BasicJsonResponseDto<String>("Ping-service invoked successfully. " + date.toString());
}
}
I will go into details on the DTO class later at the bottom.
There are already points of discussion here.
The first point of discussion for me is the the metadata annotation at the top of the class that declares that for this endpoint we want to deliver back to the clients application/json.
But on my first writing of this annotation, I had in fact not added ANY such anotation.
So on my first implementation, the application server was working returning me a reply.
On a second step, when I added the annotation stating that the rest endpoint was to be returing applicaiton/json, weblogic stopped rendering any response complaining of the following:
SEVERE: MessageBodyWriter not found for media type=application/json,
type=class com.jersey.jaxb.Todo, genericType=class
com.jersey.jaxb.Todo.
Same experiment on wildfly, the endpoint worked immediately no major hassle.
The following stack overflow thread yielded me an answer that worked:
test serializations REST JAXRS
The fact that weblogic would complain that it knows of know body writers that are capable of redering this mime type is suprising to me, being that any JEE 7 container should be able of doing this out of the box... but ok!
On my pom for the sample application I pumped the following dependencies to be going into war, in the Web-inf/lib.
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.8.6</version>
</dependency>
And problem solved.
The rest web service goes back to working.
On chrome I can control the http response metadata all perfect.
Funy thing now, when I deploy the same application and take away the jackson provider library, the rest endpoint continues to work without any problems.
Actually, I can no longer reproduce on my environment the weblogic complaint that I am not giving him any body writer that knows what to do with application/json replies.
So, this is my first question?
Does anybody know if for a basic rest service that deliver application/json where a sample application bundles no jackson library and jus uses jee7 apis, if weblogic is expected to be logging the error I quoted or not.
Does anybody have any sort of oncept/explanation for the fact that when I take away the dependencies things are just working as one would normally have expected from the start ... but not as one expect after having been forced to google a solution for the no body writer problem?
I really do not have an explanation for this...
Now the second point is to do with the class being used a return object on the /ping API i have quoted.
Originally, that endpoing API was returning a pure "String".
The ping message was not being wrapped in any sort of object.
And of course the result object was no real JSON object The return object was just a "some arbitrary string value".
So this of course is a problem for a rest client, that is expecting to de-serialize valid json and instead of getting an object or array, is getting pure raw data on the pipe.
For this reason, I then made the experiment of pumping the raw types like String and Integer under a support dto object.
Here is the implementation.
The implementation is important for the next question.
#JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "class")
public class BasicJsonResponseDto<T> implements Serializable {
T value;
public BasicJsonResponseDto() {
super();
}
public BasicJsonResponseDto(T value) {
super();
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
#Override
public String toString() {
return "BasicJsonResponseDto [value=" + value + "]";
}
}
For the sharper eyes, it will be immediately be obvious that when a response object to an endpoint is delivered via a class like this, the "de-serialization" logic is not a trivial task at all.
This wrapper object for the basic types Integer/String has a little be of poison in there.
Namely, the value T where we pump our ping string into gives no help for the de-serialization engine to figure out what object it is to expect to read out.
So the ping service, technically, is not trivial at all for the client-side code.
With that said, I now have two very different behaviors on Weblogic and Wildfly.
And the different must be directly related with the serialization technology that each is using.
When the ping service is executed on weblogic, right now, the reponse objects I get are of the form:
{"value":{"type":"string","value":"Ping-service invoked successfully.
2017-08-12T09:08:45.455Z"}}
So you see that whatever ObjectMapper weblogic is using and that I have definitely not configured, is by default pumping additional metadata aboute the T value, namely declaring it as a string.
(a) It is very cute that this done without my asking, but then on the client side I need to create an ObjectMapper to de-serialize that can interpret that same object medata.
Most likely there is an adequate set of annotation such as #JsonInfo with #JsonSubtype that I can add to the T value field to make the de-serialization work on the client side, but in terms of the DTO object that I have written I have not asked for any such metadata to go out.
(b) You will also notice, if you know jackson, that there is missing information on the object as well.
namely, I do not see the class="full.qualified.name" to my object.
But I have made sure I requested this metadata to go out on the response json by pumping this annotation into the class.
#JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "class")
So my question here is:
(1) What library exactly is weblogic using to serialize my json
(2) What default configurations do they have in there
(3) I have pumped into my pom.xml the "jackson-jaxrs-json-provider" dependency that originally make my endpoint work.
I have looked at the source code of this library, and it looks to me like this library tries to be in charge of the rendering of the json responses.
It does have a CDI #Provide #Consumes(/) Produces(/), and if I enable the debugger I can see during deployment that the jackson-jaxrs-json-provider gets invoked.
What I cannot see happening in weblogic is the ObjectMapper of this class ever getting called.
it is if I cannot override whatever default behavior is in charge right now.
Does anybody understand the behavior.
Are there ways to put the beast on a leash and take control of the situation?
Or do I have to trivialize the code to such a degree where my String wrapped object is named" StringWrappedDto and the value field is trviailized into String value.
I hope not, but right now I am struggling with this.
Now, we switch to Wildfly 10.1.0.
On Wildfly 10.1.0, my experience is things are going rather more according to expectation.
(a) If you deploy a WAR with just the RestApplication and the Endpoint I have provided.
Things work out of the box.
No hassle, no messages of incapacity to render application/json.
You are set to start working without taking control of any configuration.
(b) If you for example want to override the rendering behavior for Json, you can define your own ObjectMapper provider.
E.g.
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
And this guy here, if you debug it, you can see it get called on every call to the Ping service.
So you can take charge of how the json response will be serialized, if you need such level of control.
To conclude, on wildfly, the JSON response I get is what I expect as illustrated in the following quote:
{"class":"entrypoint.rest.BasicJsonResponse","value":"Ping-service
invoked successfully. 2017-08-12T16:42:13.788Z"}
I have tried setting breakpoints on almost every classon from jackson 2 that is involved in serialization of data, and literrally nothing gets hit on weblogic.
So I am pretty certain, something in the wlserver/modules is getting used.
Anyone has an idea of how to force jackson2 declared as dependency to the war to get used for serializaton and kill whatever default behavior is right now taking place?
--
It now starts being clear what is happening in the rendering.
I have written the following unit test as an experiment:
#Test
public void serializeJerseyTest() throws JsonProcessingException, JAXBException {
// (a) class to be marshalled into json
BasicJsonResponseDto<String> objectToSerialize = new BasicJsonResponseDto<String>(
"Ping-service invoked successfully. " + Instant.now().toString());
// (b) setup a jaxbcontext
Map<String, Object> properties = new HashMap<String, Object>(3);
JAXBContext jc = JAXBContext.newInstance(BasicStringJsonResponseDto.class);
// (c) Marshall to system out
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.marshal(objectToSerialize, System.out);
}
And the output of the unit test looks quite familiar...
{
"value" : {
"type" : "string",
"value" : "Ping-service invoked successfully. 2017-08-12T19:33:05.834Z"
}
Oracle is using Moxy to make the json...
So now the question is, how do I make it use jackson2 instead?
I am sure there is a way. Proably to be found on the jersey documentation, which I believe by default will want to use Moxy.
For future, reference, I will be now posting a debug stack trace that speaks volumes.
All the code I was trying to debug and could not find out how because I wasll the the time trying to set breakpoints on jackson when the implementation was jersey + moxy all along.
So here is the answer to that.
I came to this stack trace for the most rediculous reason in the world.
Moxy out of the box canont deserialize the JSON object it is producing for this web service.
Can anyone understand this?
That moxy is serializing me som json on the POJO but then the unmarshall cannot properly unsmarshall the value field?
So here is the stack trace:
Daemon Thread [[ACTIVE] ExecuteThread: '4' for queue: 'weblogic.kernel.Default (self-tuning)'] (Suspended (breakpoint at line 51 in entrypoint.rest.ObjectAdapter))
entrypoint.rest.ObjectAdapter.marshal(java.lang.Object) line: 51
entrypoint.rest.ObjectAdapter.marshal(java.lang.Object) line: 1
org.eclipse.persistence.internal.jaxb.XMLJavaTypeConverter.convertObjectValueToDataValue(java.lang.Object, org.eclipse.persistence.sessions.Session, org.eclipse.persistence.oxm.XMLMarshaller) line: 178
org.eclipse.persistence.oxm.mappings.XMLAnyObjectMapping.convertObjectValueToDataValue(java.lang.Object, org.eclipse.persistence.sessions.Session, org.eclipse.persistence.oxm.XMLMarshaller) line: 652
org.eclipse.persistence.oxm.mappings.XMLAnyObjectMapping.convertObjectValueToDataValue(java.lang.Object, org.eclipse.persistence.core.sessions.CoreSession, org.eclipse.persistence.internal.oxm.Marshaller) line: 1
org.eclipse.persistence.internal.oxm.XMLAnyObjectMappingNodeValue.marshalSingleValue(org.eclipse.persistence.internal.oxm.XPathFragment, org.eclipse.persistence.internal.oxm.record.MarshalRecord, java.lang.Object, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.NamespaceResolver, org.eclipse.persistence.internal.oxm.record.MarshalContext) line: 72
org.eclipse.persistence.internal.oxm.XMLAnyObjectMappingNodeValue.marshal(org.eclipse.persistence.internal.oxm.XPathFragment, org.eclipse.persistence.internal.oxm.record.MarshalRecord, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.NamespaceResolver, org.eclipse.persistence.internal.oxm.record.MarshalContext) line: 65
org.eclipse.persistence.internal.oxm.XMLAnyObjectMappingNodeValue(org.eclipse.persistence.internal.oxm.NodeValue).marshal(org.eclipse.persistence.internal.oxm.XPathFragment, org.eclipse.persistence.internal.oxm.record.MarshalRecord, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.NamespaceResolver, org.eclipse.persistence.internal.oxm.record.MarshalContext, org.eclipse.persistence.internal.oxm.XPathFragment) line: 102
org.eclipse.persistence.internal.oxm.record.ObjectMarshalContext.marshal(org.eclipse.persistence.internal.oxm.NodeValue, org.eclipse.persistence.internal.oxm.XPathFragment, org.eclipse.persistence.internal.oxm.record.MarshalRecord, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.NamespaceResolver, org.eclipse.persistence.internal.oxm.XPathFragment) line: 59
org.eclipse.persistence.internal.oxm.XPathNode.marshal(org.eclipse.persistence.internal.oxm.record.MarshalRecord, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.NamespaceResolver, org.eclipse.persistence.internal.oxm.Marshaller, org.eclipse.persistence.internal.oxm.record.MarshalContext, org.eclipse.persistence.internal.oxm.XPathFragment) line: 443
org.eclipse.persistence.internal.oxm.XPathObjectBuilder.buildRow(org.eclipse.persistence.internal.oxm.record.XMLRecord, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.Marshaller, org.eclipse.persistence.internal.oxm.XPathFragment) line: 243
org.eclipse.persistence.internal.oxm.TreeObjectBuilder.buildRow(org.eclipse.persistence.internal.oxm.record.XMLRecord, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.XMLMarshaller, org.eclipse.persistence.internal.oxm.XPathFragment) line: 118
org.eclipse.persistence.internal.oxm.TreeObjectBuilder.buildRow(org.eclipse.persistence.internal.oxm.record.XMLRecord, java.lang.Object, org.eclipse.persistence.internal.core.sessions.CoreAbstractSession, org.eclipse.persistence.internal.oxm.Marshaller, org.eclipse.persistence.internal.oxm.XPathFragment) line: 1
org.eclipse.persistence.oxm.XMLMarshaller(org.eclipse.persistence.internal.oxm.XMLMarshaller<ABSTRACT_SESSION,CHARACTER_ESCAPE_HANDLER,CONTEXT,DESCRIPTOR,MARSHALLER_LISTENER,MEDIA_TYPE,NAMESPACE_PREFIX_MAPPER,OBJECT_BUILDER,SESSION>).marshal(java.lang.Object, org.eclipse.persistence.oxm.record.MarshalRecord, ABSTRACT_SESSION, DESCRIPTOR, boolean) line: 766
org.eclipse.persistence.oxm.XMLMarshaller(org.eclipse.persistence.internal.oxm.XMLMarshaller<ABSTRACT_SESSION,CHARACTER_ESCAPE_HANDLER,CONTEXT,DESCRIPTOR,MARSHALLER_LISTENER,MEDIA_TYPE,NAMESPACE_PREFIX_MAPPER,OBJECT_BUILDER,SESSION>).marshalStreamOrWriter(java.lang.Object, org.eclipse.persistence.oxm.record.MarshalRecord, ABSTRACT_SESSION, DESCRIPTOR, boolean) line: 1147
org.eclipse.persistence.oxm.XMLMarshaller(org.eclipse.persistence.internal.oxm.XMLMarshaller<ABSTRACT_SESSION,CHARACTER_ESCAPE_HANDLER,CONTEXT,DESCRIPTOR,MARSHALLER_LISTENER,MEDIA_TYPE,NAMESPACE_PREFIX_MAPPER,OBJECT_BUILDER,SESSION>).marshal(java.lang.Object, java.io.OutputStream, ABSTRACT_SESSION, DESCRIPTOR) line: 934
org.eclipse.persistence.oxm.XMLMarshaller(org.eclipse.persistence.internal.oxm.XMLMarshaller<ABSTRACT_SESSION,CHARACTER_ESCAPE_HANDLER,CONTEXT,DESCRIPTOR,MARSHALLER_LISTENER,MEDIA_TYPE,NAMESPACE_PREFIX_MAPPER,OBJECT_BUILDER,SESSION>).marshal(java.lang.Object, java.io.OutputStream) line: 877
org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(java.lang.Object, java.io.OutputStream) line: 496
org.glassfish.jersey.moxy.json.internal.ConfigurableMoxyJsonProvider(org.eclipse.persistence.jaxb.rs.MOXyJsonProvider).writeTo(java.lang.Object, java.lang.Class<?>, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap<java.lang.String,java.lang.Object>, java.io.OutputStream) line: 957
org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(javax.ws.rs.ext.WriterInterceptorContext, javax.ws.rs.ext.MessageBodyWriter) line: 265
org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(javax.ws.rs.ext.WriterInterceptorContext) line: 250
org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed() line: 162
org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(javax.ws.rs.ext.WriterInterceptorContext) line: 106
org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed() line: 162
org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(javax.ws.rs.ext.WriterInterceptorContext) line: 86
org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed() line: 162
weblogic.jaxrs.server.internal.ChunkedOutputWriter.aroundWriteTo(javax.ws.rs.ext.WriterInterceptorContext) line: 65
org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed() line: 162
org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(java.lang.Object, java.lang.Class<?>, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap<java.lang.String,java.lang.Object>, org.glassfish.jersey.internal.PropertiesDelegate, java.io.OutputStream, java.lang.Iterable<javax.ws.rs.ext.WriterInterceptor>) line: 1130
org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(org.glassfish.jersey.server.ContainerResponse) line: 711
org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(org.glassfish.jersey.server.ContainerResponse) line: 444
org.glassfish.jersey.server.ServerRuntime$Responder.process(org.glassfish.jersey.server.ContainerResponse) line: 434
org.glassfish.jersey.server.ServerRuntime$2.run() line: 329
org.glassfish.jersey.internal.Errors$1.call() line: 271
org.glassfish.jersey.internal.Errors$1.call() line: 267
org.glassfish.jersey.internal.Errors.process(java.util.concurrent.Callable<T>, boolean) line: 315
org.glassfish.jersey.internal.Errors.process(org.glassfish.jersey.internal.util.Producer<T>, boolean) line: 297
org.glassfish.jersey.internal.Errors.process(java.lang.Runnable) line: 267
org.glassfish.jersey.process.internal.RequestScope.runInScope(org.glassfish.jersey.process.internal.RequestScope$Instance, java.lang.Runnable) line: 317
org.glassfish.jersey.server.ServerRuntime.process(org.glassfish.jersey.server.ContainerRequest) line: 305
org.glassfish.jersey.server.ApplicationHandler.handle(org.glassfish.jersey.server.ContainerRequest) line: 1154
org.glassfish.jersey.servlet.WebComponent.serviceImpl(java.net.URI, java.net.URI, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) line: 471
org.glassfish.jersey.servlet.WebComponent.service(java.net.URI, java.net.URI, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) line: 425
org.glassfish.jersey.servlet.ServletContainer.service(java.net.URI, java.net.URI, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) line: 383
org.glassfish.jersey.servlet.ServletContainer.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) line: 336
org.glassfish.jersey.servlet.ServletContainer.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) line: 223
weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run() line: 286
weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run() line: 260
weblogic.servlet.internal.StubSecurityHelper.invokeServlet(javax.servlet.ServletRequest, javax.servlet.http.HttpServletRequest, weblogic.servlet.internal.ServletRequestImpl, javax.servlet.ServletResponse, javax.servlet.http.HttpServletResponse, javax.servlet.Servlet) line: 137
weblogic.servlet.internal.ServletStubImpl.execute(javax.servlet.ServletRequest, javax.servlet.ServletResponse, weblogic.servlet.internal.FilterChainImpl) line: 350
weblogic.servlet.internal.TailFilter.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) line: 25
weblogic.servlet.internal.FilterChainImpl.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) line: 78
weblogic.servlet.internal.RequestEventsFilter.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) line: 32
weblogic.servlet.internal.FilterChainImpl.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) line: 78
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(weblogic.servlet.internal.ServletStub, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) line: 3683
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run() line: 3649
weblogic.security.acl.internal.AuthenticatedSubject.doAs(weblogic.security.subject.AbstractSubject, java.security.PrivilegedAction) line: 326
weblogic.security.service.SecurityManager.runAsForUserCode(weblogic.security.acl.internal.AuthenticatedSubject, weblogic.security.acl.internal.AuthenticatedSubject, java.security.PrivilegedAction<T>) line: 197
weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(weblogic.security.acl.internal.AuthenticatedSubject, java.security.PrivilegedAction, weblogic.security.acl.internal.AuthenticatedSubject) line: 203
weblogic.servlet.provider.WlsSubjectHandle.run(java.security.PrivilegedAction) line: 71
weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(weblogic.servlet.internal.ServletInvocationContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, boolean, boolean) line: 2433
weblogic.servlet.internal.WebAppServletContext.securedExecute(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean) line: 2281
weblogic.servlet.internal.WebAppServletContext.execute(weblogic.servlet.internal.ServletRequestImpl, weblogic.servlet.internal.ServletResponseImpl) line: 2259
weblogic.servlet.internal.ServletRequestImpl.runInternal() line: 1691
weblogic.servlet.internal.ServletRequestImpl.run() line: 1651
weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run() line: 270
weblogic.invocation.ComponentInvocationContextManager._runAs(weblogic.invocation.ComponentInvocationContext, java.lang.Runnable) line: 348
weblogic.invocation.ComponentInvocationContextManager.runAs(java.security.Principal, weblogic.invocation.ComponentInvocationContext, java.lang.Runnable) line: 333
weblogic.work.LivePartitionUtility.doRunWorkUnderContext(java.lang.Runnable, weblogic.invocation.ComponentInvocationContext) line: 54
weblogic.work.PartitionUtility.runWorkUnderContext(java.lang.Runnable, weblogic.invocation.ComponentInvocationContext) line: 41
weblogic.work.ServerWorkManagerImpl(weblogic.work.SelfTuningWorkManagerImpl).runWorkUnderContext(weblogic.work.ExecuteThread, weblogic.work.WorkAdapter) line: 640
weblogic.work.ExecuteThread.execute(weblogic.work.WorkAdapter) line: 406
weblogic.work.ExecuteThread.run() line: 346
I believe I will now search for the way to use jackson on weblogic, there is simply no way that I am going to be working around this issue by pumping the class full of jaxB annotation and on top of that be writing XmlAdapters for this.
Jackson can do all of this for free.
That is why when needed, Jackson will writen the #class attribute with all the neded metadata for the class to deserialize.
It simply cannot be this bad. Cannot be.
I got the same problem recently on weblogic 12.2.1.3 and it was MOXy all the way. Even if I specified in my ear to user JAX-RI through services in META-INF, weblogic was still loading MOXy.
I succeded to disable it setting the property:
import org.glassfish.jersey.CommonProperties;
import org.glassfish.jersey.server.ResourceConfig;
#ApplicationPath("api")
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, Boolean.TRUE);
///.. the rest of my setup
}
}
Well,
Weblogic is implementing JAX-RS via Jersey.
According to the jersey documentation, it should be a simple matter of pumping a dependency into your deployment to do the swtich from Moxy to Jackson.
E.g
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.26-b09</version>
<scope>runtime</scope>
</dependency>
See the following reference.
https://jersey.github.io/documentation/latest/media.html#json
Seems not to be so trivial, to do the switch, my weblogic behavior was still reflecting the usage of Moxy, even once I added the library on the jersey documentaiton. Perhaps I tried with the wrong version... I am not going to find this out today.
Since quite honestly, my patience has reached its limit for this petty problem.
I have decide to go with the flow. Leave Jersey to its default behavior let it Moxy. I will not get in the way.
I find Moxy rather more verbose than jackson, and I do not particularly fancy having to be spreading around jaxb.properties files like mushrooms where folders containing rest DTOS.
jaxb.properties example:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
In any case, right now I want consistency to exist between the outcome of a rest call on Weblogic and Wildfly. No way I am going to be writing if app server is Weblogic de-serialize it with A and if it is wildfly deserialize it with B. No way!
So what I did was quite simple.
Wildfly uses restEasy. And rest easy is easy! :)
So i simply went to my web.xml
And pumped the following information:
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>org.eclipse.persistence.jaxb.rs.MOXyJsonProvider</param-value>
</context-param>
Thanks restEasy documentation, that was really helpful!
Finally, since I always use EclipseLink instead of Hibernate, the eclipselink module is already active whend df I startup wildfly. No need to activate it via jboss-deployment descriptor.xml.
However, the module was lacking sufficient metadata.
I had to pump into the module "org.eclipse.persistence" main.xml the following dependency:
<module name="javax.ws.rs.api" />
That means my module looks as follows:
<module xmlns="urn:jboss:module:1.3" name="org.eclipse.persistence">
<properties>
<property name="jboss.api" value="private"/>
</properties>
<resources>
<resource-root path="jipijapa-eclipselink-10.1.0.Final.jar"/>
<resource-root path="eclipselink-2.6.4.jar">
<filter>
<exclude path="javax/**" />
</filter>
</resource-root>
</resources>
<dependencies>
<module name="asm.asm"/>
<module name="javax.api"/>
<module name="javax.annotation.api"/>
<module name="javax.enterprise.api"/>
<module name="javax.persistence.api"/>
<module name="javax.transaction.api"/>
<module name="javax.validation.api"/>
<module name="javax.xml.bind.api"/>
<module name="org.antlr"/>
<module name="org.dom4j"/>
<module name="org.javassist"/>
<module name="org.jboss.as.jpa.spi"/>
<module name="org.jboss.logging"/>
<module name="org.jboss.vfs"/>
<!-- Add dependency on rest api -->
<module name="javax.ws.rs.api" />
</dependencies>
</module>
NOTE:
Just be careful maintaining such information, you want to automate hacking these files because you will lose track of this as time goes by.
Best is you create an installer for wildfly that given a vanilla zip does all your hacky tunings to the base metadata files, otherwise you are lost.
In any case, now Wildfly is rendering the output of rest calls based on Moxy and not based on Jackson.
This means I will have to refactor my rest client to be Moxy based, but quite honestly...
I am out of energy to struggle against weblogic.
I prefer Jackson, so much simpler and quicker to use, but hey... pick your battles right?
Editing informaiton:
some more information on weblogic:
On Weblogic, the following configuration is effective.
IF you write RestApplication class and override the public Map getProperties() you can add the following property:
proprties.put("jersey.config.server.disableMoxyJson", true);
And this will disable the Server behavior of using moxy and switch to jackson.
This has not effect on wildfly since only weblogic uses jersey and wildfly uses resteasy. Finally, to make a rest client you would do:
javax.ws.rs.client.ClientBuilder.newClient().register(Class.forName("org.glassfish.jersey.jackson.JacksonFeature"))
public class RestApplication extends Application {
#Override
public Map<String, Object> getProperties() {
Map<String, Object> map = new HashMap<>();
map.put("jersey.config.server.disableMoxyJson", true);
return map;
}
And also...
Remember to set proper headers in the HTTP-request.
I sent Http-Request without "Content-Type":"application/json" and the Weblogic webserver responded with 500 Internal Server Error.
Weblogic should have returned 400 Bad Request, but i dont think httpstatuscodes where so important for Oracle when they developed this webserver. Lol.

Unused properties in IntelliJ

I am having a problem with IntelliJ inspection: It is indicating that all of my properties are unused (see the image). This is untrue, because all my properties all correctly used in spring boot project. I am using IntelliJ Community Edition 2016.1.4
If you want to ignore all warnings in a specific file. We just have to add this at the first line :
# suppress inspection "UnusedProperty" for whole file
If you just want to ignore a warning for a single property, you can add this line before the property :
# suppress inspection "UnusedProperty"
Idea -> Preferences -> search "unused" or "Inspections" -> uncheck "Unused Property " under "Properties Files"
Maybe the plugin is not supporting this feature/annotation which Intellij is then able to resolve. But you could write your own method for that.
So you have to create a method which calls the method which is not capable of creating the connection. The created method has to make us of the #PropertyKey Annotation which will allow Intellij to see the connection for your method and resolve the not used problem you have.
private static final String BUNDLE_NAME = "application";
public static void newMethod(#PropertyKey(resourceBundle = BUNDLE_NAME) String key) {
oldMethod(key) //replace oldMethod with your method
}
By calling the method foo it will detect the property connection to the property file if your resources are allocatable.
newMethod("your.awesome.key")
add library to pom.xml file problem will be solved
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.2</version>
</dependency>
Use final String variable to define the property's key REGION_CONFIG_KEY,
Invoke the property's key in #Value("${" + REGION_CONFIG_KEY + "}",
So the problem will be fixed

Grails render PDF file

I am trying to render a PDF file in my web page but using the bellow syntax I get a weird characters combination.
render file: new File ("path/to/file.pdf"), fileName: 'myPdfFile.pdf'
Does anyone knows what do I have to add more than the line above?
Thanks
I don't think that Grails does this by default.
Take a look at PDF rendering plugins. This looks to be the freshest, but make sure it's compatible with your Grails version.
If You are using Grails 3, this could be the way to go.
Coincidentally, I had the same problem yesterday but with some differences. I had to get to load a PDF from a Grails form in a new tab, using POST method to access a PHP script which generates PDF according some variables.
Anyway, I recommend you to check your header. If you get the binary file, for example, then you must define the header. So, we have for example:
Controller/Action:
def generatesReport = {
def url = StaticContextService.app.config.grailsPath.urlLocalServer,
path = 'some/url/which/generates/this.pdf',
parameters = /* defining parameters bla bla bla */
def bytes = SendHttpService.getYourBinaryHere(url, path, parameters)
/* HERE IS MY ANSWER, properly */
response.setContentType('application/pdf')
response.setContentLength(bytes.length)
response.setHeader('Content-Disposition', 'inline; filename="yourPdfFile.pdf"')
ServletOutputStream outputStream = response.getOutputStream()
outputStream.write(bytes,0,bytes.length)
outputStream.flush()
outputStream.close()
} // end method
There are many ways to define the header, and so you need to verify which settings are better for your demand (:
Don't forget to add the necessary libraries for your dependencies. Cheers!
in Grails 3, you can simply do
render file: new File ("path/to/file.pdf")
Did you try your suggested plugin? I am not able to use this dependency in my project. 1.0.0 Version does not exist, there are 2.0.0, 2.0.2 and 2.0.3 versions - but project compilation fails when I try to use them.
I have tried to download git sources and run them - website is up, but I also see error below:
Grails Runtime Exception
Error Details
Error 404:
Servlet: grailsDispatcherServlet
URI: /
When I try to visit particular controller action it ends like this:
java.lang.reflect.InvocationTargetException
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at java.beans.Introspector.getPublicDeclaredMethods(Introspector.java:1337)
at java.beans.Introspector.getTargetMethodInfo(Introspector.java:1197)
at java.beans.Introspector.getBeanInfo(Introspector.java:426)
at java.beans.Introspector.getBeanInfo(Introspector.java:173)
at grails.plugins.rendering.document.RenderEnvironment.init(RenderEnvironment.groovy:31)

Index was outside the bounds of the array in #Scripts.Render

For each controller have a folder (with the same name controler), and for each action a script file.
For each file is creating a bundle following the pattern: "~/Scripts/Controllers/{controller-name}/{filename-without-extension}"
bundles.IncludePerFile(new DirectoryInfo(server.MapPath("~/Scripts/Controllers")), "~/Scripts/Controllers/{0}/{1}",
(dir,file) => string.Format("~/Scripts/Controllers/{0}/{1}", dir, Path.GetFileNameWithoutExtension(file)), "*.js");
IncludePerFile is an extension method I created to perform this task
Then one bundle for: ~/Scripts/Controllers/processos/pasta should exist!
And to confirm this:
So far so correct! The bundle exists!
Running app
When I run the application, the following error occurs:
Full image
Wrongly and inefficient to repair the error:
If I change this:
#Scripts.Render("~/Scripts/Controllers/processos/pasta")
to this:
#Scripts.Render("~/Scripts/Controllers/processos/pasta.js")
No error is generated. But the file is not minified since there is effectively a bundle. (I have already put in release mode and published application!)
Full error
Index was outside the bounds of the array.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Source Error:
Line 3: #section js {
Line 4: #*#Scripts.Render("~/Scripts/Controllers/processos/Pasta.js", "~/Scripts/Controllers/processos/display.js")*#
Line 5: #Scripts.Render("~/Scripts/Controllers/processos/pasta")
Line 6: #Scripts.Render("~/Scripts/Controllers/processos/display.js")
Line 7:
Source File: w:\Clients\creditoimobiliariobb\sistema\src\CreditoImobiliarioBB\CreditoImobiliarioBB.Web\Views\processos\display.cshtml Line: 5
Stack Trace:
[IndexOutOfRangeException: Index was outside the bounds of the array.]
System.String.get_Chars(Int32 index) +0
Microsoft.Ajax.Utilities.CssParser.Append(Object obj, TokenType tokenType) +402
Microsoft.Ajax.Utilities.CssParser.AppendCurrent() +74
Microsoft.Ajax.Utilities.CssParser.SkipToClose() +744
Microsoft.Ajax.Utilities.CssParser.SkipToEndOfStatement() +232
Microsoft.Ajax.Utilities.CssParser.ParseRule() +574
Microsoft.Ajax.Utilities.CssParser.ParseStylesheet() +1235
Microsoft.Ajax.Utilities.CssParser.Parse(String source) +897
Microsoft.Ajax.Utilities.Minifier.MinifyStyleSheet(String source, CssSettings settings) +419
System.Web.Optimization.CssMinify.Process(BundleContext context, BundleResponse response) +302
System.Web.Optimization.Bundle.ApplyTransforms(BundleContext context, String bundleContent, IEnumerable`1 bundleFiles) +207
System.Web.Optimization.Bundle.GenerateBundleResponse(BundleContext context) +355
System.Web.Optimization.Bundle.GetBundleResponse(BundleContext context) +104
System.Web.Optimization.BundleResolver.GetBundleContents(String virtualPath) +254
System.Web.Optimization.AssetManager.EliminateDuplicatesAndResolveUrls(IEnumerable`1 refs) +435
System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable`1 assets) +1029
System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat, String[] paths) +75
System.Web.Optimization.Scripts.RenderFormat(String tagFormat, String[] paths) +292
System.Web.Optimization.Scripts.Render(String[] paths) +51
I've had the same error in this question: StyleBundle Index was outside the bounds of the array
And answer is pretty simple: you have to update your Microsoft Web Optimization & WebGrease packages (at this time 1.1.2 & 1.6.0 versions)
I would verify that all the elements of your
IncludePerFile(new DirectoryInfo(server.MapPath("~/Scripts/Controllers")), "~/Scripts/Controllers/{0}/{1}",
(dir,file) => string.Format("~/Scripts/Controllers/{0}/{1}", dir, Path.GetFileNameWithoutExtension(file)), "*.js")
are putting in the created bundles exactly what you think they're putting in.
I got this error at run time when the wrong type of file is included within a bundle. i.e.
#Styles.Render("~/bundles/myStyleBundle");
actually contains a JavaScript file.
I had the same problem and when I tried different checking I found out that there is a selector in my css file like this that cause the problem:
.glyphicons-icon _:-o-prefocus,
.glyphicons-icon {
background-image: url(../images/glyphicons.png);
}
it seems that Microsoft.Ajax.Utilities.CssParser has a problem with _: css selector. I removed the line and it's working.
I just ran into a similar problem. I am using VS 2013 and MVC 5 and was updating to Bootstrap v3.0.1 in order to use a theme from Bootswatch. I updated everything using the latest Bootstrap download and the site seemed to work fine. I then grabbed the CSS for Slate from the Bootswatch site and used it in the new stylesheet, changed it in the StyleBundle and built solution. When I ran it, I got the "Index was outside the bounds of the array" error. Switch back to bootstrap.css and it worked fine.
I then used NuGet Package Manager to update all my packages... I had just installed VS 2013 and not yet updated everything. Rebuilt the solution and wallah, it works great. So I would up vote the updating your packages answser.
You may need to update some of your nuget libraries. Try updating WebGrease
I'm using
#Scripts.Render()
For me it was an issue with the backtik in JS file.
Sample 1
let something = `some text
bla bla
`;
Above code thrown this exception
Index and length must refer to a location within the string.
Sample 2
let something = `some text
bla bla`;
Now it works well, so do not keep the closing backtik at the beginning new line ...