how can I get more error messages out of solrj SolrException - solr

When I send queries to Solr using solrj, I sometimes get SolrException's thrown. When I dig through the exception, it just says "Bad Request", and gives the HTTP return code (which is 400).
When I take the request URL and put it in my browser, I was able to see a richer error message. The browser displays an error message saying one of the fields names is not valid.
I would like to be able to capture this inside my log file. I was able to capture this by copying all the parameters to an Apache HTTP Client POST request (I'm using POST and not GET because GET made the URL too long) and re-executing the request, but this is inefficient. Is there a way to get error message out of SolrException directly?
Here's what I'm doing:
catch (SolrServerException e) {
if(e.getRootCause() instanceof SolrException) {
SolrException ee = (SolrException) e.getRootCause();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(SOLR_URL);
// copy params over
Iterator<String> iter = request.getParams().getParameterNamesIterator();
while(iter.hasNext()) {
String p = iter.next();
method.setParameter(p, request.getParams().get(p));
}
int statusCode;
try {
// re execute and display the error message
statusCode = client.executeMethod(method);
logger.error(method.getResponseBodyAsString());
} catch (Exception e1) {
// TODO Auto-generated catch block
}
}

These messages aren't available via SolrJ. You can see them in solr's log file, but there is no way to capture them in your client, since solr only returns the 400 error status with a generic message to the client :(

Related

Camel ActiveMQ replyTo Issues

Getting a exception when trying to use replyTo. Requirement is to receive reply from external queue . Not sure why I am getting timeout error, do I have to make any configuration changes or any code changes . Tried different ways, but it’s not working . Any help will be appreciated
I am reading file from folder, split the file and sending results to req queue and expecting a reply on req2
from("file://C:/pkuma1?fileName=request464.txt").routeId(messageType+"sasasas")
.split()
.tokenize("\\n")
.log(INFO,"i am initial")
.setHeader("JMSReplyTo", simple("req2"))
.inOut("amq://queue:req?replyTo=req2&preserveMessageQos=true&replyToType=Shared&receiveTimeout=250")
// .inOut("amq://queue:req")
.transform(constant("Bye Camel"))
.log(INFO,"msg id initial = ${in.header.JMSMessageId}")
.log(INFO,"corr id initial = ${in.header.JMSCorrelationID}")
.to("stream:out");
from("amq://queue:req")
.log(INFO,"i am second route")
.log(INFO,"msg id second route = ${in.header.JMSMessageId}")
.log(INFO,"corr id second route = ${in.header.JMSCorrelationID}");
.setHeader("JMSCorrelationID", simple("${in.header.JMSCorrelationID}"));
.transform(simple("Hello in second route ${in.body}"))
.process(exchange -> {
System.out.println(exchange);
System.out.println("route2");
});
//.end();
//.to("amq://queue:req2");
from("amq://queue:req2?disableReplyTo=true")
.log(INFO,"i am third route")
.log(INFO,"msg id third route = ${in.header.JMSMessageId}")
.log(INFO,"corr id third route = ${in.header.JMSCorrelationID}")
.setHeader("JMSCorrelationID", simple("${in.header.JMSCorrelationID}"))
.transform(simple("Hello ${in.body}"))
.process(exchange -> {
System.out.println(exchange);
System.out.println("route3");
System.out.println(exchange.getIn().getHeader("JMSCorrelationID"));
exchange.getIn().setBody("Hello ${in.body}");
exchange.getIn().setHeader(JmsConstants.JMS_DESTINATION, "");
exchange.getIn().setHeader("JMSReplyTo","");
exchange.getIn().setHeader("JmsDestination","");
exchange.getIn().setHeader("CamelJmsDestination","");
})
.to("stream:out")
.end();
Getting following error Timeout occurred after 120000 millis waiting for reply message with correlationID

I want me bot to send a message everytime it errors

I wanted to make it so everytime my bot had an error it would send the error in a channel but it does nothing
bot.on('error', function (err) {
bot.guilds.get("609118791854456860").channels.get("609118791854456865").send(err)
})
I don't believe Client emits an event called "error". This code here should catch all uncaught errors and send them in a channel of your choosing:
process.on("uncaughtException", e => {
console.error(e);
Client.channels.get("YOUR CHANNEL ID").send(e.stack.slice(0, 2000); //ensure the stack trace is not too long, messages are limited to 2000 characters
process.exit();
});
In this code snippet, I've named my new Discord.Client() instance Client, it seems you've named yours bot, so you can swap the two names.
According to the docs, the Error Event is calledwhenever the client's WebSocket encounters a connection error.I believe the key is connection error. So if this event is called, you are no longer connected or something is wrong with the connection. Therefore no message can be sent if it can't connect.
One workaround is what Cloud has in his answer, and use the process.on("uncaughtException", e => {})
But just in case the error is fatal and the bot can't connect. You should save the error to a .txt file so whenever the bot successfully re-connects, you send whatever is in that file to your desired channel. Then have the bot delete the file if it successfully sent the message.

CORS AWS using Lambda (JAVA)

I am using AWS API Gateway with a Java Lambda Backend.
Everything is peachy until a friend using Angular 4 is trying to make requests. He keeps getting:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at URL (Reason: CORS header
'Access-Control-Allow-Origin' missing).
I have enabled CORS via the gateway:
Despite this the error remains. What should I modify ?
Thanks.
Ian's Comments:
I use Output/Input Streams so my output, as per your comment I am trying as below but still no success. Any ideas ?
private void sendResponse(JSONObject body, int statusCode, OutputStream outputStream)
{
OutputStreamWriter writer;
JSONObject responseJson = new JSONObject();
JSONObject responseHeadersJson = new JSONObject();
responseHeadersJson.put("Access-Control-Allow-Origin","*");
responseHeadersJson.put("Access-Control-Allow-Headers","Content-Type");
responseJson.put("headers",responseHeadersJson);
responseJson.put("statusCode", statusCode);
responseJson.put("body", body.toJSONString());
try {
writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(responseJson.toJSONString());
writer.close();
} catch (IOException e) {
System.out.println("Outputstream Error "+e);
}}
I can see that you are using Proxy Resource.
That means you are controlling the response thats going back as well from your Lambda. CORS needs to be configured on the response as well by adding the origin header.
When you build the response you need to add the cors headers by passing the domain or *.
I have built a ResponseBuilder that you can use as an example:
https://github.com/ahpoi/commons-utils-sdk/blob/master/src/main/java/com/ahpoi/commons/utils/aws/lambda/model/proxy/response/ResponseBuilder.java
public ResponseBuilder originHeader(String domain) {
headers.put(ACCESS_CONTROL_ALLOW_ORIGIN, domain);
return this;
}
private void initDefaultHeaders() {
headers.put(ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type");
}
public Response build() {
this.initDefaultHeaders();
return new Response(statusCode, headers, body);
}
If you didn't use Proxy Resource, your configuration would have been enough.

Can I use one servlet to receive xmpp messages, and another to send them in App Engine?

Does the required servlet URL mapping (/_ah/xmpp/message/chat/) for the xmpp service restrict me to using only that servlet for both sending and receiving xmpp messages?
My application receives messages, adds them to an 'inQueue' for processing, and once processed, the results are added to an 'outQueue'. Ideally I'd like the worker servlet assigned to the outQueue to send the response.
I am using push queues and the servlets are obviously invoked by an HTTP POST request...
When I try to use the xmpp service to send the message from my outQueue worker ( which is obviously not mapped to /_ah/xmpp/message/chat/ ), it expectedly does nothing.
In the servlet mapped to /_ah/xmpp/message/chat/:
//Generate a Memcache key
String key = generateMemcacheKey(message);
//Serialize the message as xml using getStanza (for now, just put in the senderJID as string)
String senderJIDString = message.getFromJid().getId();
//Cache the message in Memcache
cache.put(key, senderJIDString);
//Enqueue a task for the message
private Queue queue = QueueFactory.getQueue("inQueue");
queue.add(TaskOptions.Builder.withUrl("/xmppParser").param("memcacheKey", key));
In xmppParser servlet doPost method:
//Extract message from memcache
String key = req.getParameter("memcacheKey");
String recipientJIDString = (String)cache.get(key);
//Todo Detect language
//Todo Parse Message into an Imperative accordingly (For now, just reply hello)
//Todo Handle Session status
//Put Imperative into memcache (For now, just put recipientID in)
cache.put(key, recipientJIDString);
//Enqueue appropriately
Queue queue = QueueFactory.getQueue("outQueue");
queue.add(TaskOptions.Builder.withUrl("/responseServlet").param("memcacheKey", key
));
Now I would like this responseServlet to send the reply:
//Get a handler on the memcache
MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
//Extract the key to the response from the request
String key = req.getParameter("memcacheKey");
//Extract the message from the memcache ( For now it's just the JID of the sender)
String recipientJIDString = (String)cache.get(key);
//Parse it into a message (For now just make a simple "I hear you" message)
JID recipientJID = new JID(recipientJIDString);
Message response = new MessageBuilder()
.withMessageType(MessageType.NORMAL)
.withRecipientJids(recipientJID)
.withBody("I hear you")
.build();
//Send the message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
xmpp.sendMessage(response);
The servlet mappings are all kosher, and the xmpp service is unable to send the message. It raises a null pointer exception, but the memcache viewer confirms the recipientJID is kosher as well... I'm guessing only the servlet mapped to /_ah/xmpp/message/chat/ is able to send messages, or am I wrong?
I am forced to test on the live site itself as XMPP does not seem to be supported by the development server, adding the possibility of my having overlooked some production environment configuration...
Much obliged!
ram

Gae Java - After getting Authorization Token (with ClientLogin) cannot fetch spreadsheet feed url with 2 http requests

I have a problem using google apps engine with google spreadsheet.
I Get the authorization token with another servlet (by google ClientLogin) and then i try to get the spreadsheet feed xml with GET request and Authorization header (as described by google documentation).
My servlet look like this:
public class My2Servlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
HTTPRequest tokenRequest = new HTTPRequest(new URL("http://localhost:8888/myGae/getauthtoken"), HTTPMethod.GET);
HTTPResponse tokenResponse = urlFetchService.fetch(tokenRequest);
String token = Utils.getText(tokenResponse.getContent()); /*this token is OK*/
HTTPRequest spreadsheetFeedRequest = new HTTPRequest(new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full"), HTTPMethod.GET);
spreadsheetFeedRequest.setHeader(new HTTPHeader("Authorization", "GoogleLogin auth=" + token));
HTTPResponse spreadsheetFeedResponse = urlFetchService.fetch(spreadsheetFeedRequest); /*here the problems!!!*/
String spreadsheetFeed = Utils.getText(spreadsheetFeedResponse.getContent());
resp.setContentType("text/plain");
resp.getWriter().println(spreadsheetFeed);
}
}
I can correctly have the token but when i try to do the second request to have the spreadsheet feed i have the error 400 Bad Request and if i retry to reload this error:
java.io.IOException: Could not fetch URL: https://spreadsheets.google.com/feeds/spreadsheets/private/full
It seems that only the first request work... in fact if I comment the second request and get the token then comment the first request and execute the second request with token hand-written I correctly have the spreadsheet feed xml output...
Why can't I perform two subsequent requests?
I have implemented google-oauth (3-legged) & used gdata client library. I am explaining only for FYI, as this not the solution but just a suggestion.
You can download it from here. See the documentation.
Then use the following code :
Get the Spreadsheet feed :
SpreadsheetFeed resultFeed = googleService.getFeed(feedUrl, SpreadsheetFeed.class);
if (resultFeed.getEntries().isEmpty()) {
out.println("<br/>|\tNo entries found.");
} else {
List<SpreadsheetEntry> spreadsheets = resultFeed.getEntries();
for (int i = 0; i < spreadsheets.size(); i++) {
SpreadsheetEntry entry = spreadsheets.get(i);
out.println("<br/>" + entry.getTitle().getPlainText());
}
}

Resources