send message to mobile api j2me - exception

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();
}

Related

How can I mock RabbitMQClient of io.quarkiverse.rabbitmqclient.RabbitMQClient and write junit for basic send and consume operation?

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);
}
}

How to post JSON to a REST webservice in codenameone

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");

JavaFX, SceneBuilder, Populating TableView with MySQL Result Set

I have finally overcome my issue with a NPE in my code whilst learning FX/FXML. I now however have a different problem, a window opens with my TableView however there is no content in the table at all. As you cann I have printed out the JobList to make sure there is content being returned, and this returns three jobs (the correct amount). Am I missing something that binds the table to the returned list?
Here is the code;
public class SecondInterface implements Initializable {
private JobDataAccessor jAccessor;
private String aQuery = "SELECT * FROM progdb.adamJobs";
private Parent layout;
private Connection connection;
#FXML
TableView<Job> tView;
public void newI(Connection connection) throws Exception {
Stage primaryStage;
primaryStage = MainApp.primaryStage;
this.connection = connection;
System.out.println(connection);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Test1.fxml"));
fxmlLoader.setController(this);
try {
layout = (Parent) fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
primaryStage.getScene().setRoot(layout);
}
public Parent getLayout() {
return layout;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
jAccessor = new JobDataAccessor();
try {
System.out.println("This connection: " + connection);
System.out.println("This query: " + aQuery);
List<Job> jList = jAccessor.getJobList(connection, aQuery);
for (Job j : jList) {
System.out.println(j);
}
tView.getItems().addAll(jAccessor.getJobList(connection, aQuery));
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Android ListView Volley FATAL EXCEPTION error

I'm developing an Android App and i create a slide menu. In the slide menu i have item "Search". This is a fragment that call a json (using volley) and input the result into custom list view.
Now when i call the fragment (using debug mode) the fragment start to download some data but after some record of json download the app crash and i receive this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.firstproject.fragment.SearchFragment.loadListView(SearchFragment.java:175)
at com.firstproject.fragment.SearchFragment.access$000(SearchFragment.java:46)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:105)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:98)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
I attach my code where i call a json file (for privacy delete the url json)
Any help please?
Thanks
public class SearchFragment extends Fragment {
public SearchFragment(){}
private static final String url = "http://<server_name>/<folder>/data.json";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false);
}
ListView geoJSON;
String globalResponse="";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String tag_string_req = "string_req";
final ProgressDialog pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue mRequestQueue;
Network network = new BasicNetwork(new HurlStack());
//Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Instantiate the RequestQueue with the cache and network.
Cache cache = AppController.getInstance().getRequestQueue().getCache();
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
Cache.Entry entry = cache.get(url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
//loadListView(gobalResponse,0,1000);
//Toast.makeText(getActivity(), "Cache utilized!", 0).show();
// handle data, like converting it to xml, json, bitmap etc.,
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
// Cached response doesn't exists. Make network call here
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
globalResponse=response;
Globals.GlobalResponse=globalResponse;
Log.d("", response.toString());
loadListView(globalResponse,0,1000);
//loadListView(response,0,1000);
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(), error.getMessage()+"", 0).show();
pDialog.hide();
}
});
strReq.setShouldCache(true);
//strReq.
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private ArrayList<GeoJsonResponse> globalResponseObject;//=new ArrayList<GeoJsonResposne>();
private void loadListView(String response,float lowerLimit,float upperLimit)
{
try {
JSONObject featureCollection=new JSONObject(response);
globalResponseObject=new ArrayList<GeoJsonResponse>();
JSONArray features=featureCollection.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject properties=features.getJSONObject(i);
float mag=Float.parseFloat(properties.getJSONObject("properties").getString("mag"));
if(!(mag>=lowerLimit&&mag<upperLimit)) continue;
Log.d("",properties.getJSONObject("properties").getString("author")
+ properties.getJSONObject("properties").getString("mag")
+ properties.getJSONObject("properties").getString("place")
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)
);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = format.parse(properties.getJSONObject("properties").getString("time"));
GeoJsonResponse obj=new GeoJsonResponse(
properties.getJSONObject("properties").getString("eventId"),
properties.getJSONObject("properties").getString("author"),
properties.getJSONObject("properties").getString("place"),
Double.parseDouble(properties.getJSONObject("properties").getString("mag")),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)),
properties.getJSONObject("properties").getString("time"),date1,
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1))
);
globalResponseObject.add(obj);}
if(lowerLimit==0)
Globals.geoJsonResponse=globalResponseObject;
// Collections.sort(globalResponseObject, new DateSorter());
CustomListAdapter adpater=new CustomListAdapter(getActivity()
, globalResponseObject);
adpater.notifyDataSetChanged();
geoJSON.setAdapter(adpater);
geoJSON.invalidate();
geoJSON.invalidateViews();
//, author, place, magnitude, distance, date)
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Retrieving information from solrj in JSF

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