Update: Simplified example and changed my question.
With the following code when the keyword is found it retrieves data but when I use a keyword which is not in the data it gives me org.apache.solr.common.SolrException: missing content stream
class SearchBean
{
public void query(String q) throws IOException
{
HttpSolrServer server = null;
try
{
server = new HttpSolrServer("http://localhost:8080/solr/");
}
catch(Exception e)
{
e.printStackTrace();
}
SolrQuery query = new SolrQuery();
query.setQuery(q);
query.setFacet(true);
query.addFacetField("name");
query.addFacetField("title");
try
{
QueryResponse rsp = server.query(query);
SolrDocumentList docs = rsp.getResults();
List<ExampleBean> beans = rsp.getBeans(ExampleBean.class);
server.addBeans(beans);
System.out.println("Found: " + docs.getNumFound());
System.out.println("Start: " + docs.getStart());
System.out.println("Max Score: " + docs.getMaxScore());
System.out.println("--------------------------------");
System.out.println(rsp.toString());
System.out.println("--------------------------------");
for(ExampleBean example:beans){
System.out.println(example.getName().toString());
}
}
catch (SolrServerException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException
{
SearchBean solrj = new SearchBean();
solrj.query("test");
}
}
I have indexed my data and imported to solr via data-config.xml
Related
I'm new to the quarkus framework where I'm writing rabbitmq-client library based on quarkur framework. I'm using io.quarkiverse.rabbitmqclient.RabbitMQClient.
I need to write JUnit for basic send and consume operations, please help me with how can I write junit and mock RabbitMQClient. I'm using the below code to send and consume message.
#ApplicationScoped
public class RabbitMQProducerAdapterImpl extends RabbitMQCongiguration implements RabbitMQProducerAdapter {
#Override
public void sendMessage(String exchange, String routingKey, String messagePayload) throws IOException {
setUpConnectionAndChannel();
channel.basicPublish(exchange, routingKey, null, messagePayload.getBytes(StandardCharsets.UTF_8));
Log.info("message sent succefully: " + messagePayload);
}
}
Here is the RabbitMQCongiguration
#ApplicationScoped
public class RabbitMQCongiguration {
#Inject
private RabbitMQClient rabbitClient;
protected Channel channel;
protected void setUpConnectionAndChannel() {
try {
// create a connection
Connection connection = rabbitClient.connect();
// create a channel
channel = connection.createChannel();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
protected void setupQueueInDirectExchange(String exchangeName, String routingKey, String queueName,
boolean createExchangeQueues) throws IOException {
setUpConnectionAndChannel();
if (createExchangeQueues) {
this.channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, null);
// declaring a queue for this channel. If queue does not exist,
// it will be created on the server. this line not needed if queue already
// present
this.channel.queueDeclare(queueName, true, false, false, null);
}
// Bind Routing Key to Exchange
this.channel.queueBind(queueName, exchangeName, routingKey);
}
}
Below is the class for consumer
#ApplicationScoped
public class RabbitMQConsumerAdapterImpl extends RabbitMQCongiguration implements RabbitMQConsumerAdapter, Runnable {
private String queueName;
private MessageProcessor messageProcessor;
#Override
public void consumeMessage(String exchange, String queueName, String routingKey,
MessageProcessor messageProcessor) throws IOException {
Log.info("starting consumer...");
try {
this.queueName = queueName;
this.messageProcessor = messageProcessor;
Log.info("setting up rabbitMQPrefetchCountConfig");
setupQueueInDirectExchange(exchange, routingKey, queueName, false);
Thread consumerThread = new Thread(this);
consumerThread.start();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#Override
public void run() {
try {
// start consuming messages. Auto acknowledge messages.
Log.info("Start consuming messages from thread...");
channel.basicConsume(this.queueName, false, (Consumer) new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String msgPayload = null;
if (body == null || body.length == 0) {
Log.warn("Invalid Message Body - Consumer Tag : " + consumerTag + ", Message DeliveryTag : "
+ envelope.getDeliveryTag());
channel.basicReject(envelope.getDeliveryTag(), false);
} else {
msgPayload = new String(body);
try {
JsonParser.parseString(msgPayload);
} catch (JsonSyntaxException ex) {
Log.error(msgPayload + " is not a valid json, Reason - ", ex);
channel.basicReject(envelope.getDeliveryTag(), false);
Log.warn("Rejected the current payload.");
return;
}
messageProcessor.processMessage(msgPayload);
channel.basicAck(envelope.getDeliveryTag(), false);
}
// just print the received message.
Log.info("Received: " + new String(body, StandardCharsets.UTF_8));
}
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#ApplicationScoped
public class MessageProcessorImpl implements MessageProcessor{
#Override
public void processMessage(String messagePayload) {
Log.info("message consumed: " + messagePayload);
}
}
Can anyone can show me, with sample codes:
How to post JSON to a REST webservice; and
How to read the JSON response from the server;
Using Codename One?
Here is what i have tried which is returning bad request response from the server:
Button b1 = new Button("Add Staff");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
JSONObject json = new JSONObject();
try {
ConnectionRequest post = new ConnectionRequest(){
#Override
protected void postResponse() {
try {
json.put("firstname", fname.getText());
json.put("middlename", mname.getText());
json.put("lastname", lname.getText());
json.put("dob", dob.getText());
json.put("gender", gender.getSelectedItem().toString());
json.put("marital", marital.getSelectedItem().toString());
json.put("phone", phone.getText());
json.put("adds", adds.getText());
json.put("username", user.getText());
json.put("password", pass.getText());
json.put("lat", lat.getText());
json.put("long", lon.getText());
} catch (JSONException ex) {
ex.printStackTrace();
}
}
#Override
protected void readResponse(InputStream input) throws IOException {
}
};
post.setUrl("http://localhost:8093/halimatbank/cbs/staff");
post.setPost(true);
post.setContentType("APPLICATION/JSON");
post.addArgument("body", json.toString());
boolean show = Dialog.show("Add Staff", "Are you Sure you want to add this Staff", "Yes", "NO");
NetworkManager.getInstance().addToQueueAndWait(post);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(post.getResponseData()), "UTF-8"));
Map<String, Object> response = (Map<String, Object>)result.get("response");
Dialog.show("Staff Saved", ""+response, "OK","");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
postResponse() is invoked after the process completes. Not related to post itself. You want to override buildRequestBody which executes before. If I understand correctly you want the entire body to be the JSON and not an argument named "body" which is what you did...:
ConnectionRequest post = new ConnectionRequest(){
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.toString().getBytes("UTF-8"));
}
#Override
protected void readResponse(InputStream input) throws IOException {
// parse response data
}
};
post.setUrl("http://localhost:8093/halimatbank/cbs/staff");
post.setPost(true);
post.setContentType("application/json");
Hello everyone I'm getting this error:
Uncaught exception: java.lang.IllegalArgumentException: Port Number formatted badly
- com.sun.midp.io.j2me.sms.Protocol.openPrimInternal(), bci=209
- com.sun.midp.io.j2me.sms.Protocol.openPrim(), bci=4
- javax.microedition.io.Connector.open(), bci=47
- javax.microedition.io.Connector.open(), bci=3
- javax.microedition.io.Connector.open(), bci=2
- travel.entities.SendMessage$1.run(SendMessage.java:31)
- java.lang.Thread.run(), bci=5
when converting those two textfields to send them
public TextField tfDestination = new TextField("Destination","", 20, TextField.PHONENUMBER);
public TextField tfPort = new TextField("Port", "50001", 6, TextField.NUMERIC);
using this method:
public static void execute(final String destination, final String port, final String message) {
Thread th = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
try {
msgConnection = (MessageConnection) Connector.open("sms://:"+port+":"+destination);
TextMessage textMessage = (TextMessage)msgConnection.newMessage(MessageConnection.TEXT_MESSAGE);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}
I'm getting the error on this line:
msgConnection = (MessageConnection)Connector.open("sms://:"+destination+":"+port);
Anyone have an idea?
Your destination should come before port number.
Try this:
public static void execute(final String destination, final String port, final String message) {
Thread th = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
String address = "sms://:"+destination+":"+port;
try {
msgConnection = (MessageConnection) Connector.open(address);
TextMessage textMessage = (TextMessage) msgConnection.newMessage(MessageConnection.TEXT_MESSAGE);
textMessage.setAddress(address);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}
I would like to run a task during the waiting of a web request. If the task finishes before the request can return a response, then I would display a message "The server is taking too long". I'm using a WebClient object, how can I manage the time out?
public Class Result
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("critere", out sCritere))
{
try
{
_datamanager = new DataManager();
_datamanager.m_evt_Client_DownloadStringCompleted += OnDownloadStringCompleted;
_datamanager.DownloadXmlData(DataManager.URL_RECHERCHE, sCritere);
//HERE I NEED TO RUN A TIMER If the response is too long i would display a message
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
NavigationService.GoBack();
NavigationService.RemoveBackEntry();
}
}
}
}
public Class DataManager
{
public void DownloadXmlData(string uri, string critere = "")
{
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.Credentials = new NetworkCredential(UserSaved, PasswordSaved, domain);
client.DownloadStringAsync(new Uri(uri + critere));
}
catch(WebException )
{
throw new WebException(MyExceptionsMessages.Webexception) ;
}
catch (Exception )
{
throw new UnknowException(MyExceptionsMessages.UnknownError);
}
}
public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//raise Downloadstringcompleted event if error==null
}
}
You can use BackgroundWorker..
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
// your task to do while webclient is downloading
};
bw.RunWorkerCompleted += (s, e) =>
{
// check whether DownloadStringCompleted is fired or not
// if not, cancel the WebClient's asynchronous call and show your message.
client.CancelAsync();
MessageBox.Show("message");
}
client.DownloadStringAsync(uri);
bw.RunWorkerAsync();
I have to process an xml against an xslt with result-document that create many xml.
As suggested here:
Catch output stream of xsl result-document
I wrote my personal URI Resolver:
public class CustomOutputURIResolver implements OutputURIResolver{
private File directoryOut;
public CustomOutputURIResolver(File directoryOut) {
super();
this.directoryOut = directoryOut;
}
public void close(Result arg0) throws TransformerException {
}
public Result resolve(String href, String base) throws TransformerException {
FileOutputStream fout = null;
try {
File f = new File(directoryOut.getAbsolutePath() + File.separator + href + File.separator + href + ".xml");
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new StreamResult(fout);
}
}
that get the output directory and then saves here the files.
But then when I tested it in a junit I had some problems in the clean-up phase, when trying to delete the created files and noticed that the FileOutputStream fout is not well handled.
Trying to solve the problem gave me some thoughts:
First I came out with this idea:
public class CustomOutputURIResolver implements OutputURIResolver{
private File directoryOut;
private FileOutputStream fout
public CustomOutputURIResolver(File directoryOut) {
super();
this.directoryOut = directoryOut;
this.fout = null;
}
public void close(Result arg0) throws TransformerException {
try {
if (null != fout) {
fout.flush();
fout.close();
fout = null;
}
} catch (Exception e) {}
}
public Result resolve(String href, String base) throws TransformerException {
try {
if (null != fout) {
fout.flush();
fout.close();
}
} catch (Exception e) {}
fout = null;
try {
File f = new File(directoryOut.getAbsolutePath() + File.separator + href + File.separator + href + ".xml");
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new StreamResult(fout);
}
}
So the fileOutputStream is closed anytime another one is opened.
But:
1) I don't like this solution very much
2) what if this function is called in a multithread process? (I'm not very skilled about Saxon parsing, so i really don't know..)
3) Is there a chance to create and handle one FileOutputStream for each resolve ?
The reason close() takes a Result argument is so that you can identify which stream to close. Why not:
public void close(Result arg0) throws TransformerException {
try {
if (arg0 instanceof StreamResult) {
OutputStream os = ((StreamResult)arg0).getOutputStream();
os.flush();
os.close();
}
} catch (Exception e) {}
}
From Saxon-EE 9.5, xsl:result-document executes in a new thread, so it's very important that the OutputURIResolver should be thread-safe. Because of this change, from 9.5 an OutputURIResolver must implement an additional method getInstance() which makes it easier to manage state: if your newInstance() method actually creates a new instance, then there will be one instance of the OutputURIResolver for each result document being processed, and it can hold the output stream and close it when requested.