Error Invoking a Method on a DataSource MBean - connection

I'm sure I'm going about this in completely the wrong way, but can someone point out the error in the code below...
MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer (null).get (0);
ObjectName mBean = new ObjectName ("Catalina:type=DataSource,path=/<context>,host=localhost,class=javax.sql.DataSource,name=\"<name>\"");
String [] params = {"<username>", "<password>"};
Connection myConnection = (Connection) server.invoke (mBean, "getConnection", params, null);
Statement myStatement = myConnection.createStatement ();
String myResult = myStatement.executeQuery ("SELECT 1 FROM DUAL;").toString ();
myConnection.close ();
The problem is occurring when I try to instantiate the Connection object by invoking the getConnection method on my MBean. I receive the following error...
Aug 6, 2012 8:46:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalArgumentException: Inconsistent arguments and signature
at org.apache.tomcat.util.modeler.ManagedBean.getInvoke(ManagedBean.java:578)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:289)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(Unknown Source)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(Unknown Source)
What am I doing wrong?

I see you are doing:
Connection myConnection = (Connection) server.invoke (mBean, "getConnection",
params, null);
You are passing in null for the param signature array which I don't think is allowed. To quote the javadocs from MbeanServer.invoke(...):
#param signature An array containing the signature of the operation. The class objects will be loaded using the same class loader as the one used for loading the MBean on which the operation was invoked.
This array should hold the class names of the method parameters you are trying to invoke and they must match precisely. Primitive types should be passed in as the string "int", "long", ... while class types as "java.util.Date", "java.lang.String", ...
So I think you need to pass in something like:
String [] params = {"<username>", "<password>"};
String [] signatures = {"java.lang.String", "java.lang.String"};
Connection myConnection = (Connection) server.invoke (mBean, "getConnection",
params, signatures);

Related

Vaadin binder throw an exception on empty field

In my Vaadin (v.23.2.6) application I have a form tied up to Filter class which has 5 attributes.
All of them are optional, i.e. user can leave the blank.
public FilterPanel(ApiBookUtils api) {
this.api = api;
this.authorField = new ComboBox<Author>("Author Name");
this.countryField = new ComboBox<>("Country");
this.countryField.setReadOnly(true);
this.fromYear = new IntegerField ("From");
this.fromYear.setWidth("60px");
this.toYear = new IntegerField ("To");
this.toYear.setWidth("60px");
this.binder = new Binder(Filter.class);
this.setModal(true);
this.setCloseOnOutsideClick(false);
this.setCloseOnEsc(true);
buildDialog();
}
private void buildDialog() {
bindFields();
addFields();
setDialogListeners();
setDialogItems();
}
private void bindFields() {
this.binder.bind(authorField, Filter::getAuthor, Filter::setAuthor);
this.binder.forField(countryField).bind(Filter::getCountry, Filter::setCountry);
this.binder.forField(fromYear).bind(Filter::getFromYear, Filter::setFromYear);
this.binder.forField(toYear).bind(Filter::getToYear, Filter::setToYear);
this.binder.forField(postingDateField).bind(Filter::getPostingDate, Filter::setPostingDate);
this.binder.forField(tagField).bind(Filter::getTags, Filter::setTags);
}
I am getting getting exception if IntegerField is left blank.
com.vaadin.flow.data.binder.BindingException: An exception has been thrown inside binding logic for the field element [label='From']
at com.vaadin.flow.data.binder.Binder$BindingImpl.execute(Binder.java:1570) ~[flow-data-23.2.5.jar:23.2.5]
at com.vaadin.flow.data.binder.Binder$BindingImpl.writeFieldValue(Binder.java:1427) ~[flow-data-23.2.5.jar:23.2.5]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.lang.NullPointerException: null
at com.vaadin.flow.data.binder.Binder$BindingImpl.lambda$writeFieldValue$5169480d$1(Binder.java:1431) ~[flow-data-23.2.5.jar:23.2.5]
Does anybody know how to make binder to accept empty field and set up default value in the bean?
I found the workaround the bug in the Binder. Apparently, it does not process primitive types correctly. I have replaced int fields in my bean with Integer object and exception was gone.
If IntegerField is empty, the value is by definition null. If your business logic throws NPE due this, Binder will fail. You can set the binding to convert null value to your presentation by using withNullPresentation(defaultValue).
this.binder.forField(fromYear)
.withNullPresentation(0) // e.g. interpret null as zero
.bind(Filter::getFromYear, Filter::setFromYear);

Elasticsearch java RestHighLevelClient "Unable to parse response body" IllegalArgumentException: Required [index]

I'm dealing with a problem when creating an index using the java RestHighLevelClient in Elasticsearch and my CreateIndexResponse object is in consequence null.
I am actually able to create the index, which I can confirm later querying it, but when I create the index, I get this exception. Here my code:
`CreateIndexRequest request = new CreateIndexRequest("myindex");
CreateIndexResponse createIndexResponse = client.indices().create(request);`
Elasticsearch returns the message of success with:
`HTTP 200 Success
{
"acknowledged": true,
"shards_acknowledged": true
}`
And I am actually able to retrieve the index later with a GET call, but when the RestHighLevelClient tries to parse the response, using the following internal call:
//Type of the response converter: CheckedFunction<Req, Request, IOException> requestConverter
responseConverter.apply(response);
The following exception happens:
java.io.IOException: Unable to parse response body for
Response{requestLine=PUT /myindex?master_timeout=30s&timeout=30s HTTP/1.1,
host=http://localhost:9200, response=HTTP/1.1 200 OK}
at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:507)
at org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:474)
at org.elasticsearch.client.IndicesClient.create(IndicesClient.java:77)
at hello.client.HelloClient.createSynch(HelloClient.java:84)
at hello.main.Main.main(Main.java:25)
Caused by: java.lang.IllegalArgumentException: Required [index]
So basically what this is saying is that the following response cannot be parsed, but for me it looks pretty parsable:
Response{requestLine=PUT /myindex?master_timeout=30s&timeout=30s HTTP/1.1,
host=http://localhost:9200, response=HTTP/1.1 200 OK}
Why does it tell me that the index is missing? Is it that I'm using wrongly the java client? This is the version:
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.1</version>
</dependency>
</dependencies>`
Thanks in advance for the help!
You need to either update your version dependency or add compatibility headers (https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/) as for my case even latest version of Spring-data-elastic search doesn't support version 8+ of Elastic Search. Had to configure my client like this:
#Configuration
#EnableElasticsearchRepositories(basePackages = "*")
public class ElasticsearchClientConfig {
#Value("${elasticsearch.host}")
private String host;
#Value("${elasticsearch.port}")
private int port;
#Value("${elasticsearch.protocol}")
private String protocol;
#Value("${elasticsearch.username}")
private String userName;
#Value("${elasticsearch.password}")
private String password;
#Bean(destroyMethod = "close")
public RestHighLevelClient restClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
.setDefaultHeaders(compatibilityHeaders());
return new RestHighLevelClient(builder);
}
private Header[] compatibilityHeaders() {
return new Header[]{new BasicHeader(HttpHeaders.ACCEPT, "application/vnd.elasticsearch+json;compatible-with=7"), new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.elasticsearch+json;compatible-with=7")};
}
}

Rest Cypher query parameters - From .net to java

I am trying to send cypher query with parameters from .net to neo4j server with Rest method
i get this error :
Problem accessing /db/data/cypher. Reason:
java.lang.String cannot be cast to java.util.MapCaused by:
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
This is the Code :
DateTime startQueryTime = DateTime.Now;
RestClient restClient = new RestClient("http://localhost:7474/db/data/cypher");
restClient.AddDefaultHeader("Accept", "application/json");
restClient.AddDefaultHeader("Content-Type", "application/json");
JObject parameters1 = new JObject();
parameters.Add("startName", "Alon");
RestRequest restRequest = new RestRequest(); ;
restRequest.AddParameter("query", "START root=node:Node_Type(Type=\"Person\") where root.Person_Name = {startName} RETURN root limit 20");
restRequest.AddParameter("params", parameters1);
IRestResponse restResponse = restClient.Post(restRequest);
thanks in advance.
Alon
The result of your query is of the form Map<String,Object> instead of String. The result map contains the node property names as keys and its values represented as objects.
Examine your actual REST outgoing call and make sure the parameters map is not serialized to a String but a JSON Map structure.

Grails error using HttpServletResponse to export file for download

I am using opencsv in my Grails application to export attributes from my Person domain class to CSV. I am receiving the following error, however:
Servlet.service() for servlet [default] in context with path [/myapp] threw exception [Request processing failed; nested exception is org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException: Error processing GroovyPageView: getOutputStream() has already been called for this response] with root cause
Message: getOutputStream() has already been called for this response
From searching online, I think the answer may be to implement some responseComplete() method somewhere for the HttpServletResponse response. However, I am not sure how to do this. Any ideas? Here is my code:
def export = {
def course = Course.get(params.id)
if(course){
def persons = course ? Person.findAllByCourse(course) : []
response.setHeader("Content-disposition",
"attachment; filename=people.csv")
response.contentType = "text/csv"
def out = response.outputStream
out.withWriter { writer ->
String[] properties = new String[3]
def csvWriter = new CSVWriter(writer)
persons.each { person ->
properties[0] = person.firstName
properties[1] = person.lastName
properties[2] = person.email
properties[3] = person.phone
properties[4] = person.address1
properties[5] = person.address2
properties[6] = person.city
properties[7] = person.state
properties[8] = person.zip5
csvWriter.writeNext(properties)
}
csvWriter.flush()
}
}
Your problem probably stems from explicitly writing to the output stream in your controller, followed by the default behavior of GSP rendering upon returning from your action. You might check How to prevent Grails from rendering the default view? for another case of this, with a couple fixes. I don't have grails on the machine I'm on currently to recreate the issue, but sounds like adding an explicit return null to at the end of the closure may help. Or producing some token output or a 200 status code via render.
You have to change this proprity String[] properties = new String[3] by String[] properties = new String[9].
It works for me.

Sun sTax, JAXB and turning off validation against DTD/XSD/schema

We are using JAXB in conjuction with sTAX XMLEventReaderAPI to parse and extract data xml retrieved by making a REST Call.
InputStream responseStream = response.getEntityInputStream();
if (responseStream != null)
{
XMLInputFactory xmlif = XMLInputFactory.newInstance();
// stax API
XMLEventReader xmler = xmlif.createXMLEventReader(new InputStreamReader(responseStream));
EventFilter filter = new EventFilter() {
public boolean accept(XMLEvent event) {
return event.isStartElement();
}
};
XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
xmlfer.nextEvent();
// use jaxb
JAXBContext ctx = JAXBContext.newInstance(Summary.class);
Unmarshaller um = ctx.createUnmarshaller();
while (xmlfer.peek() != null) {
JAXBElement<CustomObject> se = um.unmarshal(xmler,
CustomObject.class);
CustomObject = se.getValue();
}
responseStream.close();
} else {
logger.error("InputStream response from API is null. No data to process");
}
response.close();
}
So Basically we parse using sTAX first then unarshall content using JAXB which unmarshalls it the CustomObject type. We do other stuff to this CustomObject type later.
However we ran into an issue as this chunk of code executes on JBoss AS 6.1.0.Final
We get an exception saying "The declaration for the entity "HTML.version" must end with '>'"
It appears that either sTAX or JAXB is validating against a DTD/XSD. The XSD is defined on the same server to which the REST call is made.
Because we are using SUN sTAX and not woodstox that there is no inherent DTD/XSD Validation that comes with it. There is no validation and the error cannot come from the sTAX call
Is that correct ?
If the issue is not validation failure with sTAX it has got to be JAXB.
However I cannot do the following:
um.setValidating(false);
because setValidating is a deprecated method.
Any ideas/suggestions on how to go about this ? Is our hypothesis correct ? Is this a known JBoss Issue perhaps ?

Resources