NetworkManager is APSupported - java

I want to consume a service. I am 100% sure that this service works correctly.
Service call
public void add(User user) {
ConnectionRequest con = new ConnectionRequest();
String url="http://localhost/NY/untitled/web/app_dev.php/user/new"
+ "?Fonctionuser="+user.getUserFunction()
+"&Fullname="+user.getUserName()
+"&Imageproduit="+user.getUserImage()
+"&Latitude="+user.getLatitude()
+"&Longitude="+user.getLongitude()
+"&State="+user.getUserState();
System.out.println(user.getUserState());
con.setUrl(url);
NetworkManager.getInstance().addToQueue(con);
}
Error
Exception in thread "main" java.lang.NullPointerException
at com.codename1.io.NetworkManager.isAPSupported(NetworkManager.java:866)
at com.codename1.io.ConnectionRequest.<init>(ConnectionRequest.java:330)
at Services.UserServices.add(UserServices.java:18)
at Services.Main.main(Main.java:30)
Main method
public static void main(String[] args) {
User user = new User();
user.setLatitude(111);
user.setLongitude(111);
user.setUserFunction( UserFunction.Client.ordinal());
user.setUserImage("uezfniez");
user.setUserState((int)UserState.Hold.ordinal());
user.setUserName("jamel");
UserServices userServices = new UserServices();
userServices.add(user);
}

It seems you nedd to write your code in an Action Listener
registerButton.addActionListener(e -> {
con.setUrl("http://localhost/NY/untitled/web/app_dev.php/user/"
+ "new?Fonctionuser=2&Fullname=jamel&Imageproduit=uezfniez&Latitude=111&Longitude=111&State=2");
NetworkManager.getInstance().addToQueue(con);
});

I'm guessing that you invoked that code from the constructor or a static initializer which means the implementation of Codename One didn't finish initializing. No code that relies on implementation should be executed before the init(Object) method is invoked.
Action listeners happen well after that point and would thus work well in this case.

Related

How to instantiate, configure and use a lib/framework in a oo-application?

I decided to split the last part of that question here into a new question here: https://softwareengineering.stackexchange.com/questions/411738/extension-of-classes-where-to-put-behaviour-how-much-direct-access-is-allowe
If i have a lib and i want to use it, i wrote mostly a own class. This class has one method. In that there is the code how to instantiate the lib/framework. Sometimes there are a few more methods, with them i not only instantiate the class but use it. For example if i want to start a http-server i have there a start-method.
class Container
{
TheLib theLib;
public void init() //or a constructor
{
//some init of the theLib
}
public void start() //
{
theLib.doSomething(...)
theLib.doSomethingmore(...);
theLib.start(...);
}
//important!
public TheLib getTheLib()
{
return this.theLib; //after i started configured it and so on, i want of course use all methods,
which the lib have in some other parts in my application
}
}
But it seems not to be the best solution.
Are there any better solutions, that OO is?
Often i also use only one method, a own class for this seems to be here a big overhead?
Exposing the lib breaks encapsulation? Tell-Dont-Ask is also violated?
Everything depend on what you actually need or how you have access to your 'the lib' instance.
public class Container {
private TheLib theLib;
/* #1: Do you already created the instance before? */
public Container(TheLib theLib) {
this.theLib = theLib;
}
/* #2: Do you need to created the instance each time? */
public Container() {
this.theLib = new TheLib();
}
public void start() {
theLib.doSomething(...)
theLib.doSomethingmore(...);
theLib.start(...);
}
public TheLib getTheLib() {
return this.theLib;
}
public static void main(String[] args) {
/* #1 */
TheLib theLib = ...;
Container container = new Container(theLib);
/* #2 */
Container container = new Container();
/* Continue the flow of your program */
container.start();
container.getTheLib().doSomethingEvenMore();
}
}
Or maybe you actually need only one instance of your 'Container' class. In this case, you should look on how to make a singleton: Java Singleton and Synchronization
Anwser: Often i also use only one method, a own class for this seems to be here a big overhead?
Well, in Java, you cannot do formal programming like in C, so everything line of code that you write, or will be using, has to be in a class of some sort.
If your piece of code is small and don't really need an object, static function might do the work.

Serializing only works when called in static main method of JavaFX App class

I'm working on a project that uses JavaFX for the GUI (I know, non-serializable). I want to serialize objects such as my Users.
I'm not able to access the instance that JavaFX Application uses, but I have it associated in other classes.
For example - it is associated with my Controller class:
public class MyApp extends Application {
public void start(Stage stage){
// ... assume controller loaded
controller.setApp(this);
}
}
public class Controller {
MyApp app;
public setApp(MyApp app){
this.app = app
}
}
Now when I go to serialize an instance of MyApp, I'm having difficulty. I found a slight trick (option 1), but it feels a little messy. I'd much rather do option 2.
Option 1 [WORKS] - create an additional instance in the main method.
public class MyApp extends Application {
public void start(Stage stage){
// ... assume controller loaded
controller.setApp(this);
}
public static void main(String[] args){
MyApp app = new MyApp(); // this is a different instance than javafx instance.
launch(args)
app.users = Controller.getUsers();
writeApp(app);
}
public static void writeApp(PhotoApp photoApp) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(storeDir + File.separator + storeFile));
oos.writeObject(photoApp);
oos.close();
}
}
Thus, option 1 essentially creates a new instance and copies stuff back and forth from the actual instance in controller.
OPTION 2 [DOES NOT WORK] - serialize the instance associated with the controller (since that is the actual instance JavaFX is using)
public class Controller {
MyApp app;
public void setApp(MyApp app){
this.app = app
}
public void someAction(){
MyApp.writeApp(this.app);
}
}
When I do Option 2 I get errors saying Controller is not serializable. I understand that it is not (which is okay), but I don't get that error in Option 1. In both options I'm calling the same method with some instance of MyApp. I'm not sure why it works for Option 1 but not Option 2.
Any reason why one option works over the other? How do most people do serialization of some of their objects when they use JavaFX?

Install4j: how to check a RemoteCallable running unelevated

My installer is storing some information in a singleton class during the installation process. Now, I have noticed that in elevated action, the singleton class does not have the same instance. So far, I have not found any workaround/solution so that they share the same instance. So, I have decided to make sure that if anyone wants to get an instance of the singleton, they must call from an unelevated environment. Let's say the singleton looks like the following:
public class InvestigatorReport {
private final List<Report> reports = new ArrayList<>();
private final static InvestigatorReport INSTANCE = new InvestigatorReport();
private InvestigatorReport() {
MyLogger.logInfo(getClass(), "initiating...");
}
public static InvestigatorReport getInstance(Context context) {
if (context.hasBeenElevated()) {
throw new IllegalAccessError(
"this method must be called unelevated!");
}
return INSTANCE;
}
private boolean addReport(Report report) {
return reports.add(report);
}
}
But the problem is, There are some cases when I have to call this add report from an action class that is elevated. So I have tried the following in my elevated action class:
if (context.hasBeenElevated()) {
return (Boolean) context.runUnelevated(new RemoteCallable() {
#Override
public Serializable execute() {
return getInstance(context).addReport(report);
}
});
}
But, as you can see if I am passing the same context object from the elevated action class to the RemoteCallable class so, even though I am running the class unelevated, the context.hasBeenElevated() still returns true.
Is there any other way that I can check the elevation level other than the context? If you have any other better idea on preventing anyone from calling the singleton getInstance() method, I am all ears.
I would use a different pattern. Make all methods of your singleton static and wrap the data access with runUnelevated calls:
public static boolean addReport(Report report, Context context) {
context.runUnelevated(new RemoteCallable() {
#Override
public Serializable execute() {
InvestigatorReport.reports.add(report);
return null;
}
});
}
In that way, you can call the methods from both elevated and unelevated code without having to check anything at the call site.

How do I stop a webservice endpoint?

I understand that I need to call the stop() method using the endpoint.
But I am not sure how to call it.
Here's my code
public class Publish {
public static void main(String[] args) {
String address = "http://localhost:8483/cal";
Object implementor = new CalWebserviceImpl();
Endpoint endpoint = Endpoint.publish(address, implementor);
System.out.println(endpoint.isPublished());
endpoint.stop();
} // main
}
And this is the error I get:
Exception in thread "main" com.sun.xml.internal.ws.server.ServerRtException: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.ServerMgr.createContext(ServerMgr.java:117)
I assume that I am getting the error message because I am trying to (re-)publish the endpoint before stopping it.
I tried to create a new endpoint reference and use it to stop it.
Endpoint ep = Endpoint.create(implementor);
ep.stop();
But I am getting the same error message.
I am just unclear how to call the stop() the service. Please advise. Thank you!
Edit:
Here's another unsuccessful attempt:
package com.website.test;
import javax.xml.ws.Endpoint;
public class Unpublish {
Endpoint ep = null;
public static void main(String[] args) {
Unpublish up = new Unpublish();
up.run();
} // main
public void run(){
String address = "http://localhost:8483/cal";
Object implementor = new CalWebserviceImpl();
// my service is already running, I believe it's publish here that's causing the issue
ep = Endpoint.publish(address, implementor);
startWebService();
}
private void startWebService() {
if(ep.isPublished()){
System.out.println("Endpoint webservice is running!");
}
else{
ep.stop();
System.out.println("Endpoint webservice stopped!");
}
}
}

Problem with Apache's Java XMLRPC library

So i'm trying to get my Apache xmlrpc client/server implementation to play ball. Everything works fine except for one crucial issue:
my handler class (mapped through the properties file org.apache.xmlrpc.webserver.XmlRpcServlet.properties) reacts as it should but it's constructor is called at every method invocation. It would seem that the handler class is instantiated at each call which is bad because I have data stored in instance variables that I need to save between calls.
How do I save a reference to the instantiated handler so that I can access it's instance variables?
So, for anyone else who still wants to use XMLRPC here's how I fixed this issue:
http://xmlrpc.sourceforge.net/
far superior to apache xmlrpc, in my opinion.
This is standard behaviour of Apache XMLRPC 3.x. http://ws.apache.org/xmlrpc/handlerCreation.html:
By default, Apache XML-RPC creates a new object for processing each
request received at the server side.
However, you can emulate the behaviour of XMLRPC 2.x, where you registered handler objects instead of handler classes, using a RequestProcessorFactoryFactory. I have written a custom RequestProcessorFactoryFactory that you can use:
public class CustomHandler implements RequestProcessorFactoryFactory {
Map<Class<?>, RequestProcessorFactory> handlers =
Collections.synchronizedMap(
new HashMap<Class<?>, RequestProcessorFactory>());
#Override
public RequestProcessorFactory getRequestProcessorFactory(Class pClass)
throws XmlRpcException {
return handlers.get(pClass);
}
public void addHandler(final Object handler) {
handlers.put(handler.getClass(), new RequestProcessorFactory() {
#Override
public Object getRequestProcessor(XmlRpcRequest pRequest)
throws XmlRpcException {
return handler;
}
});
}
}
This can then be used with e.g. a XMLRPC WebServer like this
WebServer server = ...
PropertyHandlerMapping phm = new PropertyHandlerMapping();
server.getXmlRpcServer().setHandlerMapping(phm);
Custom sh = new CustomHandler();
phm.setRequestProcessorFactoryFactory(sh);
Object handler = ... /** The object you want to expose via XMLRPC */
sh.addHandler(handler);
phm.addHandler(serverName, handler.getClass());
Maybe something to do with javax.xml.rpc.session.maintain set to true?
I know this is a really old post but I managed to solve the problem with Apache's Java XML-RPC.
First, I thought this could be solved with singleton class in Java but it doesn't work and throws "illegal access exception".
These are what I have done:
public class XmlRpcServer {
private static JFrame frame = new JFrame();
private static JPanel pane = new JPanel();
public static XmlRpcServer singleton_inst = new XmlRpcServer();
public XmlRpcServer() {
// I kept the constructor empty.
}
public static void main(String[] args) throws XmlRpcException, IOException {
// In my case, I put the constructor code here.
// Then stuff for XML-RPC server
// Server Part
WebServer ws = new WebServer(8741);
PropertyHandlerMapping mapping = new PropertyHandlerMapping();
mapping.addHandler("SERVER", singleton_inst.getClass());
ws.getXmlRpcServer().setHandlerMapping(mapping);
ws.start();
////
}
// I called doTheJob() from python via XML-RPC
public String doTheJob(String s) throws XmlRpcException {
loop();
return s;
}
// It executed loop() forever
private static void loop() throws XmlRpcException {
// Actual work is here
}
But metaspace increases gradually:
I worked too much on this metaspace issue when looping forever in Java but I couldn't figure out a solution.

Categories